python小游戏迷宫
时间: 2025-01-06 08:34:22 浏览: 5
### 如何用Python创建迷宫小游戏
为了构建一个基于Python的迷宫小游戏,通常会选择`pygame`库作为图形界面工具[^1]。下面展示了一个简化版的游戏框架,该框架包含了迷宫生成、玩家控制以及基本碰撞检测等功能。
#### 安装依赖项
如果尚未安装所需的库,则可以通过命令行执行如下指令完成安装:
```bash
pip install pygame
```
#### 导入必要的模块并初始化Pygame环境
在编写具体逻辑之前,先要导入需要用到的标准库和其他第三方包,并设置好初始状态以便后续操作。
```python
import sys
import random
import pygame as pg
pg.init()
screen_width, screen_height = 800, 600
window_surface = pg.display.set_mode((screen_width, screen_height))
clock = pg.time.Clock()
# 设置颜色常量
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
def draw_text(text, font_size=74):
"""绘制文字"""
myfont = pg.font.SysFont('Comic Sans MS', font_size)
textsurface = myfont.render(str(text), False, WHITE)
return textsurface
```
#### 迷宫结构定义与随机生成算法实现
这里采用了一种简单的方法来自动生成迷宫地图;实际应用中可以根据需求调整复杂度更高的生成策略。
```python
class Cell(object):
def __init__(self, x, y, walls=None):
self.x = x
self.y = y
if not walls:
self.walls = {'top': True,
'right': True,
'bottom': True,
'left': True}
else:
self.walls = walls
def make_maze(w=16, h=12):
cells = [[Cell(x=x, y=y) for y in range(h)] for x in range(w)]
verticals = [["| "] * w + ['\n'] for _ in range(h)]
horizontals = [['+---'] * w + ['+\n']]
def break_wall(cell_1, cell_2):
dx = cell_2.x - cell_1.x
dy = cell_2.y - cell_1.y
if dx == 1 and dy == 0: # 右边相邻单元格
cell_1.walls['right'], cell_2.walls['left'] = False, False
elif dx == -1 and dy == 0: # 左边相邻单元格
cell_1.walls['left'], cell_2.walls['right'] = False, False
elif dx == 0 and dy == 1: # 下方相邻单元格
cell_1.walls['bottom'], cell_2.walls['top'] = False, False
elif dx == 0 and dy == -1: # 上方相邻单元格
cell_1.walls['top'], cell_2.walls['bottom'] = False, False
else:
raise Exception(f'无法连接两个不相邻的单元格 {cell_1} 和 {cell_2}')
visited = set()
def visit(r, c):
if (r, c) in visited or r < 0 or c < 0 or r >= h or c >= w:
return
stack = [(r, c)]
while len(stack) > 0:
current_r, current_c = stack[-1]
neighbors = []
delta = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for dr, dc in delta:
nr, nc = current_r + dr, current_c + dc
if nr < 0 or nc < 0 or nr >= h or nc >= w \
or ((nr, nc) in visited):
continue
neighbors.append((nr, nc))
if len(neighbors) == 0:
stack.pop()
continue
next_neighbor = random.choice(neighbors)
rn, cn = next_neighbor
break_wall(cells[current_c][current_r], cells[cn][rn])
visited.add(next_neighbor)
stack.append(next_neighbor)
visit(random.randint(0,h-1),random.randint(0,w-1))
for i in range(len(verticals)):
for j in range(len(horizontal)):
char_index = int(j / 4)
vchar_index = int(i/2)
if not cells[char_index][vchar_index].walls["top"]:
horizontal[i*2]=horizontal[i*2][:j]+' '+horizontal[i*2][j+1:]
if not cells[char_index][vchar_index].walls["left"]and j%4==0 :
vertical[vchar_index*2+i//h]=vertical[vchar_index*2+i//h][:j]+ " "+vertical[vchar_index*2+i//h][j+1:]
maze_str=""
for line in horizontals+verticals[:-1]:
maze_str+= ''.join(line)
return maze_str.splitlines(),cells[0][0],cells[w-1][h-1]
maze_lines,start,end=make_maze()
for row,line in enumerate(maze_lines):
print("".join(line).replace("+","█").replace("-","─").replace("|","│"))
print("\n起点:",start,"\n终点:",end)
```
上述代码实现了迷宫的地图表示形式及其可视化输出功能。通过调用函数 `make_maze()` 即可获得由字符串组成的二维数组描述的一个新迷宫实例,其中包含起始位置和目标位置的信息。
#### 主程序循环设计
最后一步就是搭建整个游戏运行的核心部分——事件监听器与渲染机制相结合形成交互式的体验效果。
```python
player_pos=start
while True:
window_surface.fill(BLACK)
keys_pressed = pg.key.get_pressed()
new_player_pos=[player_pos.x,player_pos.y]
if keys_pressed[pg.K_LEFT]:
new_player_pos[0]-=1
elif keys_pressed[pg.K_RIGHT]:
new_player_pos[0]+=1
elif keys_pressed[pg.K_UP]:
new_player_pos[1]-=1
elif keys_pressed[pg.K_DOWN]:
new_player_pos[1]+=1
try:
target_cell=maze[new_player_pos[0]][new_player_pos[1]]
if all([not wall for wall in list(target_cell.walls.values())]):
player_pos=target_cell
if player_pos==end:
print("恭喜通关!")
break
except IndexError:
pass
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
for idx,row in enumerate(maze_lines):
text_surf = draw_text(row.replace('+',' ').replace('-',' ').replace('|',' '))
window_surface.blit(text_surf,(0,idx*text_surf.get_height()))
player_rect = pg.Rect(player_pos.x*(text_surf.get_width()/len(max(maze_lines,key=len))),\
player_pos.y*(text_surf.get_height()),\
text_surf.get_width()/len(max(maze_lines,key=len)),\
text_surf.get_height())
pg.draw.rect(window_surface,WHITE,player_rect)
clock.tick(30)
pg.display.flip()
```
这段脚本负责处理用户的键盘输入动作,并据此更新角色的位置坐标,在每次迭代过程中重新绘制场景画面直至达到胜利条件为止。
阅读全文