python弹球小游戏

import pygame
import random

# 游戏窗口大小
WIDTH = 800
HEIGHT = 600

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)


# 球的类
class Ball:
    def __init__(self):
        self.radius = 10
        self.speed = [random.randint(2, 4), random.randint(2, 4)]
        self.color = RED
        self.rect = pygame.Rect(400, 300, self.radius * 2, self.radius * 2)

    def move(self):
        self.rect.move_ip(self.speed[0], self.speed[1])

        # 球碰到边界反弹
        if self.rect.left <= 0 or self.rect.right >= WIDTH:
            self.speed[0] = -self.speed[0]

        if self.rect.top <= 0 or self.rect.bottom >= HEIGHT:
            self.speed[1] = -self.speed[1]

    def draw(self, screen):
        pygame.draw.circle(screen, self.color, self.rect.center, self.radius)


# 初始化pygame
pygame.init()

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("壁球小游戏")

# 创建球对象
ball = Ball()

# 游戏主循环
running = True
clock = pygame.time.Clock()

while running:
    # 处理退出事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 移动球
    ball.move()

    # 绘制背景
    screen.fill(BLACK)

    # 绘制球
    ball.draw(screen)

    # 更新屏幕
    pygame.display.flip()

    # 控制游戏帧率
    clock.tick(60)

# 退出游戏
pygame.quit()

python弹球小游戏_第1张图片

你可能感兴趣的:(python,pygame,开发语言)