所以我正在用python制作yahtzee游戏。单击按钮时,我将其设置为掷骰子。然后,您可以单击以防止再次滚动该数字。我的目标是将这个range(5)中的值分配给一个变量。最好我希望每次单击骰子按钮时都会更新该变量。
这只是为了我自己一直在努力使python变得更好的游戏。我尝试过想一种将其分配给字典的方法,但是我一直找不到方法。
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()
答案 0 :(得分:1)
这是您想要的吗?
nums = list(range(5)) #nums is now list of [0,1,2,3,4]
答案 1 :(得分:0)
除list(range(5))
之外的另一种方式:
nums = [*range(5)]
print(nums)
# [0, 1, 2, 3, 4]
似乎也快了很多。 (我使用100
进行了更准确的测试。)
In [1]: %timeit nums = list(range(100))
3.24 µs ± 87.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [2]: %timeit nums = [*range(100)]
1.08 µs ± 40.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
答案 2 :(得分:0)
我理解这一点,但是有办法让我获取相同的列表吗? for循环中的数字?
我猜您只想执行一次语句块n
(此处= 1000)次,并且每次使用相同的编号num
。如果是这样,您可以使用:
n = 1000
num = 1 # the number you want to repeat
#Execute for 0.06280231475830078s
for i in [num]*n:
print(i)
或
n = 1000
num = 1 # the number you want to repeat
#Execute for 0.05784440040588379s
for _ in range(n):
print(num)