Python中石头剪子布游戏的问题
我现在正在用Python编写一个石头、剪刀、布的小游戏,不过我遇到了一些问题。虽然游戏能运行,但代码有点粗糙。我想让程序在玩家出错时提醒他们,但在测试时,程序却随机告诉玩家他们出错了,实际上他们并没有出错。下面是我遇到问题的那段代码,这不是整个游戏的代码。
def game(self):
print "This is rock, paper, scissors!"
rps = ('rock', 'paper', 'scissors')
comp1 = raw_input("Rock, paper or scissors?\n> ")
comp2 = random.choice(rps)
if comp1 == 'rock' and comp2 == 'scissors' or comp1 == 'scissors' and comp2 == 'paper' or comp1 == 'paper' and comp2 == 'rock':
print "You won! The computer chose %s" % comp2
return "game"
elif comp1 == 'rock' and comp2 == 'rock':
print "In a stalemate, there are no winners, only losers :)\nThe computer also chose %s" % comp2
return "game"
elif comp1 == 'scissors' and comp2 == 'scissors':
print "In a stalemate, there are no winners, only losers :)\nThe computer also chose %s" % comp2
return "game"
elif comp1 == 'paper' and comp2 == 'paper':
print "In a stalemate, there are no winners, only losers :)\nThe computer also chose %s" % comp2
return "game"
elif comp1 != 'rock' or 'scissors' or 'paper':
print "Try choosing between rock, paper and scissors next time. It might help.
return "game"
else:
print "The computer %s. You have failed. Problem?" % comp2
return "game"
4 个回答
你这里的逻辑有问题,elif comp1 != 'rock' or 'scissors' or 'paper':
这行代码不太对。因为字符串 'scissors' 和 'paper' 会被当作布尔值来判断,而它们的值是“真”,因为它们不是空的。
你想要的应该是 elif comp1 != 'rock' and comp1 != 'scissors' and comp1 != 'paper':
,或者因为你已经把这些值放在 rps
这个元组里,你可以用 elif comp1 not in rps:
来判断。
应该是这样的
comp1 not in ['rock', 'scissors', 'paper']
‘剪刀’和‘纸’总是会被认为是真的(或者在用or
的时候,它们会保持原样)
comp1 != 'rock' or 'scissors' or 'paper'
另外,使用comp1 == comp2
,这样简单多了。
更改
elif comp1 != 'rock' or 'scissors' or 'paper':
为
elif comp1 not in rps:
你之前做的事情相当于:
elif (comp1 != 'rock') or 'scissors' or 'paper':
那么为什么条件总是成立呢?
仔细看看 or 'scissors' or 'paper'
这一部分。
1) 在Python中,非空字符串被视为True,而空字符串被视为False。你可以看看这个互动示例:
>>> bool('')
False
>>> bool('a')
True
2) 在Python中,if
语句如果没有比较(比如 if var1:
),实际上是在检查这个表达式是否为True。所以,
if var1:
这和
if var1 == True:
是一样的。
如果把这两个概念结合起来看:
if 'rock':
# Always executed
if '':
# Never executed
回到你最初的if语句:
elif comp1 != 'rock' or 'scissors' or 'paper':
无论是'scissors'还是'paper',都会始终返回True,因此里面的语句总是会被执行。
那么“in”操作符是什么呢?
in
操作符在 elif comp1 not in rps:
中会检查 comp1
的内容是否是元组 rps
(也就是 ('rock', 'paper', 'scissors')
)中的一个项。前面的 not
会否定这个检查,意思是检查 comp1
的内容是否不在元组 rps
中。因此,只有当用户输入的内容存储在 comp1
中是无效的时候,里面的语句才会被执行。