首页 > 解决方案 > 如何将 range(5) 中的值分配给变量?

问题描述

所以我正在用python制作一个yahtzee游戏。当您单击按钮时,我已设置为掷骰子。然后,您可以通过单击它来阻止该数字再次滚动。我的目标是将此范围(5)中的值分配给一个变量。最好我希望每次单击骰子按钮时它都会更新变量。

这只是为了我一直在为自己开发的一款游戏,以便更好地使用 python。我试图想办法将它分配给一个 dict 但我一直无法找出如何。

from tkinter import *
from random import randint

root = Tk()
root.title("Sam's Yahtzee")

def roll(dice, times):
    if times > 0:
        dice['text'] = randint(1, 6)
        root.after(10, roll, dice, times-1)

def roll_dices():
    for i in range(5):
        if dices[i][1].get() == 0:
            # dice is not held, so roll it
            roll(dices[i][0], 10)

dices = []
for i in range(5):
    ivar = IntVar()
    dice = Checkbutton(root, text=randint(1, 6), variable=ivar, bg='silver', bd=1, font=('Arial', 24), indicatoron=False, height=3, width=5)
    dice.grid(row=0, column=i)
    dices.append([dice, ivar])

Button(text='Dice', command=roll_dices, height=2, font=(None, 16, 'bold')).grid(row=1, column=0, columnspan=5, sticky='ew')

yahtzee = 0
threeKind = 0
fourKind = 0
fullHouse = 0
smallStraight = 0
largeStraight = 0
chance = 0

possibleHands = {"yahtzee": yahtzee,
                 "threeKind": threeKind,
                 "fourKind": fourKind,
                 "fullHouse": fullHouse,
                 "smallStraight": smallStraight,
                 "largeStraight": largeStraight,
                 "chance": chance}

root.mainloop()

标签: python

解决方案


这是你想要的吗?

nums = list(range(5)) #nums is now list of [0,1,2,3,4]

推荐阅读