我对编码还比较陌生(因为我13岁),现在正在尝试用Python 3构建剪刀石头布游戏。这是我目前的代码`
answer = input("To play: type in Rock (r), Paper (p) or Scissors (s)").lower()
if answer == "rock" or answer == "r":
answer = 1
print ("You chose Rock!")
elif answer == "paper" or answer == "p":
answer = 2
print ("You chose Paper!")
elif answer == "scissors" or answer == "s":
answer = 3
print ("You chose Scissors!")
else:
print ("You didn't pick an option... Make sure you spell it right!")
rps()
computer = lambda: random.randint(1, 3)
if computer == 1:
string_computer = "Rock"
elif computer == 2:
string_computer = "Paper"
elif computer == 3:
string_computer = "Scissors"
else:
print ("There must had been a glitch")
rps()
if answer == computer:
print(("The computer chose"), string_computer,("so it\'s a draw!"))
elif answer == 1 and computer == 2:
print(("The computer chose"), string_computer,("so unfortuantely you lost."))
rps()
elif answer == 1 and computer == 3:
print(("The computer chose"), string_computer,("so you won! Congratulations!"))
rps()
elif answer == 2 and computer == 1:
print(("The computer chose"), string_computer,("so you won! Congratulations!"))
rps()
elif answer == 2 and computer == 3:
print(("The computer chose"), string_computer,("so unfortuantely you lost."))
rps()
elif answer == 3 and computer == 1:
print(("The computer chose"), string_computer,("so unfortuantely you lost."))
rps()
else:
print(("The computer chose"), string_computer,("so you won! Congratulations!"))
rps()
`
当我尝试运行代码时,所有语法都是正确的,但是出现了“一定有一个小故障”,我添加了该小故障,以查看它是否没有在1到3之间选择一个数字。因此它会选择一个介于1到3之间的数字?
答案 0 :(得分:1)
import random
computer = random.randint(1,3)
这里不需要lambda函数。
包括lambda函数集computer
,该函数将生成1到3之间的随机数。
>>> computer = lambda: random.randint(1, 3)
>>> computer
<function <lambda> at 0x000001F4DD2738C8>
如果您再致电computer()
,则会得到1到3之间的一个随机数。
>>> computer()
2
>>> computer()
2
>>> computer()
1
为了您的功能,摆脱lambda:
是最好的解决方法。如果您想在if computer...
语句中添加括号,则可能会以glitch
语句结尾,因为您将为每个computer()
调用生成一个新的随机整数。