我已经为拾音棒游戏编写了代码,可以在两种模式下播放
在单人游戏模式下,我的程序似乎有问题。计算机在逻辑上不可能的地方输出负数,我想防止这种情况的发生。 以下是代码:
import random
sticks = 27
choice = input("Do you wanna play multiplayer or against the computer? Type M for multiplayer and S for against the computer: ")
if choice == "M":
while sticks > 0:
i = int(input("Between 1 and 3, how many sticks do you want to pick : "))
while i < 1 or i > 3:
print("It has to be between 1 and 3! You NOOB!")
i = int(input("Between 1 and 3, how many sticks do you want to pick : "))
sticks = sticks - i
print(sticks," stick(s) left...")
print("You lost! hahaha...")
elif choice == "S":
while sticks > 0:
i = int(input("Between 1 and 3, how many sticks do you want to pick : "))
while i < 1 or i > 3:
print("It has to be between 1 and 3! You NOOB!")
i = int(input("Between 1 and 3, how many sticks do you want to pick : "))
sticks = sticks - i
print(sticks," stick(s) left...")
if sticks == 0:
print("You lost! hahaha...")
break
else:
num = random.randint(1,3)
print("Computer's Turn...")
print("The computer picked ",num, " stick(s)...")
sticks = sticks - num
if sticks < 1:
print("You won... Damn you are good!")
print(sticks," stick(s) left...")
这是输出:
Do you wanna play multiplayer or against the computer? Type M for multiplayer and S for against the computer: S
Between 1 and 3, how many sticks do you want to pick : 3
24 stick(s) left...
Computer's Turn...
The computer picked 2 stick(s)...
22 stick(s) left...
Between 1 and 3, how many sticks do you want to pick : 3
19 stick(s) left...
Computer's Turn...
The computer picked 1 stick(s)...
18 stick(s) left...
Between 1 and 3, how many sticks do you want to pick : 3
15 stick(s) left...
Computer's Turn...
The computer picked 1 stick(s)...
14 stick(s) left...
Between 1 and 3, how many sticks do you want to pick : 3
11 stick(s) left...
Computer's Turn...
The computer picked 2 stick(s)...
9 stick(s) left...
Between 1 and 3, how many sticks do you want to pick : 3
6 stick(s) left...
Computer's Turn...
The computer picked 2 stick(s)...
4 stick(s) left...
Between 1 and 3, how many sticks do you want to pick : 2
2 stick(s) left...
Computer's Turn...
The computer picked 3 stick(s)...
You won... Damn you are good!
-1 stick(s) left...
如您所见,游戏会显示一个负数,它应该在结束时说您赢了,否则计算机将无法输入负数。有人可以告诉我我在做什么错吗?
答案 0 :(得分:0)
当“ sticks <3”时,您必须在某处实现“ if”语句。考虑一下,如果sticks = 2,则您的第一个while循环仍将运行,因为sticks>0。那么,如果我选择的下一个为3,会发生什么? 2-3 = -1。因此,一旦sticks = 2,您就需要执行某种声明,说我只能等于2或1,并且对于sticks = 1也要执行相同的操作