QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

手机号码,快捷登录

手机号码,快捷登录

查看: 5228|回复: 0

[Python] Python游戏编程之实现飞机大战

[复制链接]

等级头衔

积分成就    金币 : 2841
   泡泡 : 1516
   精华 : 6
   在线时间 : 1294 小时
   最后登录 : 2024-11-21

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老

联系方式
发表于 2021-7-2 09:51:02 | 显示全部楼层 |阅读模式
       不知道大家有没有打过飞机,喜不喜欢打飞机。当我第一次接触这个东西的时候,我的内心是被震撼到的。第一次接触打飞机的时候作者本人是身心愉悦的,因为周边的朋友都在打飞机, 每次都会下意识彼此较量一下,看谁打得更好。打飞机也是需要有一定的技巧的,熟练的朋友一把能打上半个小时,生疏的则三五分钟就败下阵来。那么怎么实现自己的打飞机游戏?下面就跟大家一起来动手实现打飞机游戏。
# |1 a+ _7 [# }一.游戏设定3 k1 V! D) H7 F" t5 e
游戏界面如下图所示:' s# z+ i% k0 n* g8 j- R9 y* X
1.jpg
: ~7 H, j, {6 C  G+ V2 t游戏的基本设定:
; n. H! u! t) u* H- \- H
  • 敌方共有大中小3款飞机,分为高中低三种速度;
  • 子弹的射程并非全屏,而大概是屏幕长度的80%;
  • 消灭小飞机需要1发子弹,中飞机需要8发,大飞机需要20发子弹;
  • 每消灭一架小飞机得1000分,中飞机6000分,大飞机10000分;
  • 每隔30秒有一个随机的道具补给,分为两种道具,全屏炸弹和双倍子弹;
  • 全屏炸弹最多只能存放3枚,双倍子弹可以维持18秒钟的效果;
  • 游戏将根据分数来逐步提高难度,难度的提高表现为飞机数量的增多以及速度的加快。
    7 Z9 A* u8 D. d5 |
       另外还对游戏做了一些改进,比如为中飞机和大飞机增加了血槽的显示,这样玩家可以直观地知道敌机快被消灭了没有;我方有三次机会,每次被敌人消灭,新诞生的飞机会有3秒钟的安全期;游戏结束后会显示历史最高分数。
0 h* B$ U: b4 J* Z. Y" f       这个游戏加上基本的注释代码量在800行左右,代码看上去比较多,多打代码少动脑。所以大家不要怕,越是多的代码,逻辑就越容易看得清楚,就越好学习。好,那让我们从无到有,从简单到复杂来一起打造这个游戏吧!
  i+ @' `( i! T& c! l4 o二.我方飞机. |4 Q" ?3 y1 [9 q2 b5 q4 p
       首先创建一个myplane. py模块来定义我方飞机:
