[英]UPDATING a variable inside a loop (python)
我正在嘗試使用循環為我的棋盤游戲創建骰子。 但是,變量 pos 不會自我更新,因此下次觸發 for 循環時,它會從其先前的值而不是 0 開始。在每次觸發 for 循環時,pos 默認從 0 開始並且不會每次運行后都不會更新。 這意味着玩家將始終 go 回到方塊 0。
這是我到目前為止編碼的內容:
w = True
while w == True:
dice1 = random.randint(1, 6)
player1_dice = input("\nBULL (P1): Please press 'ENTER' to roll the dice ")
if player1_dice == "":
print("BULL (P1) rolled a", dice1)
elif player1_dice != "":
print("BULL (P1): Please make sure to press 'ENTER' ")
dieValue = dice1
pos = 0
for pos in range(dieValue) :
posi = pos + 1
P1_pos = player1.goto(p1_list[posi])
pos = posi
當您在循環中更改pos
時,它本身不會更改,因為range(dieValue)
是 for 循環正在循環的可迭代對象。 您可以將范圍精確地視為(0, 1, 2, ..., dieValue - 1)
。
要維護播放器的 position,您必須在 while 循環之外記錄 position。 此外,您應該將 for 循環更改為
for _ in range(dieValue):
pos += 1
P1_pos = player1.goto(p1_list[pos])
如果我沒聽錯,那么播放器的 position 應該作為此函數/方法的參數傳遞。 然后你將 dice1 和這個 position 相加得到一個新的 position。 或者你可以通過 player1.pos() 訪問玩家的位置。
另一個奇怪的事情是您將pos
初始化為 0,然后您還在 for 循環中使用pos
。 在您的 for 循環中,第一次迭代中的pos
為 0,第二次迭代中為 1,依此類推,直到獲得pos
== dice1-1 的值(如果有 range(4),則pos
的值為 0, 1,2,3)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.