Skip to content

Commit cad2546

Browse files
add an example, bouncing_balls.py
1 parent 88392e1 commit cad2546

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

examples/bouncing_balls.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from typing import Unpack
2+
from functools import partial
3+
4+
import pygame
5+
from pygame.colordict import THECOLORS
6+
from pygame import Rect, Vector2, Color
7+
8+
import asyncpygame as apg
9+
10+
11+
async def bouncing_ball(*, dest: Rect, space: Rect, color, velocity: Vector2, **kwargs: Unpack[apg.CommonParams]):
12+
draw_func = partial(pygame.draw.ellipse, kwargs["draw_target"], color, dest)
13+
with kwargs["executor"].register(draw_func, kwargs["priority"]):
14+
async for dt in kwargs["clock"].anim_with_dt():
15+
dest.move_ip(velocity * (dt / 1000.0))
16+
if not dest.colliderect(space):
17+
return
18+
if dest.left < space.left or dest.right > space.right:
19+
velocity.x = -velocity.x
20+
if dest.top < space.top or dest.bottom > space.bottom:
21+
velocity.y = -velocity.y
22+
23+
24+
async def main(**kwargs: Unpack[apg.CommonParams]):
25+
from random import randint
26+
pygame.init()
27+
pygame.display.set_caption("Bouncing Balls")
28+
29+
kwargs["draw_target"] = screen = pygame.display.set_mode((1280, 720))
30+
31+
r = kwargs["executor"].register
32+
r(partial(screen.fill, THECOLORS["black"]), priority=0)
33+
r(pygame.display.flip, priority=0xFFFFFF00)
34+
35+
async with apg.open_nursery() as nursery:
36+
clock = kwargs["clock"]
37+
priority = 0x100
38+
screen_rect = screen.get_rect()
39+
while True:
40+
await clock.sleep(randint(1000, 2000))
41+
ball_size = randint(20, 150)
42+
nursery.start(bouncing_ball(
43+
dest=Rect(0, 0, ball_size, ball_size).move_to(center=screen_rect.center),
44+
space=screen_rect,
45+
color=Color(randint(0, 255), randint(0, 255), randint(0, 255)),
46+
velocity=Vector2(randint(-150, 150), randint(-150, 150)),
47+
priority=priority,
48+
**kwargs
49+
))
50+
priority += 1
51+
52+
53+
if __name__ == "__main__":
54+
apg.run(main)

0 commit comments

Comments
 (0)