发球
本课属于 Coddy Pygame 学习旅程的“项目”单元。第 17 课,共 33 课。
得分后,球应该在中间等待,直到有玩家准备好。用一个标志表示球是否在等待:
waiting = False
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
waiting = False
# 球拍始终会移动
if not waiting:
# 球会移动、反弹并得分;得分后将 waiting 设为 True球拍移动的代码放在 if 外面,这样球等待时,玩家也可以做好准备。空格键每按下一次只触发一次操作,因此要使用 KEYDOWN 事件。
球等待时,在底部附近显示 Press Space to serve,并将文字居中放在 (300, 360)。
挑战
中等每得一分后,都要等待发球。
- 在循环之前,设置
waiting = False。 - 将球的移动、反弹和计分放在
if not waiting:下,并在每得一分后设置waiting = True。 pygame.K_SPACE的 KEYDOWN 事件会将waiting = False。等待时,在(300, 360)处居中显示Press Space to serve。
点击 “开始”,故意让球从你身边经过:球会停在中间,直到你按下 Space。然后点击 “检查”。
亲手试试
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)
ball = pygame.Rect(293, 193, 14, 14)
vx, vy = 5, 4
left = pygame.Rect(20, 160, 12, 80)
right = pygame.Rect(568, 160, 12, 80)
left_score = 0
right_score = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
left.y -= 6
if keys[pygame.K_s]:
left.y += 6
if keys[pygame.K_UP]:
right.y -= 6
if keys[pygame.K_DOWN]:
right.y += 6
left.clamp_ip(screen.get_rect())
right.clamp_ip(screen.get_rect())
ball.x += vx
ball.y += vy
if ball.top <= 0 or ball.bottom >= 400:
vy = -vy
if ball.colliderect(left):
vx = abs(vx)
if ball.colliderect(right):
vx = -abs(vx)
if ball.left > 600:
left_score += 1
ball.center = (300, 200)
vx = -vx
if ball.right < 0:
right_score += 1
ball.center = (300, 200)
vx = -vx
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 160, 255), left)
pygame.draw.rect(screen, (235, 80, 80), right)
pygame.draw.rect(screen, (255, 196, 0), ball)
score = font.render(f"{left_score} : {right_score}", True, (240, 240, 240))
screen.blit(score, score.get_rect(center=(300, 30)))
pygame.display.flip()
clock.tick(60)
pygame.quit()
项目中的所有课
自己练习: Pygame 在线编辑器