2020年9月12日星期六

96B 《零基礎入門學習Python》筆記 第096講:Pygame:飛機大戰7 中

下面貼出完整代碼:(大家等很久了吧,還是希望大家把前面的細節搞懂,別直接就把完整代碼拿去裝B)
  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("飞机大战 -- Python 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()

0 留言:

發佈留言