在用户在python中更改变量后,如何继续更新它?
我正在制作一个游戏,用户输入“x”数量的筹码放入第一堆和第二堆。(例如,用户输入:12;第一堆:12,第二堆:12)然后从第一堆或第二堆中取出“z”数量的芯片,然后计算机从另一堆中取出用户从中取出的相同数量的芯片。所以基本上电脑总是赢。但我在更新桩时遇到了一些问题,直到两个桩都达到0在用户在python中更改变量后,如何继续更新它?,python,Python,我正在制作一个游戏,用户输入“x”数量的筹码放入第一堆和第二堆。(例如,用户输入:12;第一堆:12,第二堆:12)然后从第一堆或第二堆中取出“z”数量的芯片,然后计算机从另一堆中取出用户从中取出的相同数量的芯片。所以基本上电脑总是赢。但我在更新桩时遇到了一些问题,直到两个桩都达到0 def initGame(): pile1= chips pile2= chips finished = False while chips<=0: if ch
def initGame():
pile1= chips
pile2= chips
finished = False
while chips<=0:
if chips <= 0:
print("Please input a number greater than 0")
finished= True
else:
finished= True
return pile1, pile2
def displayPiles(pile1, pile2):
print("It is your turn human.")
print("Here are the piles: ")
print("pile 1: "+ str(pile1))
print("pile 2: "+ str(pile2))
return pile1, pile2
def getHumanMove(x,y):
finished = False
while not finished:
x=int(input("Which pile would you like to take from?(1 or 2)"))
y=int(input("How many would you like from pile "+ str(x)+ "? "))
if pile1 and pile2<y:
print("pile " +str(x)+ " does not have that many chips. Try again.")
elif y==0:
print("You must take at least one chip. Try again.")
else:
print("That was a legal move. Thank You.")
finished = True
return x,y
def getPiles(pile1, pile2, move):
print("Here are the piles: ")
x,y = move
if x == 1:
pile1= pile1- y
print("pile 1: ", str(pile1))
print("pile 2: ", str(pile2))
elif x == 2:
pile2= pile1- y
print("pile 1: ", str(pile1))
print("pile 2: ", str(pile2))
return pile1, pile2
def getCompMove(x,y, pile1, pile2):
print("Now it's my turn.")
pile1, pile2= pile1, pile2
x= x
y= y
if x==1:
print("I, the champion chips computer will take "+str(y)+ " chips from pile 2")
pile2= pile2 - y
pile1= pile1
elif x==2:
print("I, the champion chips computer will take "+str(y)+ " chips from pile 1")
pile1= pile1 - y
pile2= pile2
if pile1==0 and pile2==0:
print("The game is over because I took the last chip.")
print("Thanks for playing. Let's wager next time.")
return x,y, pile1, pile2
def compPiles(pile1, pile2):
print("Here are the piles: ")
pile1, pile2= pile1, pile2
print("pile 1: ", str(pile1))
print("pile 2: ", str(pile2))
return pile1, pile2
当我运行这个程序时,它会正确地删除被删除的芯片数量,但当计算机移动时,它不会更新它
Here are the piles:
pile 1: 9
pile 2: 12
Now it's my turn.
I, the champion chips computer will take 3 chips from pile 2
Here are the piles:
pile 1: 12
pile 2: 9
更新的丢失并不奇怪:您将getCompMove的结果放入变量
pile
中,以后再也不用它了。我想如果你加上
pile1, pile2 = pile
或
它会表现得更好。顺便说一句,在学习Python时,应该尝试将所有单独的函数转换为包含两个堆的类中的方法:这样会更清晰,传入和传出的变量也会更少。除非在注释中声明,否则系统地隐藏具有相同名称的局部变量对读者来说是一种痛苦。最简单的方法是使用列表或字典。为什么要在函数中使用
pile1=pile1
?@lafexlos只是一个错误。刚脱下来。
pile1, pile2 = pile
pile1, pile2 = getCompMove(...)