第1关:迷宫游戏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# 全局变量
has_key = False # 玩家是否有钥匙
lives = 3 # 初始生命值为3
flag = False # 标志变量,用于避免重复提示找到钥匙

def input_maze():
maze = []
"""用户输入自定义迷宫,返回二维列表表示迷宫"""
print("请输入迷宫地图(#代表墙, .代表空地, S代表起点, E代表终点, K代表钥匙):")
print("请按行输入地图,或输入 'done' 结束输入:")
# 读入迷宫地图,直到用户输入 'done' 为止
while True:
line = input()
if line.strip().lower() == 'done':
break
maze.append(list(line)) # 每一行存为一个列表,添加到 maze 中

# 验证迷宫是否包含起点和终点
if not validate_maze(maze):
print("迷宫必须有起点(S)和终点(E),请重新输入。")
maze.clear() # 清空迷宫重新输入
input_maze()
return maze

def validate_maze(maze):
"""验证迷宫是否包含起点和终点"""
start_exist = any('S' in row for row in maze) # 检查是否存在起点 S
end_exist = any('E' in row for row in maze) # 检查是否存在终点 E
return start_exist and end_exist

def find_start_exit_pos(maze):
"""找到起点和终点的位置"""
start_pos = None
exit_pos = None
# 遍历迷宫矩阵,寻找 S 和 E 的位置
for i, row in enumerate(maze):
for j, cell in enumerate(row):
if cell == 'S':
start_pos = (i, j)
elif cell == 'E':
exit_pos = (i, j)
return start_pos, exit_pos

def print_maze(maze, player_pos):
"""打印当前迷宫状态以及玩家位置"""
maze_copy = [row[:] for row in maze] # 创建迷宫副本
px, py = player_pos
maze_copy[px][py] = 'P' # 用 P 标记玩家当前位置
# 打印迷宫的每一行
for i, row in enumerate(maze):
for j, cell in enumerate(row):
print(maze_copy[i][j], end='')
print(" ") # 输出迷宫矩阵中的字符
# print() # 换行
print()

def move_player(maze, directionlst, now_pos):
"""根据玩家的输入方向,移动玩家位置"""
global lives # 使用全局变量 lives
before_pos = now_pos # 保存移动前的位置
for dr in directionlst:
row = now_pos[0]
col = now_pos[1]

# 根据输入方向修改玩家位置
if dr == 'w': # 向上
now_pos = (row - 1, col)
elif dr == 's': # 向下
now_pos = (row + 1, col)
elif dr == 'd': # 向右(修改为跳两格)
now_pos = (row, col + 2)
elif dr == 'a': # 向左(修改为跳两格)
now_pos = (row, col - 2)
else: # 无效指令
print("无效的移动指令,请输入 'w', 'a', 's', 'd' 来移动。")
return before_pos

# 检查是否为有效移动
if is_valid_move(now_pos, maze):
get_key(maze, now_pos) # 检查是否拾取钥匙
else:
# 移动无效时减少生命值
lives -= 1
print(f"撞墙了!当前生命值为{lives}")
if lives <= 0: # 生命值用尽
print("你用尽了所有生命,游戏结束")
exit()
print("无法移动到该位置!已回到上一次的位置。")
return before_pos

# 提示找到钥匙(仅限一次)
global flag
if has_key and flag == False:
print("你找到了钥匙!")
flag = True
return now_pos

def is_valid_move(position, maze):
"""检查移动是否有效(未越界且不是墙)"""
row, col = position
# 确保行列在范围内且目标位置不是墙
if 0 <= row < len(maze) and 0 <= col < len(maze[0]):
return maze[row][col] != '#'
return False

def get_key(maze, new_pos):
"""检查玩家是否拾取钥匙"""
global has_key
row, col = new_pos
if maze[row][col] == 'K': # 如果当前位置是钥匙
has_key = True

def main():
"""主函数:处理游戏逻辑"""
map_maze = input_maze() # 输入迷宫
start_pos, exit_pos = find_start_exit_pos(map_maze) # 获取起点和终点位置
before_pos = start_pos
now_pos = None
print("迷宫已生成,目标是从 S 走到E,要求先拿到K,才可以打开出口大门,成功的走出迷宫。")

# 游戏主循环
while True:
print_maze(map_maze, before_pos) # 打印迷宫和玩家位置
print("请输入移动方向 w 上, a 左, s 下, d 右:", end="")
move = input().strip().lower() # 读取玩家输入
print(move, end="\n")
now_pos = move_player(map_maze, move, before_pos) # 更新玩家位置
if now_pos == exit_pos and has_key: # 成功到达终点且有钥匙
print("恭喜你!成功走出了迷宫!")
break
if now_pos == exit_pos and not has_key: # 到达终点但没有钥匙
now_pos = before_pos
print("你需要钥匙才能进入终点!")
print("已经退回上一步位置!")
before_pos = now_pos

# 运行游戏
if __name__ == "__main__":
main()

第2关:荒岛求生

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# 玩家职业定义,player_classes是一个字典,请仔细阅读并理解
player_classes = {
'猎人': {'health': 120, 'hunger': 40, 'thirst': 40, 'energy': 60, 'resources': {'food': 3, 'water': 2, 'wood': 1}, 'skill': '捕猎'},
'农夫': {'health': 100, 'hunger': 30, 'thirst': 50, 'energy': 50, 'resources': {'food': 4, 'water': 2, 'wood': 0}, 'skill': '种植'},
'科学家': {'health': 90, 'hunger': 50, 'thirst': 50, 'energy': 70, 'resources': {'food': 2, 'water': 2, 'wood': 0, 'tools': 1}, 'skill': '发明工具'},
}
#探索事件字典
explore_events = {'event_1':
"暴风雨来袭,木材被摧毁!",'event_2':
"野兽袭击,生命值减少20!",'event_3':
"天气晴朗,额外获得一份食物和水!",'event_4':
"找到隐藏的宝箱,获得5木材!",'event_5':
"资源稀缺,食物和水减少一半!"
}

def create_player(class_name):
"""初始化玩家"""
if class_name in player_classes:
player = player_classes[class_name] # 创建玩家属性
player['class'] = class_name # 保存玩家职业
print(f"你选择的职业是: {class_name}")
return player
else:
print("无效的职业!")
return None

def display_status(player):
"""显示玩家状态"""
print(f"\n职业: {player['class']} (技能: {player['skill']})")
print(f"生命值: {player['health']}")
print(f"饥饿值: {player['hunger']}")
print(f"口渴值: {player['thirst']}")
print(f"能量值: {player['energy']}")
print(f"资源: {player['resources']}\n")

def eat_food(player):
"""吃食物:吃一份食物,资源中food值减1,玩家饥饿值减少20,并输出:你吃了一份食物!饥饿值减少。但如果食物不足,则输出:没有食物可以吃!"""
if player['resources']['food'] > 0:
player['resources']['food'] -= 1
player['hunger'] = max(0, player['hunger'] - 20)
print("你吃了一份食物!饥饿值减少。")
else:
print("没有食物可以吃!")

def drink_water(player):
"""喝水:喝一次水,资源中water值减1,玩家口渴值减少20,并输出:你喝了一杯水!口渴值减少。但如果水不足,则输出:没有水可以喝!"""
if player['resources']['water'] > 0:
player['resources']['water'] -= 1
player['thirst'] = max(0, player['thirst'] - 20)
print("你喝了一杯水!口渴值减少。")
else:
print("没有水可以喝!")

def rest(player):
"""休息:能量值增加20,不能超过100。"""
player['energy'] = min(100, player['energy'] + 20)
print("你休息了一会儿,能量值恢复了。")

def gather_resources(player):
"""采集资源:玩家资源中的食物+2,水+1,木材+1,并输出:你采集到了资源:2食物,1水,1木材。"""
player['resources']['food'] += 2
player['resources']['water'] += 1
player['resources']['wood'] += 1
print("你采集到了资源:2食物,1水,1木材。")

def explore(player,event):
"""探索事件"""
print("你决定去探索...")
event_item = explore_events[event]
print(f"探索事件发生: {event_item}")

# 处理不同的探索事件
if "暴风雨" in event_item:
player['resources']['wood'] = max(0, player['resources']['wood'] - 1)
elif "野兽袭击" in event_item:
player['health'] -= 0
elif "天气晴朗" in event_item:
player['resources']['food'] += 1
player['resources']['water'] += 1
elif "宝箱" in event_item:
player['resources']['wood'] += 5
elif "资源稀缺" in event_item:
player['resources']['food'] = max(0, player['resources']['food'] // 2)
player['resources']['water'] = max(0, player['resources']['water'] // 2)

def use_skill(player):
"""使用职业技能:不同类型的玩家使用技能获得不同的收入"""
if player['skill'] == '捕猎':
player['resources']['food'] += 3
print("你使用猎人的捕猎技能,成功获得额外的食物!")
elif player['skill'] == '种植':
player['resources']['food'] += 1
print("你使用农夫的种植技能,成功种植了食物,未来几轮获得额外资源!")
elif player['skill'] == '发明工具':
if 'tools' in player['resources']:
player['resources']['tools'] += 1
else:
player['resources']['tools'] = 1
print("你使用科学家的发明技能,成功制造了工具,采集效率提升!")

def main():
"""游戏主循环"""
print("请选择职业(猎人、农夫、科学家): ")
class_name = input()
player = create_player(class_name)
if player is None:
return # 职业无效,结束程序

while player['health'] > 0:
display_status(player)
print("你想做什么?(吃食物/喝水/休息/采集资源/探索:event1-5/使用技能/退出): ")
action = input()

if action == "吃食物":
eat_food(player)
elif action == "喝水":
drink_water(player)
elif action == "休息":
rest(player)
elif action == "采集资源":
gather_resources(player)
elif action in ['event_1', 'event_2', 'event_3', 'event_4', 'event_5']:
explore(player,action)
elif action == "使用技能":
use_skill(player)
elif action == "退出":
print("退出游戏。")
break
else:
print("无效的操作!")

# 简单的状态更新
player['hunger'] += 5
player['thirst'] += 5
player['energy'] -= 10

# 检查状态
if player['hunger'] > 100:
player['health'] -= 10
print("你太饿了!生命值下降。")
if player['thirst'] > 100:
player['health'] -= 10
print("你太渴了!生命值下降。")
if player['energy'] < 0:
print("你累倒了,游戏结束!")
break

print("游戏结束!")

if __name__ == "__main__":
main()