Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add more examples #8

Merged
merged 3 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions examples/06_full_blown_app_structure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
from typing import Unpack
from functools import partial

import pygame
import pygame.font
from pygame.colordict import THECOLORS as COLORS
import pygame.constants as C

import asyncpygame as apg
from asyncpygame.scene_switcher import SceneSwitcher, FadeTransition
from _uix.touch_indicator import touch_indicator
from _uix.anchor_layout import AnchorLayout
from _uix.ripple_button import RippleButton
from _uix.modal_dialog import ask_yes_no_question


async def main(**kwargs: Unpack[apg.CommonParams]):
pygame.init()
pygame.display.set_caption("<Your App Title>")
kwargs["draw_target"] = screen = pygame.display.set_mode((800, 600))

bgcolor = COLORS["black"]
r = kwargs["executor"].register
r(partial(screen.fill, bgcolor), priority=0)
r(pygame.display.flip, priority=0xFFFFFF00)
userdata = {
'font': pygame.font.SysFont(None, 60),
'bgcolor': bgcolor,
}
async with apg.open_nursery() as nursery:
nursery.start(confirm_before_quitting(priority=0xFFFFFD00, **kwargs))
nursery.start(touch_indicator(color="grey", priority=0xFFFFFE00, **kwargs))
nursery.start(SceneSwitcher().run(title_scene, priority=0xFFFFFC00, userdata=userdata, **kwargs))


async def confirm_before_quitting(*, priority, **kwargs: Unpack[apg.CommonParams]):
quit = partial(kwargs["sdlevent"].wait, C.QUIT, priority=priority, consume=True)
escape_key = partial(kwargs["sdlevent"].wait, C.KEYDOWN, priority=priority, filter=lambda e: e.key == C.K_ESCAPE, consume=True)
while True:
await apg.wait_any(quit(), escape_key())
if await ask_yes_no_question("Quit the app?", priority=priority, **kwargs):
apg.quit()


async def title_scene(*, scene_switcher, userdata, **kwargs: Unpack[apg.CommonParams]):
draw_target = kwargs["draw_target"]
target_rect = draw_target.get_rect()
font = userdata['font']
async with apg.open_nursery() as nursery:
AnchorLayout(
nursery,
font.render("<Your App Title>", True, "white", userdata["bgcolor"]).convert(draw_target),
target_rect.scale_by(1.0, 0.5).move_to(y=target_rect.y),
priority=0x100, **kwargs)
start_button = RippleButton(
nursery,
button_image := font.render("Start", True, "white").convert_alpha(),
button_image.get_rect(center=target_rect.scale_by(1.0, 0.5).move_to(bottom=target_rect.bottom).center).inflate(80, 80),
priority=0x100, **kwargs)
await start_button.to_be_clicked()
scene_switcher.switch_to(menu_scene, FadeTransition())
await apg.sleep_forever()


async def menu_scene(*, scene_switcher, userdata, **kwargs: Unpack[apg.CommonParams]):
draw_target = kwargs["draw_target"]
target_rect = draw_target.get_rect()
font = userdata['font']
async with apg.open_nursery() as nursery:
play_button = RippleButton(
nursery,
button_image := font.render("Play Game", True, "white").convert_alpha(),
button_image.get_rect(center=target_rect.scale_by(1.0, 0.5).move_to(y=target_rect.y).center).inflate(80, 80),
priority=0x100, **kwargs)
back_button = RippleButton(
nursery,
button_image := font.render("Back to Title", True, "white").convert_alpha(),
button_image.get_rect(center=target_rect.scale_by(1.0, 0.5).move_to(bottom=target_rect.bottom).center).inflate(80, 80),
priority=0x100, **kwargs)
tasks = await apg.wait_any(
play_button.to_be_clicked(),
back_button.to_be_clicked(),
)
next_scene = title_scene if tasks[1].finished else game_scene
scene_switcher.switch_to(next_scene, FadeTransition())
await apg.sleep_forever()


async def game_scene(*, scene_switcher, userdata, **kwargs: Unpack[apg.CommonParams]):
draw_target = kwargs["draw_target"]
target_rect = draw_target.get_rect()
font = userdata['font']
clock = kwargs["clock"]

image = font.render("Running...", True, "white", userdata["bgcolor"]).convert(draw_target)
dest = image.get_rect(center=target_rect.center)
with kwargs["executor"].register(partial(draw_target.blit, image, dest), priority=0x100):
async with clock.move_on_after(5000):
await clock.anim_attrs(dest, y=dest.y - 80, duration=400)
while True:
await clock.anim_attrs(dest, y=dest.y + 160, duration=800)
await clock.anim_attrs(dest, y=dest.y - 160, duration=800)
scene_switcher.switch_to(title_scene, FadeTransition())
await apg.sleep_forever()


