1. import pgzrun
    2. import random
    3. PAD_SPEED = 5
    4. HEIGHT = 600 # 舞台高度
    5. WIDTH = 800 # 舞台宽度
    6. pad_1 = Rect((20, 20), (10, 100))
    7. pad_2 = Rect((WIDTH-30, 20), (10, 100))
    8. scores = [0,0] #分数
    9. BALL_SPEED = 5
    10. # 定义了一个类,规则
    11. class Ball():
    12. # 第一个执行,默认执行
    13. def __init__(self):
    14. self.reset()
    15. def reset(self): # 重置
    16. self.pos = [400, 300]
    17. s = random.choice([-1,1])
    18. self.speed = [BALL_SPEED*s, BALL_SPEED*s]
    19. ball = Ball() # 把类给实例化
    20. def draw():
    21. screen.clear() # 清空屏幕
    22. screen.draw.filled_rect(pad_1, "blue") # 画一个矩形
    23. screen.draw.filled_rect(pad_2, "blue") # 画一个矩形
    24. screen.draw.filled_circle(ball.pos, 6, "white") # 画一个圆
    25. screen.draw.text(":", midtop=(WIDTH/2, 20), fontsize=64)
    26. screen.draw.text(str(scores[0]), topright=(WIDTH/2 - 40, 20), fontsize=64)
    27. screen.draw.text(str(scores[1]), topleft=(WIDTH/2 + 40, 20), fontsize=64)
    28. def update(dt):
    29. if keyboard.w:
    30. pad_1.y -= PAD_SPEED
    31. elif keyboard.s:
    32. pad_1.y += PAD_SPEED
    33. if keyboard.up:
    34. pad_2.y -= PAD_SPEED
    35. elif keyboard.down:
    36. pad_2.y += PAD_SPEED
    37. if ball.pos[0] < 1:
    38. scores[1] += 1
    39. if ball.pos[0]>WIDTH-1:
    40. scores[0]+=1
    41. for i in range(2):
    42. ball.pos[i] += ball.speed[i]
    43. if ball.pos[1] < 0 or ball.pos[1] > HEIGHT:
    44. ball.speed[1] *= -1 # 速度变成反方向
    45. if ball.pos[0] < 0 or ball.pos[0] > WIDTH:
    46. ball.reset() # 就重置了
    47. # pad_1.collidepoint(ball.pos) :板子和我们的小球相碰了
    48. if pad_1.collidepoint(ball.pos) and ball.speed[0] < 0:
    49. ball.speed[0] *= -1
    50. if pad_2.collidepoint(ball.pos) and ball.speed[0] > 0:
    51. ball.speed[0] *= -1
    52. music.play("bgm")
    53. pgzrun.go()

    bgm.mp3背景音乐素材