我创建了nim游戏的一个版本,但该版本低于零。我设置计算机的方式始终与我使用相同的金额,但是如果计数为4而我取出3,则该计算机的回合数为1。然后,计算机取出3并显示为-2。因此,我如何告诉程序始终将计数保持在零以上?还有人知道怎么做,这样计算机就不会总是输入与我相同的金额吗?
这是我的代码。
import random
Stones = random.randint(15, 30)
User = 0
YourTurn = True
print("This is a game where players take turns taking stones from a pile of stones. The player who
takes the last stone loses.")
print("The current stone count is:", Stones)
while True:
while YourTurn == True and Stones > 0:
User = int(input("How many stones do you want to remove?"))
if User == 1:
Stones -= 1
print("You removed 1 stone! The current stone count is:", Stones)
YourTurn = not True
elif User == 2:
Stones -= 2
print("You removed 2 stone! The current stone count is:", Stones)
YourTurn = not True
elif User == 3:
Stones -= 3
YourTurn = not True
print("You removed 3 stone! The current stone count is:", Stones)
else:
print("You can only remove a maximum of 3 stones.")
while YourTurn == False and Stones > 0:
AI = random.randint(1, 3)
if AI == 1:
Stones -= 1
print("The A.I removed 1 stone! The current stone count is:", Stones)
YourTurn = not False
elif AI == 2:
Stones -= 2
print("The A.I removed 2 stone! The current stone count is:", Stones)
YourTurn = not False
elif AI == 3:
Stones -= 3
print("The A.I removed 3 stone! The current stone count is:", Stones)
YourTurn = not False
if Stones <= 0:
if YourTurn == True:
print("The A.I took the last stone it lost. You won the game!")
break
elif YourTurn == False:
print("You took the last stone you lost. The A.I won the game!")
break
[您只需要将AI依次获得的结石数量从random.randint(1, 3)
更改为random.randint(1, min(3, Stones))
,以使其获得的结石数量不超过剩余的结石数量。