if __name__ == "__main__":
apg.run(main)
47 changes: 42 additions & 5 deletions examples/_uix/modal_dialog.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__all__ = ('ask_yes_no_question', )
__all__ = ('show_messagebox', 'ask_yes_no_question', )

from typing import Unpack
from contextlib import asynccontextmanager
Expand Down Expand Up @@ -35,6 +35,45 @@ async def translate_rects_vertically(clock: Clock, rects, movement, duration):
rect.y = org_y + v


async def show_messagebox(
message, *, dialog_size: Rect=None, font=None, text_ok='OK',
priority, **kwargs: Unpack[CommonParams]) -> bool:
'''
.. code-block::

await show_messagebox("Hello World", priority=0xFFFFFA00, **kwargs)
'''
bgcolor = "grey90"
clock = kwargs["clock"]
draw_target = kwargs["draw_target"]
if font is None:
font = SysFont(None, 40)

with block_input_events(kwargs["sdlevent"], priority):
async with darken(priority=priority, **kwargs), asyncgui.open_nursery() as nursery:
target_rect = draw_target.get_rect()
if dialog_size is None:
dialog_size = target_rect.inflate(-100, 0)
dialog_size.height = dialog_size.width // 2
dialog_dest = dialog_size.move_to(bottom=target_rect.top)
with kwargs["executor"].register(partial(draw_target.fill, bgcolor, dialog_dest), priority=priority + 1):
label = AnchorLayout(
nursery,
font.render(message, True, "black", bgcolor).convert(draw_target),
dialog_dest.scale_by(1.0, 0.7).move_to(top=dialog_dest.top).inflate(-10, -10),
priority=priority + 2, **kwargs)
ok_button = RippleButton(
nursery,
font.render(text_ok, True, "white"),
dialog_dest.scale_by(0.5, 0.3).move_to(midbottom=dialog_dest.midbottom).inflate(-20, -20),
priority=priority + 2, **kwargs)
rects = (dialog_dest, label.dest, ok_button.dest, )
y_movement = target_rect.centery - dialog_dest.centery
await translate_rects_vertically(clock, rects, y_movement, duration=200)
await ok_button.to_be_clicked()
await translate_rects_vertically(clock, rects, -y_movement, duration=200)


async def ask_yes_no_question(
question, *, dialog_size: Rect=None, font=None, text_yes='Yes', text_no='No',
priority, **kwargs: Unpack[CommonParams]) -> bool:
Expand All @@ -44,21 +83,19 @@ async def ask_yes_no_question(
result = await ask_yes_no_question("Do you like PyGame?", priority=0xFFFFFA00, **kwargs)
'''
bgcolor = "grey90"
executor = kwargs["executor"]
sdlevent = kwargs["sdlevent"]
clock = kwargs["clock"]
draw_target = kwargs["draw_target"]
if font is None:
font = SysFont(None, 40)

with block_input_events(sdlevent, priority):
with block_input_events(kwargs["sdlevent"], priority):
async with darken(priority=priority, **kwargs), asyncgui.open_nursery() as nursery:
target_rect = draw_target.get_rect()
if dialog_size is None:
dialog_size = target_rect.inflate(-100, 0)
dialog_size.height = dialog_size.width // 2
dialog_dest = dialog_size.move_to(bottom=target_rect.top)
with executor.register(partial(draw_target.fill, bgcolor, dialog_dest), priority=priority + 1):
with kwargs["executor"].register(partial(draw_target.fill, bgcolor, dialog_dest), priority=priority + 1):
label = AnchorLayout(
nursery,
font.render(question, True, "black", bgcolor).convert(draw_target),
Expand Down
4 changes: 2 additions & 2 deletions examples/asking_question.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from _uix.touch_indicator import touch_indicator
from _uix.ripple_button import RippleButton
from _uix.modal_dialog import ask_yes_no_question
from _uix.modal_dialog import ask_yes_no_question, show_messagebox


async def main(**kwargs: Unpack[apg.CommonParams]):
Expand All @@ -33,7 +33,7 @@ async def main(**kwargs: Unpack[apg.CommonParams]):
while True:
await button.to_be_clicked()
answer = await ask_yes_no_question("Do you like PyGame?", priority=0xFFFFFA00, **kwargs)
print("YES" if answer else "NO")
await show_messagebox(f"You answered '{'Yes' if answer else 'No'}'.", priority=0xFFFFFA00, **kwargs)


if __name__ == "__main__":
Expand Down
1 change: 0 additions & 1 deletion src/asyncpygame/_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,3 @@ def run(main_func, *, fps=30, auto_quit=True):
raise ap.ExceptionGroup(group.message, unignorable_excs)
finally:
main_task.cancel()
pygame.quit()
Loading