. m7 ]2 F4 ?+ [
  1. import pygame
  2. class MyPlane(pygame.sprite.Sprite):
  3.     def __init__(self, bg_size):
  4.         pygame.sprite.Sprite.__init__(self)
  5. self.image1 = pygame.image.load("images/me1.png").convert_alpha()
  6. self.image2 = pygame.image.load("images/me2.png").convert_alpha()
  7. self.destroy_images = []
  8. self.destroy_images.extend([\
  9.             pygame.image.load("images/me_destroy_1.png").convert_alpha(), \
  10.             pygame.image.load("images/me_destroy_2.png").convert_alpha(), \
  11.             pygame.image.load("images/me_destroy_3.png").convert_alpha(), \
  12.             pygame.image.load("images/me_destroy_4.png").convert_alpha() \
  13.             ])
  14. self.rect = self.image1.get_rect()
  15. self.width, self.height = bg_size[0], bg_size[1]
  16. self.rect.left, self.rect.top = \
  17.                         (self.width - self.rect.width) // 2, \
  18. self.height - self.rect.height - 60
  19. self.speed = 10
  20. self.active = True
  21. self.invincible = False
  22. self.mask = pygame.mask.from_surface(self.image1)
  23. # 分别定义moveUp()、moveDown()、moveLeft()和moveRight()控制我方飞机上、下、左、右移动:
  24.     def moveUp(self):
  25. if self.rect.top > 0:
  26. self.rect.top -= self.speed
  27. else:
  28. self.rect.top = 0
  29.     def moveDown(self):
  30. if self.rect.bottom < self.height - 60:
  31. self.rect.top += self.speed
  32. else:
  33. self.rect.bottom = self.height - 60
  34.     def moveLeft(self):
  35. if self.rect.left > 0:
  36. self.rect.left -= self.speed
  37. else:
  38. self.rect.left = 0
  39.     def moveRight(self):
  40. if self.rect.right < self.width:
  41. self.rect.left += self.speed
  42. else:
  43. self.rect.right = self.width
  44.     def reset(self):
  45. self.rect.left, self.rect.top = \
  46.                         (self.width - self.rect.width) // 2, \
  47. self.height - self.rect.height - 60
  48. self.active = True
  49.         self.invincible = True
三.敌方飞机+ O% E+ Z$ X/ ?% A; Y  ^1 u
       既然英雄已经有了,那现在就是需要创造敌人的时候。敌机分为小、中、大三个尺寸,它们的速度依次是快、中、慢,在游戏界面的上方位置创造位置随机的敌机,可以让它们不在同一排出现。将敌机的定义写在enemy. py模块中:7 [0 W& U7 s# f% r1 h. g4 H) {
  1. import pygame
  2. from random import *
  3. class SmallEnemy(pygame.sprite.Sprite):
  4. def __init__(self, bg_size):
  5.         pygame.sprite.Sprite.__init__(self)
  6. self.image = pygame.image.load("images/enemy1.png").convert_alpha()
  7. self.destroy_images = []
  8. self.destroy_images.extend([ \
  9.             pygame.image.load("images/enemy1_down1.png").convert_alpha(), \
  10.             pygame.image.load("images/enemy1_down2.png").convert_alpha(), \
  11.             pygame.image.load("images/enemy1_down3.png").convert_alpha(), \
  12.             pygame.image.load("images/enemy1_down4.png").convert_alpha() \
  13.             ])
  14. self.rect = self.image.get_rect()
  15. self.width, self.height = bg_size[0], bg_size[1]
  16. self.speed = 2
  17. self.active = True
  18. self.rect.left, self.rect.top = \
  19.             randint(0, self.width - self.rect.width), \
  20.             randint(-5 * self.height, 0)
  21. self.mask = pygame.mask.from_surface(self.image)
  22. def move(self):
  23. if self.rect.top < self.height:
  24. self.rect.top += self.speed
  25. else:
  26. self.reset()
  27. def reset(self):
  28. self.active = True
  29. self.rect.left, self.rect.top = \
  30.             randint(0, self.width - self.rect.width), \
  31.             randint(-5 * self.height, 0)
  32. class MidEnemy(pygame.sprite.Sprite):
  33.     energy = 8
  34. def __init__(self, bg_size):
  35.         pygame.sprite.Sprite.__init__(self)
  36. self.image = pygame.image.load("images/enemy2.png").convert_alpha()
  37. self.image_hit = pygame.image.load("images/enemy2_hit.png").convert_alpha()
  38. self.destroy_images = []
  39. self.destroy_images.extend([ \
  40.             pygame.image.load("images/enemy2_down1.png").convert_alpha(), \
  41.             pygame.image.load("images/enemy2_down2.png").convert_alpha(), \
  42.             pygame.image.load("images/enemy2_down3.png").convert_alpha(), \
  43.             pygame.image.load("images/enemy2_down4.png").convert_alpha() \
  44.             ])
  45. self.rect = self.image.get_rect()
  46. self.width, self.height = bg_size[0], bg_size[1]
  47. self.speed = 1
  48. self.active = True
  49. self.rect.left, self.rect.top = \
  50.             randint(0, self.width - self.rect.width), \
  51.             randint(-10 * self.height, -self.height)
  52. self.mask = pygame.mask.from_surface(self.image)
  53. self.energy = MidEnemy.energy
  54. self.hit = False
  55. def move(self):
  56. if self.rect.top < self.height:
  57. self.rect.top += self.speed
  58. else:
  59. self.reset()
  60. def reset(self):
  61. self.active = True
  62. self.energy = MidEnemy.energy
  63. self.rect.left, self.rect.top = \
  64.             randint(0, self.width - self.rect.width), \
  65.             randint(-10 * self.height, -self.height)
  66. class BigEnemy(pygame.sprite.Sprite):
  67.     energy = 20
  68. def __init__(self, bg_size):
  69.         pygame.sprite.Sprite.__init__(self)
  70. self.image1 = pygame.image.load("images/enemy3_n1.png").convert_alpha()
  71. self.image2 = pygame.image.load("images/enemy3_n2.png").convert_alpha()
  72. self.image_hit = pygame.image.load("images/enemy3_hit.png").convert_alpha()
  73. self.destroy_images = []
  74. self.destroy_images.extend([ \
  75.             pygame.image.load("images/enemy3_down1.png").convert_alpha(), \
  76.             pygame.image.load("images/enemy3_down2.png").convert_alpha(), \
  77.             pygame.image.load("images/enemy3_down3.png").convert_alpha(), \
  78.             pygame.image.load("images/enemy3_down4.png").convert_alpha(), \
  79.             pygame.image.load("images/enemy3_down5.png").convert_alpha(), \
  80.             pygame.image.load("images/enemy3_down6.png").convert_alpha() \
  81.             ])
  82. self.rect = self.image1.get_rect()
  83. self.width, self.height = bg_size[0], bg_size[1]
  84. self.speed = 1
  85. self.active = True
  86. self.rect.left, self.rect.top = \
  87.             randint(0, self.width - self.rect.width), \
  88.             randint(-15 * self.height, -5 * self.height)
  89. self.mask = pygame.mask.from_surface(self.image1)
  90. self.energy = BigEnemy.energy
  91. self.hit = False
  92. def move(self):
  93. if self.rect.top < self.height:
  94. self.rect.top += self.speed
  95. else:
  96. self.reset()
  97. def reset(self):
  98. self.active = True
  99. self.energy = BigEnemy.energy
  100. self.rect.left, self.rect.top = \
  101.             randint(0, self.width - self.rect.width), \
  102.             randint(-15 * self.height, -5 * self.height)
四.发射子弹
* L; z! ]: \+ _       现在的情况是我方飞机处于落后挨打的状态,敌强我弱,所以应该拿起武器进行反击! 接下来定义子弹,子弹分为两种: 一种是普通子弹一次只发射一颗; 另一种是补给发放的超级子弹一次可以发射两颗。我们将子弹定义为独立的模块bullet.py:# D1 T! d3 X! }0 P) B7 v$ F9 j
  1. import pygame
  2. class Bullet1(pygame.sprite.Sprite):
  3. def __init__(self, position):
  4.         pygame.sprite.Sprite.__init__(self)
  5. self.image = pygame.image.load("images/bullet1.png").convert_alpha()
  6. self.rect = self.image.get_rect()
  7. self.rect.left, self.rect.top = position
  8. self.speed = 12
  9. self.active = False
  10. self.mask = pygame.mask.from_surface(self.image)
  11. def move(self):
  12. self.rect.top -= self.speed
  13. if self.rect.top < 0:
  14. self.active = False
  15. def reset(self, position):
  16. self.rect.left, self.rect.top = position
  17. self.active = True
  18. class Bullet2(pygame.sprite.Sprite):
  19. def __init__(self, position):
  20.         pygame.sprite.Sprite.__init__(self)
  21. self.image = pygame.image.load("images/bullet2.png").convert_alpha()
  22. self.rect = self.image.get_rect()
  23. self.rect.left, self.rect.top = position
  24. self.speed = 14
  25. self.active = False
  26. self.mask = pygame.mask.from_surface(self.image)
  27. def move(self):
  28. self.rect.top -= self.speed
  29. if self.rect.top < 0:
  30. self.active = False
  31. def reset(self, position):
  32. self.rect.left, self.rect.top = position
  33.         self.active = True
  34. 五.发放补给包
  35. 游戏设计每30秒随机发放一个补给包,可 能是超级子弹,也可能是全屏炸弹。补给包有自己的图像和运动轨迹,定义一个模块supply.py:
  36. import pygame
  37. from random import *
  38. class Bullet_Supply(pygame.sprite.Sprite):
  39. def __init__(self, bg_size):
  40.         pygame.sprite.Sprite.__init__(self)
  41. self.image = pygame.image.load("images/bullet_supply.png").convert_alpha()
  42. self.rect = self.image.get_rect()
  43. self.width, self.height = bg_size[0], bg_size[1]
  44. self.rect.left, self.rect.bottom = \
  45.             randint(0, self.width - self.rect.width), -100
  46. self.speed = 5
  47. self.active = False
  48. self.mask = pygame.mask.from_surface(self.image)
  49. def move(self):
  50. if self.rect.top < self.height:
  51. self.rect.top += self.speed
  52. else:
  53. self.active = False
  54. def reset(self):
  55. self.active = True
  56. self.rect.left, self.rect.bottom = \
  57.             randint(0, self.width - self.rect.width), -100
  58. class Bomb_Supply(pygame.sprite.Sprite):
  59. def __init__(self, bg_size):
  60.         pygame.sprite.Sprite.__init__(self)
  61. self.image = pygame.image.load("images/bomb_supply.png").convert_alpha()
  62. self.rect = self.image.get_rect()
  63. self.width, self.height = bg_size[0], bg_size[1]
  64. self.rect.left, self.rect.bottom = \
  65.             randint(0, self.width - self.rect.width), -100
  66. self.speed = 5
  67. self.active = False
  68. self.mask = pygame.mask.from_surface(self.image)
  69. def move(self):
  70. if self.rect.top < self.height:
  71. self.rect.top += self.speed
  72. else:
  73. self.active = False
  74. def reset(self):
  75. self.active = True
  76. self.rect.left, self.rect.bottom = \
  77.             randint(0, self.width - self.rect.width), -100
六.主模块
" r( L: n& W( P# u* `( i6 n       所有的模块都到齐了,接下来就该实现我们的主模块:
& T9 ~$ L# g& s
  1. # main.py
  2. import pygame
  3. import sys
  4. import traceback
  5. import myplane
  6. import enemy
  7. import bullet
  8. import supply
  9. from pygame.locals import *
  10. from random import *
  11. pygame.init()
  12. pygame.mixer.init()
  13. bg_size = width, height = 480, 700
  14. screen = pygame.display.set_mode(bg_size)
  15. pygame.display.set_caption("飞机大战 -- FishC Demo")
  16. background = pygame.image.load("images/background.png").convert()
  17. BLACK = (0, 0, 0)
  18. WHITE = (255, 255, 255)
  19. GREEN = (0, 255, 0)
  20. RED = (255, 0, 0)
  21. # 载入游戏音乐
  22. pygame.mixer.music.load("sound/game_music.ogg")
  23. pygame.mixer.music.set_volume(0.2)
  24. bullet_sound = pygame.mixer.Sound("sound/bullet.wav")
  25. bullet_sound.set_volume(0.2)
  26. bomb_sound = pygame.mixer.Sound("sound/use_bomb.wav")
  27. bomb_sound.set_volume(0.2)
  28. supply_sound = pygame.mixer.Sound("sound/supply.wav")
  29. supply_sound.set_volume(0.2)
  30. get_bomb_sound = pygame.mixer.Sound("sound/get_bomb.wav")
  31. get_bomb_sound.set_volume(0.2)
  32. get_bullet_sound = pygame.mixer.Sound("sound/get_bullet.wav")
  33. get_bullet_sound.set_volume(0.2)
  34. upgrade_sound = pygame.mixer.Sound("sound/upgrade.wav")
  35. upgrade_sound.set_volume(0.2)
  36. enemy3_fly_sound = pygame.mixer.Sound("sound/enemy3_flying.wav")
  37. enemy3_fly_sound.set_volume(0.2)
  38. enemy1_down_sound = pygame.mixer.Sound("sound/enemy1_down.wav")
  39. enemy1_down_sound.set_volume(0.2)
  40. enemy2_down_sound = pygame.mixer.Sound("sound/enemy2_down.wav")
  41. enemy2_down_sound.set_volume(0.2)
  42. enemy3_down_sound = pygame.mixer.Sound("sound/enemy3_down.wav")
  43. enemy3_down_sound.set_volume(0.5)
  44. me_down_sound = pygame.mixer.Sound("sound/me_down.wav")
  45. me_down_sound.set_volume(0.2)
  46. def add_small_enemies(group1, group2, num):
  47. for i in range(num):
  48. e1 = enemy.SmallEnemy(bg_size)
  49. group1.add(e1)
  50. group2.add(e1)
  51. def add_mid_enemies(group1, group2, num):
  52. for i in range(num):
  53. e2 = enemy.MidEnemy(bg_size)
  54. group1.add(e2)
  55. group2.add(e2)
  56. def add_big_enemies(group1, group2, num):
  57. for i in range(num):
  58. e3 = enemy.BigEnemy(bg_size)
  59. group1.add(e3)
  60. group2.add(e3)
  61. def inc_speed(target, inc):
  62. for each in target:
  63. each.speed += inc
  64. def main():
  65. pygame.mixer.music.play(-1)
  66.     # 生成我方飞机
  67. me = myplane.MyPlane(bg_size)
  68. enemies = pygame.sprite.Group()
  69.     # 生成敌方小型飞机
  70. small_enemies = pygame.sprite.Group()
  71. add_small_enemies(small_enemies, enemies, 15)
  72.     # 生成敌方中型飞机
  73. mid_enemies = pygame.sprite.Group()
  74. add_mid_enemies(mid_enemies, enemies, 4)
  75.     # 生成敌方大型飞机
  76. big_enemies = pygame.sprite.Group()
  77. add_big_enemies(big_enemies, enemies, 2)
  78.     # 生成普通子弹
  79. bullet1 = []
  80. bullet1_index = 0
  81. BULLET1_NUM = 4
  82. for i in range(BULLET1_NUM):
  83. bullet1.append(bullet.Bullet1(me.rect.midtop))
  84.     # 生成超级子弹
  85. bullet2 = []
  86. bullet2_index = 0
  87. BULLET2_NUM = 8
  88. for i in range(BULLET2_NUM // 2):
  89. bullet2.append(bullet.Bullet2((me.rect.centerx - 33, me.rect.centery)))
  90. bullet2.append(bullet.Bullet2((me.rect.centerx + 30, me.rect.centery)))
  91. clock = pygame.time.Clock()
  92.     # 中弹图片索引
  93. e1_destroy_index = 0
  94. e2_destroy_index = 0
  95. e3_destroy_index = 0
  96. me_destroy_index = 0
  97.     # 统计得分
  98. score = 0
  99. score_font = pygame.font.Font("font/font.ttf", 36)
  100.     # 标志是否暂停游戏
  101. paused = False
  102. pause_nor_image = pygame.image.load("images/pause_nor.png").convert_alpha()
  103. pause_pressed_image = pygame.image.load("images/pause_pressed.png").convert_alpha()
  104. resume_nor_image = pygame.image.load("images/resume_nor.png").convert_alpha()
  105. resume_pressed_image = pygame.image.load("images/resume_pressed.png").convert_alpha()
  106. paused_rect = pause_nor_image.get_rect()
  107. paused_rect.left, paused_rect.top = width - paused_rect.width - 10, 10
  108. paused_image = pause_nor_image
  109.     # 设置难度级别
  110. level = 1
  111.     # 全屏炸弹
  112. bomb_image = pygame.image.load("images/bomb.png").convert_alpha()
  113. bomb_rect = bomb_image.get_rect()
  114. bomb_font = pygame.font.Font("font/font.ttf", 48)
  115. bomb_num = 3
  116.     # 每30秒发放一个补给包
  117. bullet_supply = supply.Bullet_Supply(bg_size)
  118. bomb_supply = supply.Bomb_Supply(bg_size)
  119. SUPPLY_TIME = USEREVENT
  120. pygame.time.set_timer(SUPPLY_TIME, 30 * 1000)
  121.     # 超级子弹定时器
  122. DOUBLE_BULLET_TIME = USEREVENT + 1
  123.     # 标志是否使用超级子弹
  124. is_double_bullet = False
  125.     # 解除我方无敌状态定时器
  126. INVINCIBLE_TIME = USEREVENT + 2
  127.     # 生命数量
  128. life_image = pygame.image.load("images/life.png").convert_alpha()
  129. life_rect = life_image.get_rect()
  130. life_num = 3
  131.     # 用于阻止重复打开记录文件
  132. recorded = False
  133.     # 游戏结束画面
  134. gameover_font = pygame.font.Font("font/font.TTF", 48)
  135. again_image = pygame.image.load("images/again.png").convert_alpha()
  136. again_rect = again_image.get_rect()
  137. gameover_image = pygame.image.load("images/gameover.png").convert_alpha()
  138. gameover_rect = gameover_image.get_rect()
  139.     # 用于切换图片
  140. switch_image = True
  141.     # 用于延迟
  142. delay = 100
  143. running = True
  144. while running:
  145. for event in pygame.event.get():
  146. if event.type == QUIT:
  147. pygame.quit()
  148. sys.exit()
  149. elif event.type == MOUSEBUTTONDOWN:
  150. if event.button == 1 and paused_rect.collidepoint(event.pos):
  151. paused = not paused
  152. if paused:
  153. pygame.time.set_timer(SUPPLY_TIME, 0)
  154. pygame.mixer.music.pause()
  155. pygame.mixer.pause()
  156. else:
  157. pygame.time.set_timer(SUPPLY_TIME, 30 * 1000)
  158. pygame.mixer.music.unpause()
  159. pygame.mixer.unpause()
  160. elif event.type == MOUSEMOTION:
  161. if paused_rect.collidepoint(event.pos):
  162. if paused:
  163. paused_image = resume_pressed_image
  164. else:
  165. paused_image = pause_pressed_image
  166. else:
  167. if paused:
  168. paused_image = resume_nor_image
  169. else:
  170. paused_image = pause_nor_image
  171. elif event.type == KEYDOWN:
  172. if event.key == K_SPACE:
  173. if bomb_num:
  174. bomb_num -= 1
  175. bomb_sound.play()
  176. for each in enemies:
  177. if each.rect.bottom > 0:
  178. each.active = False
  179. elif event.type == SUPPLY_TIME:
  180. supply_sound.play()
  181. if choice([True, False]):
  182. bomb_supply.reset()
  183. else:
  184. bullet_supply.reset()
  185. elif event.type == DOUBLE_BULLET_TIME:
  186. is_double_bullet = False
  187. pygame.time.set_timer(DOUBLE_BULLET_TIME, 0)
  188. elif event.type == INVINCIBLE_TIME:
  189. me.invincible = False
  190. pygame.time.set_timer(INVINCIBLE_TIME, 0)
  191.         # 根据用户的得分增加难度
  192. if level == 1 and score > 50000:
  193. level = 2
  194. upgrade_sound.play()
  195.             # 增加3架小型敌机、2架中型敌机和1架大型敌机
  196. add_small_enemies(small_enemies, enemies, 3)
  197. add_mid_enemies(mid_enemies, enemies, 2)
  198. add_big_enemies(big_enemies, enemies, 1)
  199.             # 提升小型敌机的速度
  200. inc_speed(small_enemies, 1)
  201. elif level == 2 and score > 300000:
  202. level = 3
  203. upgrade_sound.play()
  204.             # 增加5架小型敌机、3架中型敌机和2架大型敌机
  205. add_small_enemies(small_enemies, enemies, 5)
  206. add_mid_enemies(mid_enemies, enemies, 3)
  207. add_big_enemies(big_enemies, enemies, 2)
  208.             # 提升小型敌机的速度
  209. inc_speed(small_enemies, 1)
  210. inc_speed(mid_enemies, 1)
  211. elif level == 3 and score > 600000:
  212. level = 4
  213. upgrade_sound.play()
  214.             # 增加5架小型敌机、3架中型敌机和2架大型敌机
  215. add_small_enemies(small_enemies, enemies, 5)
  216. add_mid_enemies(mid_enemies, enemies, 3)
  217. add_big_enemies(big_enemies, enemies, 2)
  218.             # 提升小型敌机的速度
  219. inc_speed(small_enemies, 1)
  220. inc_speed(mid_enemies, 1)
  221. elif level == 4 and score > 1000000:
  222. level = 5
  223. upgrade_sound.play()
  224.             # 增加5架小型敌机、3架中型敌机和2架大型敌机
  225. add_small_enemies(small_enemies, enemies, 5)
  226. add_mid_enemies(mid_enemies, enemies, 3)
  227. add_big_enemies(big_enemies, enemies, 2)
  228.             # 提升小型敌机的速度
  229. inc_speed(small_enemies, 1)
  230. inc_speed(mid_enemies, 1)
  231. screen.blit(background, (0, 0))
  232. if life_num and not paused:
  233.             # 检测用户的键盘操作
  234. key_pressed = pygame.key.get_pressed()
  235. if key_pressed[K_w] or key_pressed[K_UP]:
  236. me.moveUp()
  237. if key_pressed[K_s] or key_pressed[K_DOWN]:
  238. me.moveDown()
  239. if key_pressed[K_a] or key_pressed[K_LEFT]:
  240. me.moveLeft()
  241. if key_pressed[K_d] or key_pressed[K_RIGHT]:
  242. me.moveRight()
  243.             # 绘制全屏炸弹补给并检测是否获得
  244. if bomb_supply.active:
  245. bomb_supply.move()
  246. screen.blit(bomb_supply.image, bomb_supply.rect)
  247. if pygame.sprite.collide_mask(bomb_supply, me):
  248. get_bomb_sound.play()
  249. if bomb_num < 3:
  250. bomb_num += 1
  251. bomb_supply.active = False
  252.             # 绘制超级子弹补给并检测是否获得
  253. if bullet_supply.active:
  254. bullet_supply.move()
  255. screen.blit(bullet_supply.image, bullet_supply.rect)
  256. if pygame.sprite.collide_mask(bullet_supply, me):
  257. get_bullet_sound.play()
  258. is_double_bullet = True
  259. pygame.time.set_timer(DOUBLE_BULLET_TIME, 18 * 1000)
  260. bullet_supply.active = False
  261.             # 发射子弹
  262. if not (delay % 10):
  263. bullet_sound.play()
  264. if is_double_bullet:
  265. bullets = bullet2
  266. bullets[bullet2_index].reset((me.rect.centerx - 33, me.rect.centery))
  267. bullets[bullet2_index + 1].reset((me.rect.centerx + 30, me.rect.centery))
  268. bullet2_index = (bullet2_index + 2) % BULLET2_NUM
  269. else:
  270. bullets = bullet1
  271. bullets[bullet1_index].reset(me.rect.midtop)
  272. bullet1_index = (bullet1_index + 1) % BULLET1_NUM
  273.             # 检测子弹是否击中敌机
  274. for b in bullets:
  275. if b.active:
  276. b.move()
  277. screen.blit(b.image, b.rect)
  278. enemy_hit = pygame.sprite.spritecollide(b, enemies, False, pygame.sprite.collide_mask)
  279. if enemy_hit:
  280. b.active = False
  281. for e in enemy_hit:
  282. if e in mid_enemies or e in big_enemies:
  283. e.hit = True
  284. e.energy -= 1
  285. if e.energy == 0:
  286. e.active = False
  287. else:
  288. e.active = False
  289.             # 绘制大型敌机
  290. for each in big_enemies:
  291. if each.active:
  292. each.move()
  293. if each.hit:
  294. screen.blit(each.image_hit, each.rect)
  295. each.hit = False
  296. else:
  297. if switch_image:
  298. screen.blit(each.image1, each.rect)
  299. else:
  300. screen.blit(each.image2, each.rect)
  301.                     # 绘制血槽
  302. pygame.draw.line(screen, BLACK, \
  303.                                      (each.rect.left, each.rect.top - 5), \
  304.                                      (each.rect.right, each.rect.top - 5), \
  305.                                      2)
  306.                     # 当生命大于20%显示绿色,否则显示红色
  307. energy_remain = each.energy / enemy.BigEnemy.energy
  308. if energy_remain > 0.2:
  309. energy_color = GREEN
  310. else:
  311. energy_color = RED
  312. pygame.draw.line(screen, energy_color, \
  313.                                      (each.rect.left, each.rect.top - 5), \
  314.                                      (each.rect.left + each.rect.width * energy_remain, \
  315.                                       each.rect.top - 5), 2)
  316.                     # 即将出现在画面中,播放音效
  317. if each.rect.bottom == -50:
  318. enemy3_fly_sound.play(-1)
  319. else:
  320.                     # 毁灭
  321. if not (delay % 3):
  322. if e3_destroy_index == 0:
  323. enemy3_down_sound.play()
  324. screen.blit(each.destroy_images[e3_destroy_index], each.rect)
  325. e3_destroy_index = (e3_destroy_index + 1) % 6
  326. if e3_destroy_index == 0:
  327. enemy3_fly_sound.stop()
  328. score += 10000
  329. each.reset()
  330.             # 绘制中型敌机:
  331. for each in mid_enemies:
  332. if each.active:
  333. each.move()
  334. if each.hit:
  335. screen.blit(each.image_hit, each.rect)
  336. each.hit = False
  337. else:
  338. screen.blit(each.image, each.rect)
  339.                     # 绘制血槽
  340. pygame.draw.line(screen, BLACK, \
  341.                                      (each.rect.left, each.rect.top - 5), \
  342.                                      (each.rect.right, each.rect.top - 5), \
  343.                                      2)
  344.                     # 当生命大于20%显示绿色,否则显示红色
  345. energy_remain = each.energy / enemy.MidEnemy.energy
  346. if energy_remain > 0.2:
  347. energy_color = GREEN
  348. else:
  349. energy_color = RED
  350. pygame.draw.line(screen, energy_color, \
  351.                                      (each.rect.left, each.rect.top - 5), \
  352.                                      (each.rect.left + each.rect.width * energy_remain, \
  353.                                       each.rect.top - 5), 2)
  354. else:
  355.                     # 毁灭
  356. if not (delay % 3):
  357. if e2_destroy_index == 0:
  358. enemy2_down_sound.play()
  359. screen.blit(each.destroy_images[e2_destroy_index], each.rect)
  360. e2_destroy_index = (e2_destroy_index + 1) % 4
  361. if e2_destroy_index == 0:
  362. score += 6000
  363. each.reset()
  364.             # 绘制小型敌机:
  365. for each in small_enemies:
  366. if each.active:
  367. each.move()
  368. screen.blit(each.image, each.rect)
  369. else:
  370.                     # 毁灭
  371. if not (delay % 3):
  372. if e1_destroy_index == 0:
  373. enemy1_down_sound.play()
  374. screen.blit(each.destroy_images[e1_destroy_index], each.rect)
  375. e1_destroy_index = (e1_destroy_index + 1) % 4
  376. if e1_destroy_index == 0:
  377. score += 1000
  378. each.reset()
  379.             # 检测我方飞机是否被撞
  380. enemies_down = pygame.sprite.spritecollide(me, enemies, False, pygame.sprite.collide_mask)
  381. if enemies_down and not me.invincible:
  382. me.active = False
  383. for e in enemies_down:
  384. e.active = False
  385.             # 绘制我方飞机
  386. if me.active:
  387. if switch_image:
  388. screen.blit(me.image1, me.rect)
  389. else:
  390. screen.blit(me.image2, me.rect)
  391. else:
  392.                 # 毁灭
  393. if not (delay % 3):
  394. if me_destroy_index == 0:
  395. me_down_sound.play()
  396. screen.blit(me.destroy_images[me_destroy_index], me.rect)
  397. me_destroy_index = (me_destroy_index + 1) % 4
  398. if me_destroy_index == 0:
  399. life_num -= 1
  400. me.reset()
  401. pygame.time.set_timer(INVINCIBLE_TIME, 3 * 1000)
  402.             # 绘制全屏炸弹数量
  403. bomb_text = bomb_font.render("× %d" % bomb_num, True, WHITE)
  404. text_rect = bomb_text.get_rect()
  405. screen.blit(bomb_image, (10, height - 10 - bomb_rect.height))
  406. screen.blit(bomb_text, (20 + bomb_rect.width, height - 5 - text_rect.height))
  407.             # 绘制剩余生命数量
  408. if life_num:
  409. for i in range(life_num):
  410. screen.blit(life_image, \
  411.                                 (width - 10 - (i + 1) * life_rect.width, \
  412.                                  height - 10 - life_rect.height))
  413.             # 绘制得分
  414. score_text = score_font.render("Score : %s" % str(score), True, WHITE)
  415. screen.blit(score_text, (10, 5))
  416.         # 绘制游戏结束画面
  417. elif life_num == 0:
  418.             # 背景音乐停止
  419. pygame.mixer.music.stop()
  420.             # 停止全部音效
  421. pygame.mixer.stop()
  422.             # 停止发放补给
  423. pygame.time.set_timer(SUPPLY_TIME, 0)
  424. if not recorded:
  425. recorded = True
  426.                 # 读取历史最高得分
  427. with open("record.txt", "r") as f:
  428. record_score = int(f.read())
  429.                 # 如果玩家得分高于历史最高得分,则存档
  430. if score > record_score:
  431. with open("record.txt", "w") as f:
  432. f.write(str(score))
  433.             # 绘制结束画面
  434. record_score_text = score_font.render("Best : %d" % record_score, True, (255, 255, 255))
  435. screen.blit(record_score_text, (50, 50))
  436. gameover_text1 = gameover_font.render("Your Score", True, (255, 255, 255))
  437. gameover_text1_rect = gameover_text1.get_rect()
  438. gameover_text1_rect.left, gameover_text1_rect.top = \
  439.                 (width - gameover_text1_rect.width) // 2, height // 3
  440. screen.blit(gameover_text1, gameover_text1_rect)
  441. gameover_text2 = gameover_font.render(str(score), True, (255, 255, 255))
  442. gameover_text2_rect = gameover_text2.get_rect()
  443. gameover_text2_rect.left, gameover_text2_rect.top = \
  444.                 (width - gameover_text2_rect.width) // 2, \
  445.                 gameover_text1_rect.bottom + 10
  446. screen.blit(gameover_text2, gameover_text2_rect)
  447. again_rect.left, again_rect.top = \
  448.                 (width - again_rect.width) // 2, \
  449.                 gameover_text2_rect.bottom + 50
  450. screen.blit(again_image, again_rect)
  451. gameover_rect.left, gameover_rect.top = \
  452.                 (width - again_rect.width) // 2, \
  453.                 again_rect.bottom + 10
  454. screen.blit(gameover_image, gameover_rect)
  455.             # 检测用户的鼠标操作
  456.             # 如果用户按下鼠标左键
  457. if pygame.mouse.get_pressed()[0]:
  458.                 # 获取鼠标坐标
  459. pos = pygame.mouse.get_pos()
  460.                 # 如果用户点击“重新开始”
  461. if again_rect.left < pos[0] < again_rect.right and \
  462.                         again_rect.top < pos[1] < again_rect.bottom:
  463.                     # 调用main函数,重新开始游戏
  464. main()
  465.                 # 如果用户点击“结束游戏”
  466. elif gameover_rect.left < pos[0] < gameover_rect.right and \
  467.                         gameover_rect.top < pos[1] < gameover_rect.bottom:
  468.                     # 退出游戏
  469. pygame.quit()
  470. sys.exit()
  471.                     # 绘制暂停按钮
  472. screen.blit(paused_image, paused_rect)
  473.         # 切换图片
  474. if not (delay % 5):
  475. switch_image = not switch_image
  476. delay -= 1
  477. if not delay:
  478. delay = 100
  479. pygame.display.flip()
  480. clock.tick(60)
  481. if __name__ == "__main__":
  482. try:
  483. main()
  484. except SystemExit:
  485. pass
  486. except:
  487. traceback.print_exc()
  488. pygame.quit()
  489.         input()
      切记: 所有的模块应该放在同一个文件夹下,最后运行我们的主模块就大功告成了!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号|渝公网安备50010502503914号 )

GMT+8, 2024-11-21 21:14

Powered by paopaomj X3.5 © 2016-2025 sitemap

快速回复 返回顶部 返回列表