Skip to content

pygbag issue #1

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

Open
ManPython opened this issue Mar 21, 2024 · 4 comments
Open

pygbag issue #1

ManPython opened this issue Mar 21, 2024 · 4 comments

Comments

@ManPython
Copy link

pygame-web/pygbag#163

I'm doing this but not working for me.
@educ8s can you confirm that this is still actual or pygbag is not compatible more?

import pygame, sys, random, asyncio
from pygame.math import Vector2

pygame.init()

title_font = pygame.font.Font(None, 60)
score_font = pygame.font.Font(None, 40)

GREEN = (173, 204, 96)
DARK_GREEN = (43, 51, 24)

cell_size = 30
number_of_cells = 25

OFFSET = 75

class Food:
	def __init__(self, snake_body):
		self.position = self.generate_random_pos(snake_body)

	def draw(self):
		food_rect = pygame.Rect(OFFSET + self.position.x * cell_size, OFFSET + self.position.y * cell_size,
			cell_size, cell_size)
		screen.blit(food_surface, food_rect)

	def generate_random_cell(self):
		x = random.randint(0, number_of_cells-1)
		y = random.randint(0, number_of_cells-1)
		return Vector2(x, y)

	def generate_random_pos(self, snake_body):
		position = self.generate_random_cell()
		while position in snake_body:
			position = self.generate_random_cell()
		return position

class Snake:
	def __init__(self):
		self.body = [Vector2(6, 9), Vector2(5,9), Vector2(4,9)]
		self.direction = Vector2(1, 0)
		self.add_segment = False
		self.eat_sound = pygame.mixer.Sound("Sounds/eat.mp3")
		self.wall_hit_sound = pygame.mixer.Sound("Sounds/wall.mp3")

	def draw(self):
		for segment in self.body:
			segment_rect = (OFFSET + segment.x * cell_size, OFFSET+ segment.y * cell_size, cell_size, cell_size)
			pygame.draw.rect(screen, DARK_GREEN, segment_rect, 0, 7)

	def update(self):
		self.body.insert(0, self.body[0] + self.direction)
		if self.add_segment == True:
			self.add_segment = False
		else:
			self.body = self.body[:-1]

	def reset(self):
		self.body = [Vector2(6,9), Vector2(5,9), Vector2(4,9)]
		self.direction = Vector2(1, 0)

class Game:
	def __init__(self):
		self.snake = Snake()
		self.food = Food(self.snake.body)
		self.state = "RUNNING"
		self.score = 0

	def draw(self):
		self.food.draw()
		self.snake.draw()

	def update(self):
		if self.state == "RUNNING":
			self.snake.update()
			self.check_collision_with_food()
			self.check_collision_with_edges()
			self.check_collision_with_tail()

	def check_collision_with_food(self):
		if self.snake.body[0] == self.food.position:
			self.food.position = self.food.generate_random_pos(self.snake.body)
			self.snake.add_segment = True
			self.score += 1
			self.snake.eat_sound.play()

	def check_collision_with_edges(self):
		if self.snake.body[0].x == number_of_cells or self.snake.body[0].x == -1:
			self.game_over()
		if self.snake.body[0].y == number_of_cells or self.snake.body[0].y == -1:
			self.game_over()

	def game_over(self):
		self.snake.reset()
		self.food.position = self.food.generate_random_pos(self.snake.body)
		self.state = "STOPPED"
		self.score = 0
		self.snake.wall_hit_sound.play()

	def check_collision_with_tail(self):
		headless_body = self.snake.body[1:]
		if self.snake.body[0] in headless_body:
			self.game_over()

screen = pygame.display.set_mode((2*OFFSET + cell_size*number_of_cells, 2*OFFSET + cell_size*number_of_cells))

pygame.display.set_caption("Retro Snake")

clock = pygame.time.Clock()

game = Game()
food_surface = pygame.image.load("Graphics/food.png")

SNAKE_UPDATE = pygame.USEREVENT
pygame.time.set_timer(SNAKE_UPDATE, 200)

async def main():
    game = Game()  # Create an instance of the Game class
    while True:
        for event in pygame.event.get():
            if event.type == SNAKE_UPDATE:
                game.update()
            elif event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if game.state == "STOPPED":
                    game.state = "RUNNING"
                if event.key == pygame.K_UP and game.snake.direction != Vector2(0, 1):
                    game.snake.direction = Vector2(0, -1)
                elif event.key == pygame.K_DOWN and game.snake.direction != Vector2(0, -1):
                    game.snake.direction = Vector2(0, 1)
                elif event.key == pygame.K_LEFT and game.snake.direction != Vector2(1, 0):
                    game.snake.direction = Vector2(-1, 0)
                elif event.key == pygame.K_RIGHT and game.snake.direction != Vector2(-1, 0):
                    game.snake.direction = Vector2(1, 0)

        # Drawing
        screen.fill(GREEN)
        pygame.draw.rect(screen, DARK_GREEN,
                         (OFFSET - 5, OFFSET - 5, cell_size * number_of_cells + 10, cell_size * number_of_cells + 10), 5)
        game.draw()
        title_surface = title_font.render("Retro Snake", True, DARK_GREEN)
        score_surface = score_font.render(str(game.score), True, DARK_GREEN)
        screen.blit(title_surface, (OFFSET - 5, 20))
        screen.blit(score_surface, (OFFSET - 5, OFFSET + cell_size * number_of_cells + 10))

        pygame.display.update()
        clock.tick(60)
        await asyncio.sleep(0)

