是否可以使用一个变量,然后再重新定义它?

2024-03-28 18:49:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为学校做一个项目,这是一个骰子游戏。我的这段代码就像第22条军规。你知道吗

我需要定义一个变量,否则它会标记,所以我会这样做,但每次运行按钮时,它都会将值更改为零,而不是增加值。你知道吗

if Rollnop1 == 0 :
    Userscore1 = Randomnumber
    print ("User 1 ",Userscore1 )

    Rollnop1 = Rollnop1+1 #But this changes it so it will go to the next players roll, every 
    #time the button is pressed it changes the variable back to 0
def gamerun():
    global Player
    global usernamestr
    global passwordstr
    global usernamestr2
    global passwordstr2
    Rollnop1 = 0

    def roll2():
        Rollnop2 = 0 
        Randomnumber = random.randint(2,12)
        print ("Console: Random Number 2 = ",Randomnumber)

        if Rollnop2 == 0 :
            Userscore2 = Randomnumber
            print ("User 2 ",Userscore2 )

    def roll1():
        Rollnop1 = 0 #Need to define this here otherwise It wont work
        Randomnumber = random.randint(2,12)
        print ("Console: Random Number = ",Randomnumber)

        if Rollnop1 == 0 :
            Userscore1 = Randomnumber
            print ("User 1 ",Userscore1 )
            Rollnop1 = Rollnop1+1 #But this changes it so it will go to the next players roll, every 
                                  #time the button is pressed it changes the variable back to 0

        else:
            roll2()

    actdicegame = Tk()
    gamerunl0 = Label(actdicegame, text = usernamestr, fg = "black")
    gamerunl0.pack()
    gamerunl1 = Label(actdicegame, text = "Roll The Dice", fg = "black")
    gamerunl1.pack()
    gamerunb1 = Button(actdicegame, text="ROLL",fg="Black", command=roll1)#Register Butto
    gamerunb1.pack()

    actdicegame.geometry("350x500")
    print ("Console: GUI RUNNING 1")
    actdicegame.mainloop()

代码段https://pastebin.com/FSWwBGpA


Tags: thetoifdefitthisglobalconsole
2条回答

这可以回答您的问题:外部函数中的嵌套函数change变量不起作用。基本上,您需要在gamerun中分配Rollnop1=0和Rollnop2=0,并在roll1&roll2中声明它们为非本地的,然后再尝试更改它们的值。你知道吗

–DarrylG非常感谢你和所有帮助过你的人。你知道吗

这里有更多 nested function change variable in an outside function not working

使用一个选项,你提供球员作为掷骰的一部分,这样你就可以说哪个球员在任何给定的时间在玩。下面的函数为提供的播放器播放,并返回下一个播放者

def roll(Rollnop=0):
    UserScore = random.randint(2,12)
    print ("Console: Random Number 2 = ", UserScore)

    if Rollnop == 0 :
        print ("User 1 ", UserScore)
        return 1
    else:
        print ("User 2 ", UserScore)
        return 0

相关问题 更多 >