Last active
January 2, 2020 08:33
-
-
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]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
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.
... and I've hopefully improved code based on feedback
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.
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)
.
👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
circles = letters = []
- this assigns the same list to the variablescircles
andletters
- 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.