python 写一段魂斗罗的程序
时间: 2023-08-28 19:06:44 浏览: 113
好的,以下是一个简单的魂斗罗游戏程序:
```python
import random
# 初始化游戏地图
MAP_WIDTH = 20
MAP_HEIGHT = 10
MAP = [[' ' for _ in range(MAP_WIDTH)] for _ in range(MAP_HEIGHT)]
# 初始化玩家坐标
PLAYER_X = 0
PLAYER_Y = 0
# 初始化敌人坐标
ENEMY_X = MAP_WIDTH - 1
ENEMY_Y = MAP_HEIGHT - 1
# 初始化玩家生命值
PLAYER_LIFE = 3
# 初始化游戏结束标志
GAME_OVER = False
# 定义绘制游戏地图函数
def draw_map():
for row in MAP:
print('|', end='')
for cell in row:
print(cell, end='')
print('|')
# 定义绘制游戏状态函数
def draw_status():
print('生命值: ', PLAYER_LIFE)
# 定义移动玩家函数
def move_player(direction):
global PLAYER_X, PLAYER_Y, PLAYER_LIFE
if direction == 'up':
if PLAYER_Y > 0:
PLAYER_Y -= 1
elif direction == 'down':
if PLAYER_Y < MAP_HEIGHT - 1:
PLAYER_Y += 1
elif direction == 'left':
if PLAYER_X > 0:
PLAYER_X -= 1
elif direction == 'right':
if PLAYER_X < MAP_WIDTH - 1:
PLAYER_X += 1
# 碰到敌人,减少生命值
if PLAYER_X == ENEMY_X and PLAYER_Y == ENEMY_Y:
PLAYER_LIFE -= 1
# 定义移动敌人函数
def move_enemy():
global ENEMY_X, ENEMY_Y
if ENEMY_X > 0:
ENEMY_X -= 1
else:
ENEMY_X = MAP_WIDTH - 1
# 初始化游戏地图
MAP[PLAYER_Y][PLAYER_X] = 'P'
MAP[ENEMY_Y][ENEMY_X] = 'E'
# 开始游戏循环
while not GAME_OVER:
# 绘制游戏地图和状态
draw_map()
draw_status()
# 玩家移动
direction = input('请输入移动方向(up/down/left/right): ')
move_player(direction)
# 敌人移动
move_enemy()
# 更新游戏地图
MAP = [[' ' for _ in range(MAP_WIDTH)] for _ in range(MAP_HEIGHT)]
MAP[PLAYER_Y][PLAYER_X] = 'P'
MAP[ENEMY_Y][ENEMY_X] = 'E'
# 判断游戏是否结束
if PLAYER_LIFE <= 0:
print('游戏结束,你输了!')
GAME_OVER = True
elif ENEMY_X == PLAYER_X and ENEMY_Y == PLAYER_Y:
print('游戏结束,你赢了!')
GAME_OVER = True
```
这个程序实现了一个简单的魂斗罗游戏,玩家可以通过输入指令移动自己的角色,在地图上与敌人对抗,当玩家生命值为0或者成功击败敌人时游戏结束。
阅读全文