【发布时间】:2019-11-04 15:47:03
【问题描述】:
Python 新手在这里尝试解决我的 nim 代码游戏。 基本上,代码会移除 1、2 或 3 块石头,直到它们都不剩。我试图阻止用户和 AI 陷入负面状态(如果他们只剩下一块石头,那么 AI/用户不应该能够移除两三块石头。)这是我到目前为止的代码:
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
我不知道如何让代码不被否定,我之前的 if 和 elif 语句被代码忽略了。我将不胜感激。
【问题讨论】:
-
您可以考虑在第一个 if-else 结构中添加检查
if User > Stones并将AI = random.randint(1, 3)更改为AI = random.randint(1, min(Stones, 3))之类的东西 -
elif AI == 2:->elif AI == 2 and Stones >= 2?等等。代码风格不好,但这应该可以帮助您去除太多的石头。或者只是为用户和 AI 做检查AI = random.randint(1, 3)->AI = random.randint(1, min(3, Stones))
标签: python loops if-statement while-loop