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
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():
i=random.randrange(6)
button.title=str(i+1)
button.bg_color=colors[i]
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 '''
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)]
for i in range(N):
for j in range(N):
b[j][i].action=button_pressed
b[j][i].loc=(i,j)
value=random.randrange(6)
b[j][i].title=str(value+1)
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'
v.add_subview(b[j][i])
v.present()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment