Skip to content

Commit aba3333

Browse files
[投稿] 添加脚本: 迷宫小游戏 — by Daoyu268
1 parent a46bfeb commit aba3333

1 file changed

Lines changed: 108 additions & 0 deletions

File tree

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import random
2+
3+
# ------------- 核心配置 -------------
4+
MAZE_SIZE = 15 # 迷宫大小 (奇数)
5+
PLAYER = "P" # 玩家
6+
EXIT = "E" # 出口
7+
WALL = "■" # 墙
8+
PATH = " " # 路径
9+
10+
# ------------- 核心函数 -------------
11+
def generate_maze(size):
12+
"""生成迷宫 (简化版,100% 有解)"""
13+
maze = [[WALL for _ in range(size)] for _ in range(size)]
14+
15+
# 从起点开始,随机打通路径
16+
x, y = 1, 1
17+
maze[y][x] = PATH
18+
19+
# 简单的随机游走算法,确保迷宫连通
20+
for _ in range(size * size // 2):
21+
# 随机选一个方向
22+
dx, dy = random.choice([(0,1), (0,-1), (1,0), (-1,0)])
23+
nx, ny = x + dx, y + dy
24+
25+
# 检查是否在边界内且是墙
26+
if 1 <= nx < size-1 and 1 <= ny < size-1 and maze[ny][nx] == WALL:
27+
maze[ny][nx] = PATH
28+
x, y = nx, ny
29+
30+
# 确保出口是通路
31+
maze[size-2][size-2] = PATH
32+
return maze
33+
34+
def print_screen(maze, px, py, ex, ey):
35+
"""直接打印迷宫,不使用任何系统清屏函数"""
36+
print("\n" * 5) # 打印空行模拟清屏
37+
size = MAZE_SIZE
38+
for y in range(size):
39+
line = []
40+
for x in range(size):
41+
if x == px and y == py:
42+
line.append(PLAYER)
43+
elif x == ex and y == ey:
44+
line.append(EXIT)
45+
else:
46+
line.append(maze[y][x])
47+
print(''.join(line))
48+
49+
def show_menu():
50+
"""显示操作菜单"""
51+
print("\n===== [虚拟按钮] =====")
52+
print("1. 向上 2. 向下")
53+
print("3. 向左 4. 向右")
54+
print("5. 重置游戏")
55+
print("======================")
56+
57+
def main():
58+
maze = generate_maze(MAZE_SIZE)
59+
px, py = 1, 1 # 玩家起点
60+
ex, ey = MAZE_SIZE-2, MAZE_SIZE-2 # 出口
61+
62+
print("欢迎来到终端迷宫游戏!")
63+
print("指令: 1/2/3/4 移动, 5 重置")
64+
65+
while True:
66+
print_screen(maze, px, py, ex, ey)
67+
show_menu()
68+
69+
# 获取用户输入
70+
try:
71+
cmd = int(input("\n请输入操作: "))
72+
except:
73+
print("输入错误,请输入数字 1-5!")
74+
continue
75+
76+
# 处理移动
77+
dx, dy = 0, 0
78+
if cmd == 1: dy = -1
79+
elif cmd == 2: dy = 1
80+
elif cmd == 3: dx = -1
81+
elif cmd == 4: dx = 1
82+
elif cmd == 5:
83+
print("重置迷宫...")
84+
maze = generate_maze(MAZE_SIZE)
85+
px, py = 1, 1
86+
continue
87+
else:
88+
print("无效指令!")
89+
continue
90+
91+
# 计算新位置
92+
nx, ny = px + dx, py + dy
93+
94+
# 检查碰撞 (不能撞墙,不能出界)
95+
if (0 <= nx < MAZE_SIZE and
96+
0 <= ny < MAZE_SIZE and
97+
maze[ny][nx] != WALL):
98+
px, py = nx, ny
99+
100+
# 检查胜利
101+
if px == ex and py == ey:
102+
print("\n🎉 恭喜你!成功到达终点!")
103+
input("按回车键继续...")
104+
maze = generate_maze(MAZE_SIZE)
105+
px, py = 1, 1
106+
107+
if __name__ == "__main__":
108+
main()

0 commit comments

Comments
 (0)