# Start the event loop
asyncio.run(main())
@ad-okshaj
Copy link

ad-okshaj commented Nov 14, 2024

@ManPython @educ8s

  1. Make sure you use https://localhost:800/#debug - this will show you logs and if there exists any error.
  2. Make sure when you add the asyncio code you do not mess up the indentation.
  3. Comment these lines in your code:
# self.eat_sound = pygame.mixer.Sound("Sounds/eat.mp3")
# self.wall_hit_sound = pygame.mixer.Sound("Sounds/wall.mp3")
# self.snake.eat_sound.play()
# self.snake.wall_hit_sound.play()

Hope this solves your issue, and helps others facing problems too!

@ManPython
Copy link
Author

Ok, without sound working, but how to operate sound?

sys._emscripten_info(emscripten_version=(3, 1, 56), runtime='Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0', pthreads=False, shared_memory=False)
715: starting shell
1039: 213 lines queued for async eval
Loading snake from snake.apk
    Pygbag Version : 0.9.2
    Template Version : 0.9.0
    Python  : 3.12
    CDN URL : http://localhost:8000//archives/0.9/
    Screen  : 1280x720
    Title   : snake
    Folder  : snake
    Authors : pgw
    SPDX-License-Identifier: cookiecutter.spdx


1764: __file__='/data/data/org.python/assets/__main__.py' done : now trying user sources
1830: local=None source='' is_py=False hint='main.py'
1867: local=None source='' is_py=False hint='main.py'
404: embed= or sys.argv=['debug']
651: starting EventTarget in a few seconds

Python 3.12.2 (main, Mar  5 2024, 11:18:41) [Clang 19.0.0git (https:/github.com/llvm/llvm-project aec6a04b8e99b42eca431fc0b5 on emscripten
Type "help", "copyright", "credits" or "license" for more information.
>>> 309: assets found : 0
364: EventTarget delayed by loader
/data/data/org.python/assets/site-packages/pygame/sysfont.py:235: UserWarning: no fc_cache font cache file at /data/data/snake/assets/fc_cache
  warnings.warn(f"no fc_cache font cache file at {fc_cache}")
690: : runpy(main=PosixPath('/data/data/snake/assets/main.py'))
655: preload_code(len(code)=5248 hint=PosixPath('/data/data/snake/assets/main.py') loaderhome='.')
654: aio.pep0723.check_list aio.pep0723.env=PosixPath('/data/data/org.python/assets/build/env')

----------- computing required packages ----------
{}
----------------------------------------

656: aio.pep0723.pip_install deps=[]

1214: list_imports len(code)=5248 file=None hint=PosixPath('/data/data/snake/assets/main.py')")
aio.pep0723.Config.pkg_repolist[0]['-CDN-']='http://localhost:8000/archives/repo/'


<stdin>:42: SyntaxWarning: invalid escape sequence '\e'
<stdin>:43: SyntaxWarning: invalid escape sequence '\w'
1153: scan_imports hint=PosixPath('/data/data/snake/assets/main.py') filename='<stdin>' len(code)=5248 []
635: maybe_wanted=[] known failed aio.pep0723.hint_failed=[]
715: starting shell
1039: 151 lines queued for async eval
going interactive
746: TODO detect input/print to select repl debug
<console>:42: SyntaxWarning: invalid escape sequence '\e'
<console>:43: SyntaxWarning: invalid escape sequence '\w'
Traceback (most recent call last):
  File "<console>", line 42, in __init__
FileNotFoundError: No file 'Sounds\eat.mp3' found in working directory '/data/data/snake/assets'.
>>> 
KeyboardInterrupt

why '/data/data/snake/assets'.??

@ManPython
Copy link
Author

also in browser error is:

FIXME: TypeError: navigator.userAgentData is undefined
    mobile http://localhost:8000//archives/0.9/pythons.js:1892
    onload http://localhost:8000//archives/0.9/pythons.js:2129
    auto_start http://localhost:8000//archives/0.9/pythons.js:2526
    <anonymous> http://localhost:8000//archives/0.9/pythons.js:2550

@ManPython
Copy link
Author

Ok, I resolved.. can't be mp3 must be ogg

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants