我正在编写一个简单的迷宫游戏。我已经创建了一个带有move方法的Player类——但是每当我想检查移动是否在可用路径列表中时,它都会运行move方法并改变我的角色位置。
class Player :
def __init__ (self, position):
self.position = position
def move (self, direction):
if direction == "right": self.position[0] += 1
elif direction == "left": self.position[0] -= 1
elif direction == "up": self.position[1] -= 1
elif direction == "down": self.position[1] += 1
return self.position
maze_paths = [[0,0], [1,0]]
mac = Player([0,0])
direction = 'left'
if mac.move(direction) in maze_paths:
print('ok')
else:
print('No way!')
print('Final position is: %r' % (mac.position))
我期望的输出是:
No way!
Final position is: [0, 0]
…因为按照迷宫的定义,向左移动是不允许的。然而,我们拥有的是:
No way!
Final position is: [-1, 0]
…尽管这是不允许的,但还是发生了。 问题来源StackOverflow 地址:/questions/59381683/making-a-function-in-an-if-only-take-action-when-a-condition-is-true
正如@TimRichardson在评论中建议的那样,计算状态的行为应该从改变状态的行为中分离出来。函数式编程语言是为了简化这一过程而构建的,但Python不是——因此您需要克服一些困难。 考虑将move分成两个方法,如下所示的calculate_move和do_move:
class Player:
def calculate_move(self, direction):
"""Calculate where we would be if we moved in a direction"""
emulated_position = self.position[:] # make a copy
if direction == "right": emulated_position[0] += 1
elif direction == "left": emulated_position[0] -= 1
elif direction == "up": emulated_position[1] -= 1
elif direction == "down": emulated_position[1] += 1
return emulated_position
def do_move(self, direction):
"""Actually move in the given direction"""
self.position = self.calculate_move(direction)
maze_paths = [[0,0], [1,0]]
mac = Player([0,0])
direction = 'left'
if mac.calculate_move(direction) in maze_paths:
mac.do_move(direction)
print('ok')
else:
print('No way!')
print('Final position is: %r' % mac.position)
…适当发出作为输出:
No way!
Final position is: [0, 0]
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。