简体   繁体   English

更新循环内的变量(python)

[英]UPDATING a variable inside a loop (python)

I am trying to create dice for my board game using loops.我正在尝试使用循环为我的棋盘游戏创建骰子。 However, the variable pos won't update itself so that the next time the for loop is triggered it starts from its previous value and not 0. At the moment each time the for loop is being triggered the pos starts by default from 0 and doesn't get updated after each run.但是,变量 pos 不会自我更新,因此下次触发 for 循环时,它会从其先前的值而不是 0 开始。在每次触发 for 循环时,pos 默认从 0 开始并且不会每次运行后都不会更新。 Meaning the player would always go back to square 0.这意味着玩家将始终 go 回到方块 0。

this is what i have coded so far:这是我到目前为止编码的内容:

    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 itself does not change when you change it in the loop, because range(dieValue) is an iterable that the for loop is looping over.当您在循环中更改pos时,它本身不会更改,因为range(dieValue)是 for 循环正在循环的可迭代对象。 You can thinking of the range precisely as (0, 1, 2, ..., dieValue - 1) .您可以将范围精确地视为(0, 1, 2, ..., dieValue - 1)

To maintain the position of the player, you have to record the position outside of of the while loop.要维护播放器的 position,您必须在 while 循环之外记录 position。 Furthermore, you should change the for loop to be此外,您应该将 for 循环更改为

for _ in range(dieValue):
    pos += 1
    P1_pos = player1.goto(p1_list[pos])

If I get you right, then the position of a player should be passed as a parameter of this function/method.如果我没听错,那么播放器的 position 应该作为此函数/方法的参数传递。 Then you would sum dice1 and this position to get a new position.然后你将 dice1 和这个 position 相加得到一个新的 position。 Or you would access the pos of a player through player1.pos().或者你可以通过 player1.pos() 访问玩家的位置。

Another weird thing is that you initiate pos to 0 and then you also use pos in the for-loop.另一个奇怪的事情是您将pos初始化为 0,然后您还在 for 循环中使用pos In your for-loop pos is 0 in the first iteration, 1 in the second, and so on till you get to the value of pos == dice1-1 (if there is range(4), values of pos would be 0,1,2,3).在您的 for 循环中,第一次迭代中的pos为 0,第二次迭代中为 1,依此类推,直到获得pos == dice1-1 的值(如果有 range(4),则pos的值为 0, 1,2,3)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM