繁体   English   中英

在while循环中保存变量(骰子游戏)

[英]Save variable in while loop (dice game)

import random

player1=1

def dice_roll_1():
    while player1 <49:

            r=input("Press r to roll ")

            roll_1 = random.randint(1,6)
            roll_2 = random.randint(1,6)
            print(roll_1)
            print(roll_2)
            total=(roll_1 + roll_2)
            print("Total dice roll",total)
            print(total+player1)

dice_roll_1()

我正在为学校做这个工作,实在太难受了。 循环时,将player1变量重置为1。
我需要它来保持整个循环的总数。
例如,如果他们掷出12,则将增加玩家1,而玩家1将等于13。
然后在下一个回合中,如果他们掷出6,则将13加到19。

更新值。 然后打印

print("Total dice roll",total)
player1 += total
print(player1)

问题是您永远不会更改player1的值。

它只分配一次...

这就是该值始终为“ 1”的原因

检查下面的代码,并使用以下行:player1 + = total

我还添加了一个检查,以查看他们输入的内容是否不是“ r”

import random

player1=1

def dice_roll_1():
    while player1 <49:

        r=input("Press r to roll ")
        # if something else was entered, then continue on to the next roll
        if r != 'r':
            continue

        roll_1 = random.randint(1,6)
        roll_2 = random.randint(1,6)
        print(roll_1)
        print(roll_2)
        total=(roll_1 + roll_2)
        print("Total dice roll",total)
        # need to update the player's total
        player1 += total
        print(player1)

dice_roll_1()

print("Final total for player 1: " + player1)

暂无
暂无

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

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