这是卡片游戏(项目)的一个示例我试图创建
p1 = []
p2 = []
player_list = [p1,p2]
def hit(self):
self.append(random.choice(Deck))
print(self)
for player in player_list:
print('Player')
play = input('Hit or Stay >> ')
if play != 'hit' or play != 'stay': continue
if play == 'hit':
hit(player)
print(player)
if play == 'stay':
print(player)
print (player_list)
当您运行代码时,它不会从hit()函数更新播放器。 谁能告诉我为什么收到这个结果?
答案 0 :(得分:3)
这个条件
if play != 'hit' or play != 'stay': continue
总是如此:总是要么不被击中'是否留下'
应该是'和':
if play != 'hit' and play != 'stay': continue
更多Pythonic表达式是:
if play not in ('hit', 'stay'):
continue
您还应该考虑诸如“HIT'”之类的变体。我更喜欢将输入转换为大写。例如,
if play.upper() not in ('HIT', 'STAY'):
continue
答案 1 :(得分:0)
像往常一样,将代码分解为小的,单一用途的函数,事情变得更容易理解。
def ask():
result = None
while result not in ('hit', 'stay'):
result = raw_input('hit or stay? >> ')
return result
def process(player, command):
if command == 'hit':
hit(player)
for player in players:
command = ask()
process(player, command)
print player
现在您可以独立确保每个都有效。 ask
中的错误比原始代码的整个交错逻辑更容易检测。