我用 Python 2.7 写了一个石头剪刀布游戏的基础,如下:
1 #!/bin/py
2 #Python 2.7.6
3 from random import choice
4
5 moves = ["r", "p", "s"] # Possible moves
6 winning_combos = {("r", "s"), ("s", "p"), ("p", "r")} # Winning outcomes
7
8 def human():
9 print
10 print "R: Rock P: Paper S: Scissor"
11 print
12 human_move = raw_input("Enter your choice: ").lower()
13 return human_move
14 ()
15
16 def bot():
17 bot_move = choice(moves)
18 return bot_move
19 ()
20
21 while True:
22 human(), bot()
23 if human() == bot():
24 print "Grr... a tie!"
25 elif (human(), bot()) in winning_combos:
26 print "Woo-hoo! You win this round, human"
27 else:
28 print "Bwahahaha! The almighty bot wins!"
.
我的问题是,如果可以的话,我可以如何比较 human() 和 bot() 函数的结果,就像我在第 25 行中尝试做的那样?当这个程序按原样运行时,系统会提示我在比较完成之前输入两次。
我可以用不同的方式编写这个程序来产生可接受的结果,所以我不打算重写这个程序。我特别询问如何按原样调整此程序(我对 Python 相当陌生),并了解我做错了什么,尽管可能效果不佳。谢谢!
请您参考如下方法:
您的问题是您每次需要访问该值时都在调用 human 和 bot。将结果存储在变量中,如下所示:
while True:
human_move, bot_move = human(), bot()
if human_move == bot_move:
print "Grr... a tie!"
elif (human_move, bot_move) in winning_combos:
print "Woo-hoo! You win this round, human"
else:
print "Bwahahaha! The almighty bot wins!"
