Python教程

Python 坦克大战

本文主要是介绍Python 坦克大战,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Python 坦克大战

运行环境:python3.8.3+pygame1.9.6

代码包下载:点击此处下载

主程序文件:game.py

准备工作

1、pygame安装

pip install pygame -i https://mirrors.ustc.edu.cn/pypi/web/simple

2、numpy安装

pip install numpy -i https://mirrors.ustc.edu.cn/pypi/web/simple

操作说明


  1. # 运行游戏

  2. python game.py

按键功能
UP向上移动
DOWN向下移动
LEFT向左移动
RIGHT向右移动
回车开火
空格暂停/继续
F1加速
F2减速
F3开启/关闭无敌模式
F5增援我军
ESC退出游戏

代码示例


  1. import window

  2. import tank

  3. import time

  4. import sys

  5. import os

  6. game_stop = False

  7. GAME_SOUND_START = "start.wav"

  8. GAME_SOUND_BG = "base.wav"

  9. '''

  10. 游戏初始化

  11. '''

  12. def game_init():

  13. (width, height) = (60, 40)

  14. _window = window.GameWindow(

  15. gw_tittle="Tank", gw_width=width, gw_height=height, pnt_border=True, bg_line=True)

  16. _tank = tank.Tank(width=width, height=height, debug=False)

  17. return _tank, _window

  18. '''

  19. 坦克大战运行线程

  20. '''

  21. def game_run(_tank, _window):

  22. _tank.run(_window)

  23. _tank.show(_window)

  24. '''

  25. 坦克大战事件线程

  26. '''

  27. def game_event(_tank, _window):

  28. global game_stop

  29. event = _window.event()

  30. if event != _window.EVENT_NONE:

  31. if event == _window.EVENT_QUIT: # ESC退出

  32. _window.quit()

  33. elif event == _window.EVENT_KUP: # 方向键控坦克移动

  34. _tank.t_dir = tank.DIR_UP

  35. elif event == _window.EVENT_KDOWN:

  36. _tank.t_dir = tank.DIR_DOWN

  37. elif event == _window.EVENT_KLEFT:

  38. _tank.t_dir = tank.DIR_LEFT

  39. elif event == _window.EVENT_KRIGHT:

  40. _tank.t_dir = tank.DIR_RIGHT

  41. elif event == _window.EVENT_OK: # 回车开火

  42. _tank.t_fire = True

  43. elif event == _window.EVENT_STOP: # 空格键暂停和继续

  44. if game_stop == False:

  45. game_stop = True

  46. else:

  47. game_stop = False

  48. elif event == _window.EVENT_ADD: # F1速度加

  49. _tank.t_speed += 1

  50. elif event == _window.EVENT_SUB: # F2速度减

  51. _tank.t_speed -= 1

  52. elif event == _window.EVENT_KING: # F3无敌模式

  53. if _tank.t_king == True:

  54. _tank.t_king = False

  55. else:

  56. _tank.t_king = True

  57. elif event == _window.EVENT_HELP: # F5增援我军

  58. _tank.tank_reinforce()

  59. if __name__ == "__main__":

  60. _tank, _window = game_init()

  61. _window.sound_play(GAME_SOUND_START)

  62. while True:

  63. _window.sound_bg_play(GAME_SOUND_BG)

  64. game_event(_tank, _window)

  65. if game_stop != True:

  66. game_run(_tank, _window)

这篇关于Python 坦克大战的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!