Python 坦克大战
运行环境:python3.8.3+pygame1.9.6
代码包下载:点击此处下载
主程序文件:game.py
准备工作
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
操作说明
-
# 运行游戏
-
python game.py
按键 | 功能 |
---|---|
UP | 向上移动 |
DOWN | 向下移动 |
LEFT | 向左移动 |
RIGHT | 向右移动 |
回车 | 开火 |
空格 | 暂停/继续 |
F1 | 加速 |
F2 | 减速 |
F3 | 开启/关闭无敌模式 |
F5 | 增援我军 |
ESC | 退出游戏 |
代码示例
-
import window
-
import tank
-
import time
-
import sys
-
import os
-
game_stop = False
-
GAME_SOUND_START = "start.wav"
-
GAME_SOUND_BG = "base.wav"
-
'''
-
游戏初始化
-
'''
-
def game_init():
-
(width, height) = (60, 40)
-
_window = window.GameWindow(
-
gw_tittle="Tank", gw_width=width, gw_height=height, pnt_border=True, bg_line=True)
-
_tank = tank.Tank(width=width, height=height, debug=False)
-
return _tank, _window
-
'''
-
坦克大战运行线程
-
'''
-
def game_run(_tank, _window):
-
_tank.run(_window)
-
_tank.show(_window)
-
'''
-
坦克大战事件线程
-
'''
-
def game_event(_tank, _window):
-
global game_stop
-
event = _window.event()
-
if event != _window.EVENT_NONE:
-
if event == _window.EVENT_QUIT: # ESC退出
-
_window.quit()
-
elif event == _window.EVENT_KUP: # 方向键控坦克移动
-
_tank.t_dir = tank.DIR_UP
-
elif event == _window.EVENT_KDOWN:
-
_tank.t_dir = tank.DIR_DOWN
-
elif event == _window.EVENT_KLEFT:
-
_tank.t_dir = tank.DIR_LEFT
-
elif event == _window.EVENT_KRIGHT:
-
_tank.t_dir = tank.DIR_RIGHT
-
elif event == _window.EVENT_OK: # 回车开火
-
_tank.t_fire = True
-
elif event == _window.EVENT_STOP: # 空格键暂停和继续
-
if game_stop == False:
-
game_stop = True
-
else:
-
game_stop = False
-
elif event == _window.EVENT_ADD: # F1速度加
-
_tank.t_speed += 1
-
elif event == _window.EVENT_SUB: # F2速度减
-
_tank.t_speed -= 1
-
elif event == _window.EVENT_KING: # F3无敌模式
-
if _tank.t_king == True:
-
_tank.t_king = False
-
else:
-
_tank.t_king = True
-
elif event == _window.EVENT_HELP: # F5增援我军
-
_tank.tank_reinforce()
-
if __name__ == "__main__":
-
_tank, _window = game_init()
-
_window.sound_play(GAME_SOUND_START)
-
while True:
-
_window.sound_bg_play(GAME_SOUND_BG)
-
game_event(_tank, _window)
-
if game_stop != True:
-
game_run(_tank, _window)