class Player:
def __init__(self, x, y, width, height, color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.vel = 0
def draw(self, screen):
pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
def move(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and self.y > 0:
self.y -= 10
if keys[pygame.K_s] and self.y < screen_height - self.height:
self.y += 10
# 创建球和玩家对象
ball = Ball(screen_width // 2, screen_height // 2, 15, WHITE, 5, 5)
player = Player(10, screen_height // 2 - 20, 10, 40, WHITE)
# 游戏主循环
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 移动球和玩家
ball.move()
player.move()
# 检测球是否碰到玩家(这里只检测左侧玩家)
if (ball.x - ball.radius < player.x + player.width and
ball.x + ball.radius > player.x and
ball.y - ball.radius < player.y + player.height and
ball.y + ball.radius > player.y):
ball.y_vel = -ball.y_vel
# 填充背景色
screen.fill(BLACK)
# 绘制球和玩家
ball.draw(screen)
player.draw(screen)
# 更新屏幕显示
pygame.display.flip()
# 控制帧率
clock.tick(60)
pygame.quit()
sys.exit()