简体   繁体   中英

Same result every time with random numbers (python)

def gDiceRoll():

    gDiceOptions.destroy()

    global gDiceRoll
    gDiceRoll = Tk()
    gDiceRoll.title("Green Dice Roll")
    gDiceRoll.config(background="#32cd32")

    lbloutcome = Label(gDiceRoll, text="?", width="12", height="8", bg="#32cd32")

    play()

    while True:

        outcomeG = random.randint(1, 100)
        lbloutcome = Label(gDiceRoll, text="?", width="12", height="8", bg="#32cd32")

        if outcomeG <= 25:

            lbloutcome.config(text="G1", font=(25))
            gDiceRoll.update()
            f = open("Logs.txt", "a")
            ts = time.time()
            sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
            f.write(sttime + "G1 \n")
            f.close()
            photo = PhotoImage(file=r"C:\Temp\Dice_Roll\pics\G1.gif")
            lblop = Label(gDiceRoll, image=photo)
            lblop.pack()
            lbloutcome.pack()
            gDiceRoll.mainloop()
            gDiceRoll.after(1)
            os.execl(sys.executable, sys.executable, *sys.argv)
            break

        elif outcomeG <= 22:

            lbloutcome.config(text="G2", font=(25))
            gDiceRoll.update()
            f = open("Logs.txt", "a")
            ts = time.time()
            sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
            f.write(sttime + "G2 \n")
            f.close()
            photo = PhotoImage(file=r"C:\Temp\Dice_Roll\pics\G2.gif")
            lblop = Label(gDiceRoll, image=photo)
            lblop.pack()
            lbloutcome.pack()
            gDiceRoll.mainloop()
            gDiceRoll.after(1)
            os.execl(sys.executable, sys.executable, *sys.argv)
            break        
        #etc

Every time I run the program ir ALWAYS comes out with G1. I have tried to fix it many ways but they just create other problems. The elif G1 <= 25 means it has a 25% chance of doing G1 but it always does G1.

How can I fix this? Any help will be greatly appreciated

let's say outcomeG <= 22

then your code encounters outcomeG <= 25 condition first, and enters first condition, always .

You have to swap your if and elif to test <=22 first

Of course you have to do something if outcomeG > 25 else you're looping for nothing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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