Skip to content

Instantly share code, notes, and snippets.

@darcyclark
Last active January 2, 2020 08:33
Show Gist options
  • Save darcyclark/32b28e3338ddfaa2895f54cf9363940a to your computer and use it in GitHub Desktop.
Save darcyclark/32b28e3338ddfaa2895f54cf9363940a to your computer and use it in GitHub Desktop.
a little Python ditty to render animated New Year's wishes - using wasabi2d game framework [https://github.com/lordmauve/wasabi2d]
import math
from wasabi2d import Scene, run, event
from random import uniform as fraction
from random import randint as integer
from random import choice
scene = Scene()
scene.background = 'black'
screen = scene.layers[0]
screen.set_effect('bloom', radius=50, intensity=0.9)
items = []
words = [ '2020', 'Happy', 'New Year' ]
W = scene.width
H = scene.height
@event
def on_mouse_move(pos, rel):
dx, dy = rel
r = math.sqrt( (dx**2)+(dy**2) )
pos=(integer(0, W), integer(0, H))
c = screen.add_circle( radius=r, pos=pos, color=random_color() )
items.append(c)
l = screen.add_label(choice(words), align='center', fontsize=integer(0, 144), color=random_color(), pos=(integer(0, W), integer(0, H)) )
items.append(l)
@event
def update(dt):
all_items = items[:]
items[:] = [ i for i in items if i.scale > 0.1 ]
for i in all_items:
if i not in items:
i.delete()
for item in items:
item.scale = item.scale * 0.9 # shrink
item.y = item.y * 1.04 # fall
item.x = item.x + integer(-3, 3) # jitter
def random_color():
return ( fraction(0,1), fraction(0,1), fraction(0,1), fraction(0,1) )
run()
@lordmauve
Copy link

circles = letters = [] - this assigns the same list to the variables circles and letters - so you're actually only using one list. You're iterating over it twice.

Deleting from the items you're iterating over causes Python to skip visiting the next element (because a for loop almost literally calls items[n] with increasing n until it gets an IndexError). This operation is also O(n ** 2) because deleting a single item at an arbitrary index is O(n). To delete many items from a list, you are best to build a new list.

@darcyclark
Copy link
Author

darcyclark commented Jan 2, 2020

Thanks for guidance on the deletion from list - it felt a little wrong to be deleting from the list while iterating through it - now I know the side-effects I will avoid it in future.

@darcyclark
Copy link
Author

... and I've hopefully improved code based on feedback

@darcyclark
Copy link
Author

I think I've still got an O(N ** 2) condition in lines 35-37 ... unsure how to approach removing that condition. That said, because I'm filtering out items in line 34, N should never get large enough to be a problem.

@lordmauve
Copy link

Yep. Looks correct though - that's the main thing.

Another tip: math.sqrt( (dx**2)+(dy**2) ) can be replaced with math.hypot(dx, dy).

@darcyclark
Copy link
Author

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment