1.调用外部库
2.代码实现
1.基础版本
2.添加功能
1. elif event.type == pygame.KEYDOWN: 2. if event.key == pygame.K_w: 3. player1_paddle_dy = -5 4. elif event.key == pygame.K_s: 5. player1_paddle_dy = 5 6. 7. 8. 9. elif event.key == pygame.K_UP: 10. player_paddle_dy = -5 11. elif event.key == pygame.K_DOWN: 12. player_paddle_dy = 5 13. elif event.key == pygame.K_SPACE: 14. if space_state == "0": 15. space_state = "1"
1. # Set up the player2's paddle 2. PLAYER_PADDLE_WIDTH = 10 3. PLAYER_PADDLE_HEIGHT = 100 4. player_paddle_x = WINDOW_WIDTH - PLAYER_PADDLE_WIDTH - 10 5. player_paddle_y = WINDOW_HEIGHT // 2 - PLAYER_PADDLE_HEIGHT // 2 6. player_paddle_dy = 0 7. 8. # Set up the player1's paddle 9. player1_PADDLE_WIDTH = 10 10. player1_PADDLE_HEIGHT = 100 11. player1_paddle_x = 10 12. player1_paddle_y = WINDOW_HEIGHT // 2 - player1_PADDLE_HEIGHT // 2 13. player1_paddle_dy = 0
1. elif event.type == pygame.KEYUP: 2. if event.key == pygame.K_UP or event.key == pygame.K_DOWN: 3. player_paddle_dy = 0 4. elif event.key == pygame.K_SPACE: 5. if space_state != "1": continue 6. space_state = "0" 7. if game_state == "start": 8. game_state = "playing" 9. ball_dx = -ball_dx 10. ball_dy = -ball_dy 11. 12. elif event.key == pygame.K_w or event.key == pygame.K_s: 13. player1_paddle_dy = 0 14. elif event.key == pygame.K_SPACE: 15. if space_state != "1": continue 16. space_state = "0" 17. if game_state == "start": 18. game_state = "playing" 19. ball_dx = -ball_dx 20. ball_dy = -ball_dy
1. # Move the player's paddle 2. player_paddle_y += player_paddle_dy 3. if player_paddle_y <= 0: 4. player_paddle_y = 0 5. elif player_paddle_y + PLAYER_PADDLE_HEIGHT >= WINDOW_HEIGHT: 6. player_paddle_y = WINDOW_HEIGHT - PLAYER_PADDLE_HEIGHT 7. 8. # Move the player1's paddle 9. player1_paddle_y += player1_paddle_dy 10. if player1_paddle_y <= 0: 11. player1_paddle_y = 0 12. elif player1_paddle_y + player1_PADDLE_HEIGHT >= WINDOW_HEIGHT: 13. player1_paddle_y = WINDOW_HEIGHT - player1_PADDLE_HEIGHT
3.游戏实测