Skip to content

Instantly share code, notes, and snippets.

@jsbain
Created Apr 10, 2018
Embed
What would you like to do?
Untitled.py
import ui, random
from functools import partial
colors=['salmon','orange','yellow','turquoise','gray','white']
N=4 #size if grid
dicestr='AACIOT,ABILTY,ABJMOQ,ACDEMP,ACELRS,ADENVZ,AHMORS,BIFORX,DENOSW,DKNOTU,EEFHIY,EGKLUY,EGINTV,EHINPS,ELPSTU,GILRUW'.split(',')
dice=[[face if not face=='Q' else 'Qu' for face in die ] for die in dicestr]
def animate_button(button,num_rolls):
''' returns a callable, which when called will ui.animate to change title and color, with a recursive completion for a total of num_rolls'''
def ani():
value=random.randrange(6)
button.title=dice[button.dienum][value]
button.bg_color=colors[value]
button.transform=ui.Transform.concat(ui.Transform.translation(random.randrange(10)-5,random.randrange(10)-5),ui.Transform.rotation(random.randrange(128)/64.*3.14))
def finish():
button.transform=ui.Transform.rotation(0)
#button.bg_color='white'
# we need to call ui.animate(ani,duration,completion=ani)
dur=0.2+random.randrange(5)/50. # just some variation in dice roll duration
if num_rolls==0:
return partial(ui.animate,finish,duration=dur)
else:
#dur=1 #all dice roll together
return partial(ui.animate,ani,duration=dur,completion=animate_button(button,num_rolls-1))
def button_pressed(sender):
'''roll all dice. this could be changed to only re-roll sender, or do something else based on sender.loc, etc '''
# first, shuffle dice, then roll
shuffledice()
for button in [b[j][i] for i in range(N) for j in range(N)]:
animate_button(button, 10)() #extra () actually calls the animation
#set up grid
v=ui.View(frame=(0,0,N*50,N*50))
b=[[ui.Button(frame=(i*50,j*50,45,45)) for i in range(N)] for j in range(N)]
def shuffledice():
diceorder=list(range(N*N))
random.shuffle(diceorder)
for i in range(N):
for j in range(N):
b[j][i].action=button_pressed
b[j][i].loc=(i,j)
b[j][i].dienum=diceorder[i*N+j]
value=random.randrange(6)
b[j][i].title=dice[b[j][i].dienum][value]
b[j][i].bg_color=colors[value]
b[j][i].corner_radius=5
b[j][i].line_width=1
b[j][i].tint_color='blue'
if not b[j][i].superview:
v.add_subview(b[j][i])
shuffledice()
v.present()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment