pygame-web / pygbag

python and pygame wasm for everyone ( packager + test server + simulator )
https://github.com/pygame-web
MIT License
319 stars 36 forks source link

FileNotFoundError: [Errno 44] No such file or directory: '/data/data/cat_dash/assets/main.py' #125

Closed Jamalch15 closed 11 months ago

Jamalch15 commented 11 months ago

When I run the game in browser using the link, it shows a black screen, and when i debug it shows this:

Task exception was never retrieved future: <Task finished name='custom_site' coro=<custom_site() done, defined at :52> exception=FileNotFoundError(44, 'No such file or directory')> Traceback (most recent call last): File "", line 186, in custom_site File "", line 712, in runpy File "", line 685, in check_code FileNotFoundError: [Errno 44] No such file or directory: '/data/data/cat_dash/assets/main.py'

image

Don't mind my ugly code, I'm new. Also, this is my first GitHub post, so idk if I've given enough info. :)

import json
import math
import os
import pygame
import random
import sys
import asyncio

pygame.init()

SCREEN_WIDTH, SCREEN_HEIGHT = 1280, 720
fullscreen = False
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Endless Runner Game")

background = pygame.transform.scale(pygame.image.load("background.png"), (SCREEN_WIDTH, SCREEN_HEIGHT))

carOne = pygame.image.load("car1.png")
carLug = pygame.transform.scale(pygame.image.load("carLug.png"), (231, 190))

scaleFactor = 0.75
catSize = 60
catY = 580
catX = 150
catJumpX = 0
catJumpY = 0
jumping = False
catSpeed = 5
catDirectionBool = False
catDirection = 1
runFrame = 0
flyFrame = 0
movementAllowed = True
dead = False
catHeight = 0
points = 0
highscore = 0
catLane = 580
rightLane = 580
leftLane = 450
qPressed = False
ePressed = False
right = True
left = False
balance = 0
backgroundX = 0
speedUp = 0.0009
speed = 0
animationSpeed = 0
sessionScore = 0
catSizeIdle = 128
scaleFactorIdle = 6
catIdle = []
carsRight = []
carsXRight = []
carsLeft = []
carsXLeft = []
spawnPoint = 0

catRun = [pygame.transform.scale(pygame.image.load(f"cat animations/catRun{i}.png"),
                                 (catSize, catSize * scaleFactor)) for i in range(1, 7)]

spritesheetIdle = pygame.transform.scale(pygame.image.load("cat animations/WhiteCatIdle.png"),
                                         (catSizeIdle, catSizeIdle * scaleFactorIdle))

