写一个推箱子小游戏代码
时间: 2023-12-25 11:04:23 浏览: 151
好的,以下是一个简单的推箱子小游戏的代码,使用Python语言实现:
```python
# 推箱子小游戏
# 地图
map = [
"#####",
"# #",
"# O #",
"# X#",
"#####"
]
# 将地图转换成二维数组
map_rows = len(map)
map_cols = len(map[0])
map_arr = []
for i in range(map_rows):
row = []
for j in range(map_cols):
row.append(map[i][j])
map_arr.append(row)
# 找到人物和箱子的位置
person_pos = None
box_pos = None
for i in range(map_rows):
for j in range(map_cols):
if map_arr[i][j] == "O":
person_pos = (i, j)
elif map_arr[i][j] == "X":
box_pos = (i, j)
# 显示地图
def show_map():
for i in range(map_rows):
for j in range(map_cols):
print(map_arr[i][j], end="")
print()
# 移动人物
def move_person(direction):
global person_pos
row, col = person_pos
if direction == "up":
if map_arr[row-1][col] == " ":
map_arr[row][col] = " "
map_arr[row-1][col] = "O"
person_pos = (row-1, col)
elif map_arr[row-1][col] == "X":
if map_arr[row-2][col] == " ":
map_arr[row][col] = " "
map_arr[row-1][col] = "O"
map_arr[row-2][col] = "X"
person_pos = (row-1, col)
box_pos = (row-2, col)
elif direction == "down":
if map_arr[row+1][col] == " ":
map_arr[row][col] = " "
map_arr[row+1][col] = "O"
person_pos = (row+1, col)
elif map_arr[row+1][col] == "X":
if map_arr[row+2][col] == " ":
map_arr[row][col] = " "
map_arr[row+1][col] = "O"
map_arr[row+2][col] = "X"
person_pos = (row+1, col)
box_pos = (row+2, col)
elif direction == "left":
if map_arr[row][col-1] == " ":
map_arr[row][col] = " "
map_arr[row][col-1] = "O"
person_pos = (row, col-1)
elif map_arr[row][col-1] == "X":
if map_arr[row][col-2] == " ":
map_arr[row][col] = " "
map_arr[row][col-1] = "O"
map_arr[row][col-2] = "X"
person_pos = (row, col-1)
box_pos = (row, col-2)
elif direction == "right":
if map_arr[row][col+1] == " ":
map_arr[row][col] = " "
map_arr[row][col+1] = "O"
person_pos = (row, col+1)
elif map_arr[row][col+1] == "X":
if map_arr[row][col+2] == " ":
map_arr[row][col] = " "
map_arr[row][col+1] = "O"
map_arr[row][col+2] = "X"
person_pos = (row, col+1)
box_pos = (row, col+2)
# 判断是否胜利
def is_win():
if map_arr[box_pos[0]][box_pos[1]] == "X":
return True
else:
return False
# 游戏循环
while True:
# 显示地图
show_map()
# 判断是否胜利
if is_win():
print("You win!")
break
# 获取用户输入
direction = input("Please input direction(up/down/left/right): ")
# 移动人物
move_person(direction)
```
运行代码后,会在命令行窗口中显示游戏地图,玩家需要通过输入方向来移动人物,将箱子推到指定位置即可获胜。
阅读全文