编写一个推箱子的代码
推箱子游戏是一种经典的智力游戏,玩家需要操作人物将箱子移动到指定位置,最终完成所有关卡的挑战。下面是一个简单的推箱子游戏代码示例,使用 Python 语言编写。
游戏规则:
- 人物可以向上、下、左、右四个方向移动,每次只能移动一格。
- 箱子也可以向四个方向移动,但只能在人物推动的情况下移动。
- 箱子不能被推到障碍物或墙壁上,只能被推到空地上或目标位置上。
- 当所有箱子都被推到目标位置上时,游戏胜利。
代码实现:
# -*- coding: utf-8 -*-
# 地图数据
MAP_DATA = [
"#######",
"# #",
"# o #",
"# #",
"# x #",
"# #",
"#######"
]
# 定义地图元素类型
ELEMENT_EMPTY = " "
ELEMENT_WALL = "#"
ELEMENT_BOX = "o"
ELEMENT_TARGET = "x"
ELEMENT_PLAYER = "P"
# 初始化游戏状态
player_row, player_col = 2, 3 # 初始化人物位置
box_positions = [(2, 4)] # 初始化箱子位置
# 游戏循环
while True:
# 打印地图
for row in range(len(MAP_DATA)):
for col in range(len(MAP_DATA[row])):
if row == player_row and col == player_col:
print(ELEMENT_PLAYER, end="")
elif (row, col) in box_positions:
print(ELEMENT_BOX, end="")
else:
print(MAP_DATA[row][col], end="")
print()
# 判断是否胜利
if all([(row, col) in box_positions for row, col in target_positions]):
print("Congratulations, you win!")
break
# 获取玩家输入
direction = input("Please enter direction (w/s/a/d): ")
# 移动人物
if direction == "w":
if MAP_DATA[player_row - 1][player_col] != ELEMENT_WALL and (player_row - 1, player_col) not in box_positions:
player_row -= 1
elif MAP_DATA[player_row - 1][player_col] != ELEMENT_WALL and (player_row - 1, player_col) in box_positions:
if MAP_DATA[player_row - 2][player_col] != ELEMENT_WALL and (player_row - 2, player_col) not in box_positions:
player_row -= 1
box_positions.remove((player_row, player_col))
box_positions.append((player_row - 1, player_col))
elif direction == "s":
if MAP_DATA[player_row + 1][player_col] != ELEMENT_WALL and (player_row + 1, player_col) not in box_positions:
player_row += 1
elif MAP_DATA[player_row + 1][player_col] != ELEMENT_WALL and (player_row + 1, player_col) in box_positions:
if MAP_DATA[player_row + 2][player_col] != ELEMENT_WALL and (player_row + 2, player_col) not in box_positions:
player_row += 1
box_positions.remove((player_row, player_col))
box_positions.append((player_row + 1, player_col))
elif direction == "a":
if MAP_DATA[player_row][player_col - 1] != ELEMENT_WALL and (player_row, player_col - 1) not in box_positions:
player_col -= 1
elif MAP_DATA[player_row][player_col - 1] != ELEMENT_WALL and (player_row, player_col - 1) in box_positions:
if MAP_DATA[player_row][player_col - 2] != ELEMENT_WALL and (player_row, player_col - 2) not in box_positions:
player_col -= 1
box_positions.remove((player_row, player_col))
box_positions.append((player_row, player_col - 1))
elif direction == "d":
if MAP_DATA[player_row][player_col + 1] != ELEMENT_WALL and (player_row, player_col + 1) not in box_positions:
player_col += 1
elif MAP_DATA[player_row][player_col + 1] != ELEMENT_WALL and (player_row, player_col + 1) in box_positions:
if MAP_DATA[player_row][player_col + 2] != ELEMENT_WALL and (player_row, player_col + 2) not in box_positions:
player_col += 1
box_positions.remove((player_row, player_col))
box_positions.append((player_row, player_col + 1))
原文地址: https://www.cveoy.top/t/topic/bBTY 著作权归作者所有。请勿转载和采集!