当前位置:   article > 正文

飞机大战游戏的Python代码

飞机大战游戏的Python代码

以下是一个简单的飞机大战游戏的Python代码示例:

  1. import pygame
  2. import random
  3. # 初始化pygame
  4. pygame.init()
  5. # 设置屏幕大小和标题
  6. screen_width = 800
  7. screen_height = 600
  8. screen = pygame.display.set_mode((screen_width, screen_height))
  9. pygame.display.set_caption("飞机大战")
  10. # 设置颜色
  11. WHITE = (255, 255, 255)
  12. RED = (255, 0, 0)
  13. GREEN = (0, 255, 0)
  14. # 定义飞机类
  15. class Plane(pygame.sprite.Sprite):
  16. def __init__(self):
  17. super().__init__()
  18. self.image = pygame.Surface([50, 30])
  19. self.image.fill(GREEN)
  20. self.rect = self.image.get_rect()
  21. self.rect.x = screen_width // 2
  22. self.rect.y = screen_height - 40
  23. self.change_x = 0
  24. def update(self):
  25. self.rect.x += self.change_x
  26. if self.rect.x < 0:
  27. self.rect.x = 0
  28. if self.rect.x > screen_width - 50:
  29. self.rect.x = screen_width - 50
  30. def go_left(self):
  31. self.change_x = -5
  32. def go_right(self):
  33. self.change_x = 5
  34. def stop(self):
  35. self.change_x = 0
  36. # 定义敌人类
  37. class Enemy(pygame.sprite.Sprite):
  38. def __init__(self):
  39. super().__init__()
  40. self.image = pygame.Surface([40, 25])
  41. self.image.fill(RED)
  42. self.rect = self.image.get_rect()
  43. self.rect.x = random.randint(0, screen_width - 40)
  44. self.rect.y = -40
  45. self.speed = random.randint(1, 3)
  46. def update(self):
  47. self.rect.y += self.speed
  48. if self.rect.y > screen_height:
  49. self.rect.y = -40
  50. self.rect.x = random.randint(0, screen_width - 40)
  51. self.speed = random.randint(1, 3)
  52. # 初始化敌机精灵组和飞机精灵组
  53. all_sprites = pygame.sprite.Group()
  54. plane = Plane()
  55. all_sprites.add(plane)
  56. enemies = pygame.sprite.Group()
  57. for i in range(5):
  58. enemy = Enemy()
  59. all_sprites.add(enemy)
  60. enemies.add(enemy)
  61. # 游戏主循环
  62. running = True
  63. while running:
  64. for event in pygame.event.get():
  65. if event.type == pygame.QUIT:
  66. running = False
  67. elif event.type == pygame.KEYDOWN:
  68. if event.key == pygame.K_LEFT:
  69. plane.go_left()
  70. elif event.key == pygame.K_RIGHT:
  71. plane.go_right()
  72. elif event.type == pygame.KEYUP:
  73. if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
  74. plane.stop()
  75. elif event.key == pygame.K_SPACE: # 发射子弹,这里需要自己实现子弹类和逻辑,这里省略了子弹类的定义和逻辑实现。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/394445
推荐阅读
相关标签
  

闽ICP备14008679号