Python 推箱子游戏代码示例 - 使用面向对象编程
这是一个简单的推箱子游戏的 Python 代码示例,使用面向对象编程方式实现游戏逻辑。
class Box:
def __init__(self, position):
self.position = position
class Player:
def __init__(self, position):
self.position = position
class Game:
def __init__(self, grid, player, boxes, targets):
self.grid = grid
self.player = player
self.boxes = boxes
self.targets = targets
def move_player(self, direction):
new_position = self.player.position + direction
if self.is_valid_move(new_position):
self.player.position = new_position
def move_box(self, box, direction):
new_position = box.position + direction
if self.is_valid_move(new_position) and not self.is_box_blocked(new_position):
box.position = new_position
def is_valid_move(self, position):
return 0 <= position.x < len(self.grid[0]) and 0 <= position.y < len(self.grid) and self.grid[position.y][position.x] != '#'
def is_box_blocked(self, position):
return any(box.position == position for box in self.boxes)
def is_game_won(self):
return all(box.position in self.targets for box in self.boxes)
# 示例用法
grid = [
['#', '#', '#', '#', '#', '#', '#'],
['#', ' ', ' ', ' ', ' ', ' ', '#'],
['#', ' ', '#', '#', '#', ' ', '#'],
['#', ' ', 'T', 'B', ' ', ' ', '#'],
['#', ' ', 'P', ' ', ' ', ' ', '#'],
['#', '#', '#', '#', '#', '#', '#'],
]
player = Player(Position(4, 4))
boxes = [Box(Position(3, 2))]
targets = [Position(2, 2)]
game = Game(grid, player, boxes, targets)
while not game.is_game_won():
print("Enter your move: 'up', 'down', 'left', 'right' ")
direction = input()
if direction == 'up':
game.move_player(Position(0, -1))
elif direction == 'down':
game.move_player(Position(0, 1))
elif direction == 'left':
game.move_player(Position(-1, 0))
elif direction == 'right':
game.move_player(Position(1, 0))
for box in game.boxes:
if game.player.position == box.position:
if direction == 'up':
game.move_box(box, Position(0, -1))
elif direction == 'down':
game.move_box(box, Position(0, 1))
elif direction == 'left':
game.move_box(box, Position(-1, 0))
elif direction == 'right':
game.move_box(box, Position(1, 0))
# 打印当前游戏状态
for y in range(len(grid)):
for x in range(len(grid[0])):
position = Position(x, y)
if position == game.player.position:
print('P', end=' ')
elif position in [box.position for box in game.boxes]:
print('B', end=' ')
elif position in game.targets:
print('T', end=' ')
else:
print(grid[y][x], end=' ')
print()
这是一个简单的推箱子游戏的示例。你可以根据自己的需求进行修改和扩展。祝你玩得开心!
原文地址: https://www.cveoy.top/t/topic/Sg7 著作权归作者所有。请勿转载和采集!