使用python写一个推箱子游戏的函数
时间: 2024-03-15 22:44:33 浏览: 15
好的,下面是一个简单的推箱子游戏的 Python 函数实现:
```python
def push_box_game(map):
ROWS = len(map)
COLS = len(map[0])
player_pos = None
boxes = []
goals = []
for r in range(ROWS):
for c in range(COLS):
if map[r][c] == "P":
player_pos = (r, c)
map[r][c] = " "
elif map[r][c] == "B":
boxes.append((r, c))
map[r][c] = " "
elif map[r][c] == "G":
goals.append((r, c))
map[r][c] = " "
def check_win():
for box in boxes:
if box not in goals:
return False
return True
def move_player(dx, dy):
nonlocal player_pos
x, y = player_pos
new_x, new_y = x + dx, y + dy
if not (0 <= new_x < ROWS and 0 <= new_y < COLS):
return False
if map[new_x][new_y] == " ":
player_pos = (new_x, new_y)
return True
for box in boxes:
bx, by = box
if bx == new_x and by == new_y:
new_bx, new_by = bx + dx, by + dy
if not (0 <= new_bx < ROWS and 0 <= new_by < COLS):
return False
if map[new_bx][new_by] == " " and (new_bx, new_by) not in boxes:
box = (new_bx, new_by)
boxes.remove((bx, by))
boxes.append(box)
player_pos = (new_x, new_y)
return True
return False
while not check_win():
print_map(map, player_pos, boxes, goals)
move = input("Enter move (u/d/l/r): ")
dx, dy = 0, 0
if move == "u":
dx, dy = -1, 0
elif move == "d":
dx, dy = 1, 0
elif move == "l":
dx, dy = 0, -1
elif move == "r":
dx, dy = 0, 1
if dx != 0 or dy != 0:
if move_player(dx, dy):
clear_output()
else:
print("Invalid move!")
time.sleep(1)
clear_output()
print_map(map, player_pos, boxes, goals)
print("You won!")
def print_map(map, player_pos, boxes, goals):
ROWS = len(map)
COLS = len(map[0])
for r in range(ROWS):
for c in range(COLS):
if (r, c) == player_pos:
print("P", end="")
elif (r, c) in boxes:
print("B", end="")
elif (r, c) in goals:
print("G", end="")
else:
print(map[r][c], end="")
print()
map = [
["#", "#", "#", "#", "#", "#", "#", "#", "#"],
["#", " ", " ", " ", "B", " ", " ", " ", "#"],
["#", " ", " ", " ", " ", " ", " ", " ", "#"],
["#", " ", " ", " ", " ", " ", " ", " ", "#"],
["#", " ", " ", " ", " ", " ", " ", " ", "#"],
["#", " ", " ", " ", " ", " ", " ", " ", "#"],
["#", " ", " ", " ", " ", " ", "G", " ", "#"],
["#", " ", " ", " ", " ", " ", " ", " ", "#"],
["#", "#", "#", "#", "#", "#", "#", "#", "#"]
]
push_box_game(map)
```
这个函数接受一个地图作为参数,地图是一个二维数组,其中 # 表示墙,空格表示空格子,P 表示玩家,B 表示箱子,G 表示目标点。
函数使用了 Python 的闭包来实现内部函数的访问和修改外部变量。函数中的 `check_win` 函数用于判断游戏是否胜利,`move_player` 函数用于移动玩家和箱子,`print_map` 函数用于输出当前地图状态。函数执行时会进入一个循环,不断等待玩家输入移动指令,然后根据输入来移动玩家和箱子。当所有的箱子都被推到目标点上时,函数会输出胜利信息并结束游戏。
注意:这个函数使用了 `clear_output` 和 `time.sleep` 函数来清除屏幕和暂停一段时间,这些函数只在 Jupyter Notebook 等交互式环境中可用,如果在命令行中运行需要另外实现清屏和暂停功能。