-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
95 lines (76 loc) · 2.81 KB
/
main.py
File metadata and controls
95 lines (76 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import asyncio
import pygame
import sys
import os
# Initialize pygame
pygame.init()
# Set up display
# Get the screen surface from the pygbag environment
screen = pygame.display.get_surface()
WIDTH, HEIGHT = screen.get_size()
pygame.display.set_caption("PyGame Docker Demo")
clock = pygame.time.Clock()
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# Player
player = pygame.Rect(WIDTH//2, HEIGHT//2, 32, 32)
player_color = WHITE
async def main():
global player_color
running = True
try:
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
# Change color on key press for visual feedback
if event.key == pygame.K_SPACE:
player_color = RED if player_color == WHITE else WHITE
elif event.key == pygame.K_ESCAPE:
running = False
# Handle continuous key presses
keys = pygame.key.get_pressed()
speed = 5
if keys[pygame.K_LEFT] and player.x > 0:
player.x -= speed
if keys[pygame.K_RIGHT] and player.x < WIDTH - player.width:
player.x += speed
if keys[pygame.K_UP] and player.y > 0:
player.y -= speed
if keys[pygame.K_DOWN] and player.y < HEIGHT - player.height:
player.y += speed
# Clear screen
screen.fill(BLACK)
# Draw player
pygame.draw.rect(screen, player_color, player)
# Draw some UI elements for feedback
try:
font = pygame.font.Font(None, 36)
text = font.render("Use arrow keys to move", True, GREEN)
screen.blit(text, (10, 10))
text2 = font.render("Press SPACE to change color", True, BLUE)
screen.blit(text2, (10, 50))
text3 = font.render("Press ESC to exit", True, WHITE)
screen.blit(text3, (10, 90))
except Exception as e:
# Font rendering might fail in web environment
print(f"Font rendering error: {e}")
# Update display
pygame.display.flip()
# This is crucial for pygbag - yield control back to browser
await asyncio.sleep(0)
# Cap the frame rate
clock.tick(60)
except Exception as e:
print(f"Game error: {e}")
finally:
pygame.quit()
sys.exit()
if __name__ == "__main__":
asyncio.run(main())