基于python推箱子小游戏代码
时间: 2024-10-10 16:04:39 浏览: 77
Python推箱子游戏通常是一个经典的编程练习,它涉及迷宫导航、物体移动和目标达成等策略元素。这里提供一个简单的基于命令行的推箱子游戏代码示例:
```python
import sys
# 定义棋盘大小和初始状态
ROW = COL = 4
start_box = (0, 2)
goal = (3, 3)
def print_board(board):
for row in board:
print(' '.join(str(cell) for cell in row))
class Box:
def __init__(self, pos):
self.pos = pos
self.moved = False
class Player:
def move(self, dx, dy):
self.board.move_player(dx, dy)
if self.board.is_goal_reached():
print("You have won!")
sys.exit()
def main():
board = Board(ROW, COL, start_box, goal)
player = Player()
while True:
print_board(board.grid)
cmd = input("Enter command (e/n/s/w or x/y): ")
x, y = map(int, cmd.split())
player.move(x - 1, y - 1)
board.update_grid(player, Box(start_box))
if __name__ == "__main__":
main()
```
在这个代码中,`Box`类代表箱子,`Player`类代表玩家,`Board`类负责处理游戏状态和规则,如移动、碰撞检测和目标判断。玩家通过输入指令控制方向。
阅读全文