for frame in range(catSizeIdle * scaleFactorIdle // catSizeIdle):
    frameRect = pygame.Rect(0, frame * catSizeIdle, catSizeIdle, catSizeIdle)
    catIdle.append(spritesheetIdle.subsurface(frameRect))

catJumpAni = pygame.transform.scale(pygame.image.load("cat animations/catJump.png"), (catSize, catSize * scaleFactor))

catFlyV = pygame.image.load("cat animations/VenstreCatBlod.png").convert_alpha()
catFlyV.set_alpha(128)
catFlyM = pygame.image.load("cat animations/MidtCatBlod.png").convert_alpha()
catFlyM.set_alpha(128)
catFlyH = pygame.image.load("cat animations/HøjreCatFlyv.png").convert_alpha()
catFlyH.set_alpha(128)

catFly = [
    pygame.transform.scale(catFlyM, (catSize * scaleFactor, catSize)),
    pygame.transform.scale(catFlyH, (catSize * scaleFactor, catSize)),
    pygame.transform.scale(catFlyM, (catSize * scaleFactor, catSize)),
    pygame.transform.scale(catFlyV, (catSize * scaleFactor, catSize)),
]

clock = pygame.time.Clock()

def getSavePath():
    # Determine the user-specific directory based on the OS
    if os.name == 'posix':
        # Linux or macOS
        user_dir = os.path.expanduser("~")
    elif os.name == 'nt':
        # Windows
        user_dir = os.path.join(os.environ['HOMEPATH'], 'Documents')
    else:
        user_dir = None

    # Create a subdirectory for your game
    game_dir = os.path.join(user_dir, 'Cat_Dash')

    # Ensure the directory exists
    os.makedirs(game_dir, exist_ok=True)

    # Return the path to the high score file
    return os.path.join(game_dir, 'saves.json')

def loadSave():
    savePath = getSavePath()
    try:
        with open(savePath, "r") as file:
            data = json.load(file)
            return data
    except FileNotFoundError:
        return {}

def saveData(data):
    savePath = getSavePath()
    with open(savePath, "w") as file:
        json.dump(data, file)

savedData = loadSave()
if 'highscore' not in savedData:
    savedData['highscore'] = 0
if 'balance' not in savedData:
    savedData['balance'] = 0

text = None

def displayScore():
    global sessionScore, highscore, points, text
    font = pygame.font.SysFont("comicsansms", 100, bold=True)
    if not dead:
        text = f"{points}"
    textColor = (255, 229, 145)
    textSurface = font.render(text, True, textColor)
    textX = (SCREEN_WIDTH - textSurface.get_width()) // 2
    screen.blit(textSurface, (textX, 25))

    if points > sessionScore:
        sessionScore = points

    savedData['highscore'] = max(savedData['highscore'], points)
    highscore = savedData['highscore']
    saveData(savedData)

    font = pygame.font.SysFont("comicsansms", 20)
    highscoreText = f"Highscore: {highscore}"
    textColor = (255, 255, 255)
    textSurface = font.render(highscoreText, True, textColor)
    textX = SCREEN_WIDTH - textSurface.get_width() - 50
    screen.blit(textSurface, (textX, 25))

def calculateBalance():
    global balance, points
    balance = savedData['balance']
    coins = math.floor(points / 5)
    if dead:
        points = 0
        balance += coins
        savedData['balance'] += coins
        saveData(savedData)

    print(balance)

def displayIntro():
    font = pygame.font.SysFont("comicsansms", 120, bold=True)
    text = "Cat Dash"
    textColor = (255, 165, 0)
    textSurface = font.render(text, True, textColor)
    textX = (SCREEN_WIDTH - textSurface.get_width()) // 2

    screen.blit(textSurface, (textX, 25))

    startButtonWidth = 150
    startButtonHeight = 50
    startButtonColor = (44, 130, 201)
    startButtonHover = (64, 150, 221)
    startTextColor = (255, 255, 255)
    startButtonText = "Play"
    startFont = pygame.font.SysFont("comicsansms", 36, bold=True)

    font = pygame.font.SysFont("comicsansms", 20)
    text = "Press 'Space' to start, or:"
    textColor = (0, 0, 0)
    textSurface = font.render(text, True, textColor)
    textX = (SCREEN_WIDTH - textSurface.get_width()) // 2

    screen.blit(textSurface, (textX, 395))

    startButtonRect = pygame.Rect((SCREEN_WIDTH - startButtonWidth) // 2,
                                   (SCREEN_HEIGHT - startButtonHeight + 200) // 2, startButtonWidth, startButtonHeight)

    if startButtonRect.collidepoint(pygame.mouse.get_pos()):
        pygame.draw.rect(screen, startButtonHover, startButtonRect)
        pygame.draw.rect(screen, (0, 0, 0), startButtonRect, 2)
    else:
        pygame.draw.rect(screen, startButtonColor, startButtonRect)
        pygame.draw.rect(screen, (0, 0, 0), startButtonRect, 2)

    startTextX = startButtonRect.centerx
    startTextY = startButtonRect.centery - 5

    startTextSurface = startFont.render(startButtonText, True, startTextColor)
    startTextRect = startTextSurface.get_rect(center=(startTextX, startTextY))
    screen.blit(startTextSurface, startTextRect)

    return startButtonRect

def displayReset():
    resetButtonWidth = 160
    resetButtonHeight = 50
    resetButtonColor = (44, 130, 201)  # A shade of blue
    resetButtonHover = (64, 150, 221)  # A slightly brighter shade of blue for hover
    resetTextColor = (255, 255, 255)
    resetButtonText = "Reset"
    resetFont = pygame.font.SysFont("comicsansms", 36, bold=True)

    font = pygame.font.SysFont("comicsansms", 20)
    text = "Press 'R' to reset, or:"
    textColor = (0, 0, 0)
    textSurface = font.render(text, True, textColor)
    textX = (SCREEN_WIDTH - textSurface.get_width()) // 2

    screen.blit(textSurface, (textX, 395))

    resetButtonRect = pygame.Rect((SCREEN_WIDTH - resetButtonWidth) // 2, (SCREEN_HEIGHT - resetButtonHeight + 200) // 2
                                  , resetButtonWidth, resetButtonHeight)

    if resetButtonRect.collidepoint(pygame.mouse.get_pos()):
        pygame.draw.rect(screen, resetButtonHover, resetButtonRect)
        pygame.draw.rect(screen, (0, 0, 0), resetButtonRect, 2)
    else:
        pygame.draw.rect(screen, resetButtonColor, resetButtonRect)
        pygame.draw.rect(screen, (0, 0, 0), resetButtonRect, 2)

    resetTextX = resetButtonRect.centerx
    resetTextY = resetButtonRect.centery - 5

    resetTextSurface = resetFont.render(resetButtonText, True, resetTextColor)
    resetTextRect = resetTextSurface.get_rect(center=(resetTextX, resetTextY))
    screen.blit(resetTextSurface, resetTextRect)

    return resetButtonRect

def endlessBackground():
    global backgroundX
    backgroundX -= min(speed, 8)
    screen.blit(background, (backgroundX, 0))
    screen.blit(background, (backgroundX + SCREEN_WIDTH, 0))
    if backgroundX < -SCREEN_WIDTH:
        backgroundX = 0

def spawnObstacles():
    global points

    if not carsRight or carsRight[-1].right < SCREEN_WIDTH:
        spawnPoint = random.randint(int(SCREEN_WIDTH * (1 / 3)), int(SCREEN_WIDTH * (2 / 3)))
        carX = SCREEN_WIDTH + spawnPoint
        carY = rightLane + 85
        num = random.randint(0, 100)

        if num > 80:
            car = carLug.get_rect(bottomleft=(carX, carY))
        else:
            car = carOne.get_rect(bottomleft=(carX, carY))

        carsRight.append(car)
        carsXRight.append(car)

    if not carsLeft or carsLeft[-1].right < SCREEN_WIDTH:
        spawnPoint = random.randint(int(SCREEN_WIDTH * (1 / 3) + SCREEN_WIDTH / 2),
                                    int(SCREEN_WIDTH * (2 / 3)+ SCREEN_WIDTH / 2))
        carX = SCREEN_WIDTH + spawnPoint
        carY = leftLane + 70
        num = random.randint(0, 100)
        if num > 80:
            car = carLug.get_rect(bottomleft=(carX, carY))
        else:
            car = carOne.get_rect(bottomleft=(carX, carY))

        carsLeft.append(car)
        carsXLeft.append(car)

    for car in carsRight:
        if car.height == 121:
            screen.blit(carOne, car)
        else:
            screen.blit(carLug, car)

    for car in carsLeft:
        if car.height == 121:
            screen.blit(carOne, car)
        else:
            screen.blit(carLug, car)

def moveCars():
    for car in carsRight:
        car.x -= min(speed + 2, 21)
        if car.right < 0:
            carsRight.remove(car)
    for car in carsLeft:
        car.x -= min(speed + 2, 21)
        if car.right < 0:
            carsLeft.remove(car)

def awardPoins():
    global points
    if catX > carsXRight[0].right and not dead:
        points += 1
        carsXRight.remove(carsXRight[0])

    if catX > carsXLeft[0].right and not dead:
        points += 1
        carsXLeft.remove(carsXLeft[0])

def reset():
    global dead, catX, catY, speed, points
    dead = False
    catX = 150
    catY = 580
    speed = 2
    points = 0
    carsRight.clear()
    carsXRight.clear()
    carsLeft.clear()
    carsXLeft.clear()

def cat():
    global catY, catX, animationSpeed, jumping, catJumpY, catDirectionBool, \
        catDirection, catLane, qPressed, ePressed, left, right

    keys = pygame.key.get_pressed()

    if speed == 0:
        animationSpeed += 0.2
        idleFrame = math.floor(animationSpeed % len(catIdle))
        screen.blit(pygame.transform.flip(catIdle[idleFrame], catDirectionBool, False), (catX - 30, catY - 20))

    else:
        if not dead:
            catY -= catJumpY
            catJumpY -= 1
            if catY >= catLane:
                catY = catLane
                jumping = False

            if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
                catX += catSpeed + speedUp
                catDirectionBool = False
            elif keys[pygame.K_a] or keys[pygame.K_LEFT]:
                catX -= catSpeed + speedUp
                catDirectionBool = True
                catDirection = -1
            else:
                catDirectionBool = False
                catDirection = 1

        if not jumping and not dead:

            if not qPressed and not ePressed:
                if keys[pygame.K_q] or keys[pygame.K_UP]:
                    if catLane > leftLane:
                        qPressed = True
                if keys[pygame.K_e] or keys[pygame.K_DOWN]:
                    if catLane < rightLane:
                        ePressed = True
            elif catY == leftLane:
                qPressed = False
            elif catY == rightLane:
                ePressed = False

            if qPressed:
                left = True
                right = False
                if catLane > leftLane:
                    catLane -= 10 + speedUp
                    if catLane <= leftLane:
                        catLane = leftLane
            if ePressed:
                left = False
                right = True
                if catLane < rightLane:
                    catLane += 10 + speedUp
                    if catLane >= rightLane:
                        catLane = rightLane

            if keys[pygame.K_w] or keys[pygame.K_SPACE]:
                if not ePressed and not qPressed:
                    catJumpY = 14.5
                    jumping = True
                    # jumpSound.play()

            animationSpeed += 0.4 + speedUp
            runFrame = math.floor(animationSpeed % len(catRun))
            catRunFlipped = pygame.transform.flip(catRun[runFrame], catDirectionBool, False)
            if qPressed and not catDirectionBool:
                screen.blit(pygame.transform.rotate(catRunFlipped, 20), (catX, catY))
            elif ePressed and not catDirectionBool:
                screen.blit(pygame.transform.rotate(catRunFlipped, -20), (catX, catY))
            elif qPressed and catDirectionBool:
                screen.blit(pygame.transform.rotate(catRunFlipped, -20), (catX, catY))
            elif ePressed and catDirectionBool:
                screen.blit(pygame.transform.rotate(catRunFlipped, 20), (catX, catY))
            else:
                screen.blit(catRunFlipped, (catX, catY))

        elif not dead:
            screen.blit(pygame.transform.flip(catJumpAni, catDirectionBool, False), (catX, catY))
        else:
            animationSpeed += 0.3
            flyFrame = math.floor(animationSpeed % len(catFly))
            screen.blit(catFly[flyFrame], (catX, catY))
            catY -= 5

        catX = max(0, min(catX, SCREEN_WIDTH - 60))

def collisions():
    global dead, left, right
    catRect = pygame.Rect(catX, catY, catSize, catSize * scaleFactor)
    if not dead:
        if right or qPressed:
            for car in carsRight:
                if car.height == 121:
                    carRectTop = (car[0] + 100, 580, 80, 40)
                    carRectBottom = (car[0] + 35, 610, 160, 40)
                    carRectTopTop = (0, 0, 0, 0)
                else:
                    carRectTop = (car[0] + 100, 530, 80, 80)
                    carRectBottom = (car[0] + 35, 610, 160, 40)
                    carRectTopTop = (car[0] + 120, 510, 40, 40)

                # pygame.draw.rect(screen, (0), carRectTop)
                # pygame.draw.rect(screen, (0), carRectBottom)
                # pygame.draw.rect(screen, (0), carRectTopTop)

                if (catRect.colliderect(carRectTop) or catRect.colliderect(carRectBottom)
                        or catRect.colliderect(carRectTopTop)):
                    dead = True

        if left or ePressed:
            for car in carsLeft:
                if car.height == 121:
                    carRectTop = (car[0] + 100, 565 - (rightLane - leftLane), 80, 40)
                    carRectBottom = (car[0] + 35, 610 - (rightLane - leftLane), 160, 40)
                    carRectTopTop = (0, 0, 0, 0)
                else:
                    carRectTop = (car[0] + 100, 530 - (rightLane - leftLane), 80, 80)
                    carRectBottom = (car[0] + 35, 610 - (rightLane - leftLane), 160, 40)
                    carRectTopTop = (car[0] + 120, 510 - (rightLane - leftLane), 40, 40)

                # pygame.draw.rect(screen, (0), carRectBottom)
                # pygame.draw.rect(screen, (0), carRectTop)
                # pygame.draw.rect(screen, (0), carRectTopTop)

                if (catRect.colliderect(carRectTop) or catRect.colliderect(carRectBottom)
                        or catRect.colliderect(carRectTopTop)):
                    dead = True

start = False

async def main():
    global fullscreen, speed, screen, start, catJumpY, jumping
    startButtonRect = displayIntro()
    resetButtonRect = displayReset()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if startButtonRect.collidepoint(event.pos) and not start:
                start = True
                speed = 2
                catJumpY = 17
                jumping = True
                # jumpSound.play()
            if resetButtonRect.collidepoint(event.pos) and dead:
                reset()

        displayReset()
    keys = pygame.key.get_pressed()
    if keys[pygame.K_f]:
        fullscreen = not fullscreen
        if fullscreen:
            screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.FULLSCREEN)
        else:
            screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    if keys[pygame.K_SPACE] and not start:
        start = True
        speed = 2
    if keys[pygame.K_r] and dead:
        reset()

    endlessBackground()

    if start:
        speed += speedUp
        moveCars()
        displayScore()
        spawnObstacles()
        collisions()
        awardPoins()
    elif not dead:
        displayIntro()
    if dead:
        displayReset()

    cat()
    calculateBalance()

    clock.tick(60)

    pygame.display.flip()
    await asyncio.sleep(0)

asyncio.run(main())
pmp-p commented 11 months ago

Hi, we cannot tell from just those screenshots/code paste, please provide a github project/page or a itch web.zip archive (--archive) of whole project you give to pygbag.

moving this to discussions help zone