Как заставить работать финальный py2app (работает псевдоним)? PS Если вы находитесь на Reddit, и вы помогаете мне решить эту проблему, я дам вам награду - PullRequest
0 голосов
/ 25 апреля 2020

Фон Я перепробовал все, чтобы превратить мою игру в исполняемый файл. Игра работает отлично, и в py2app почти всегда работает псевдоним. Я попытался использовать старое семейство P C для pyinstaller, cx_Freeze, py-to-exe и всех вариантов, которые вы можете назвать. И на P C, и на Ma c я просто не могу заставить его работать, но первоначальная цель состояла в том, чтобы сделать .app, поэтому теперь, когда я награждаю того, кто его решает, я бы хотел, чтобы кто-то помог мне с py2app. Я буду готов ответить на любые вопросы на протяжении всего этого процесса, чтобы помочь любому, кто поможет мне в этом.

Текущая ошибка Я просмотрел всего около 10 различных сообщений об ошибках, и я чувствую, что каждый раз, когда я что-то исправляю, появляется другая ошибка. Вот ошибки, которые у меня возникают сейчас: Когда я пытаюсь запустить программный терминал в режиме псевдонима, он говорит следующее:

*** creating application bundle: kled ***
error: [Errno 1] Operation not permitted: '/Users/john/Documents/kledfinal/dist/kled.app/Contents/MacOS/kled'

, а фактическая программа (при нажатии) говорит следующее:

kled обнаружил фатальную ошибку и теперь завершается. Главный скрипт не может быть расположен в папке Resource.;

Также, чтобы сделать так, чтобы моя программа не зависела от пути, я переместил скрипт в папку со всеми моими спрайтами и вычеркнул путь перед моими изображениями, но когда я пытаюсь его запустить, терминал говорит:

File "/Users/john/Documents/kledfinal/kled.py", line 1, in <module>
    import pygame
ModuleNotFoundError: No module named 'pygame'

ОДНАКО эта точно такая же программа работала на моем Ma c, когда каждое изображение смотрело как это:

background = pygame.image.load('/Users/john/Documents/pygameDocs/kledPlatformer/noxus.png')

вместо этого: (ПРИМЕЧАНИЕ: на P C метод помещения моих изображений в папку с моим скриптом и наличия кода таким образом хорошо работал на моем компьютере, но все еще не неправильно конвертировать в .exe)

background = pygame.image.load('noxus.png')

Информация о компьютере macOS Catalina В VS Code внизу моей программы написано, что я работаю на Python 3.7.7 64-битной

Код установки и игры Вот мой код setup.py:

"""
This is a setup.py script generated by py2applet

Usage:
    python setup.py py2app
"""

from setuptools import setup

APP = ['kled.py']
DATA_FILES = ['introscreen.png','jinxemote1.png','jinxemote2.png','jumpleft.png','jumpright.png','jumpUPleft.png','jumpUPright.png','left1.png','left2.png','loseScreen.png','midleft.png','midright.png','noxus.png','pressAnything.png','pressAnything2.png','right1.png','right2.png','rocket1.png','rocket2.png','spat1.png','spat2.png']
OPTIONS = {}

setup(
    app=APP,
    data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)

Вот мой окончательный код игры:

import pygame
from pygame import *
import time
import random
import sys
import os
import pickle

try:
    with open('highscore.dat', 'rb') as file:
        highscore = pickle.load(file)

except:
    highscore = 0



def message_to_screen(msg, color, xcor, ycor):
    screen_text = font.render(msg, True, color) 
    gameDisplay.blit(screen_text, [xcor, ycor]) 

def intro():
    introscreen = pygame.image.load('introscreen.png')
    pressanything = [pygame.image.load('pressAnything.png'), pygame.image.load('pressAnything2.png')]

    introRun = True
    tock = 0
    imageNum = 0
    flashSpeed = 8
    while introRun == True:
        tock += 1

        if tock <= flashSpeed:
            imageNum = 0
        elif tock > flashSpeed:
            imageNum = 1
        if tock > flashSpeed * 2:
            tock = 0
        gameDisplay.blit(introscreen, (0, 0))
        gameDisplay.blit(pressanything[imageNum], (250, 100))
        pygame.display.update()
        clock.tick(10)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                introRun = False

def resetGlobals():
    global falling
    global nextRocket
    global nextRocket2
    global kledX
    global kledY
    global score
    global GA

    GA = 0
    score = 0
    falling = True
    nextRocket = False
    nextRocket2 = False
    kledX = 50
    kledY = displayHeight - 300

def lose():
    global gameRun
    global falling
    global highscore
    gameRun = False
    loseScreen = pygame.image.load('loseScreen.png')

    introRun = True

    if score > highscore:
        highscore = score

    # save the score
    with open('highscore.dat', 'wb') as file:
        pickle.dump(highscore, file)




    class Emotes():
            def __init__ (self, x, y, image, xVelocity = 3, yVelocity = 3):
                self.x = x
                self.y = y
                self.xVelocity = xVelocity
                self.yVelocity = yVelocity
                self.image = image

            def move(self):
                self.x += self.xVelocity
                self.y += self.yVelocity

                if self.x <= 0:
                    self.xVelocity = 3

                if self.x + 200 + self.xVelocity > 800:
                    self.xVelocity = -3

                if self.y <= 0:
                    self.yVelocity = 3

                if self.y + 200 + self.yVelocity > 600:
                    self.yVelocity = -3

            def draw(self):
                gameDisplay.blit(self.image, (self.x, self.y))
                message_to_screen('score: {}'.format(score), white, 0, 0)
                message_to_screen('high score: %d' % highscore, white, 0, 50)
            def do(self):
                self.draw()

                self.move()

    image1 = pygame.image.load('jinxemote1.png') 
    image2 = pygame.image.load('jinxemote2.png')
    e1 = Emotes(600, 70, image1)
    e2 = Emotes(190, 250, image2)


    while introRun == True:

        gameDisplay.blit(loseScreen, (0,0))
        e1.do()
        e2.do()

        pygame.display.update()
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                introRun = False

    resetGlobals()
    gameRun = True

class Platform():
    def __init__(self, x, y, width, height, color = (0,0,0)):
        self.x = x
        self.y = y 
        self.width = width 
        self.height = height 
        self.color = color 

    def onPlatform(self):
        global falling
        global kledX
        global kledY
        global ontop
        global platNum

        if falling and (kledY + 100 <= self.y and kledY + 100 + jumpVelocity >= self.y) and (self.x <= kledX + 50 <= self.x + self.width):
            kledY = self.y - 100
            falling = False
            ontop = True


        if platNum == '1' and not (p1.x <= kledX + 50 <= p1.x + p1.width):
            falling = True
            ontop = False
            platNum = ''
        if platNum == '2' and not (p2.x <= kledX + 50 <= p2.x + p2.width):
            falling = True
            ontop = False
            platNum = ''
        if platNum == '3' and not (p3.x <= kledX + 50 <= p3.x + p3.width):
            falling = True
            ontop = False
            platNum = ''
        if platNum == '4' and not (p4.x <= kledX + 50 <= p4.x + p4.width):
            falling = True
            ontop = False
            platNum = ''   
        if platNum == '5' and not (p5.x <= kledX + 50 <= p5.x + p5.width):
            falling = True
            ontop = False
            platNum = ''  
        if platNum == '6' and not (p6.x <= kledX + 50 <= p6.x + p6.width):
            falling = True
            ontop = False
            platNum = ''   
        if platNum == '7' and not (p7.x <= kledX + 50 <= p7.x + p7.width):
            falling = True
            ontop = False
            platNum = ''  
        if platNum == '8' and not (p8.x <= kledX + 50 <= p8.x + p8.width):
            falling = True
            ontop = False
            platNum = ''  


    def whichPlatform(self):
        global kledX
        global kledY
        global ontop
        global platNum
        global falling

        if ontop and (kledY + 100 <= p0.y and kledY + 100 + jumpVelocity >= p0.y) and (p0.x <= kledX + 50 <= p0.x + p0.width):
            platNum = '0'
        if ontop and (kledY + 100 <= p1.y and kledY + 100 + jumpVelocity >= p1.y) and (p1.x <= kledX + 50 <= p1.x + p1.width):
            platNum = '1'
        if ontop and (kledY + 100 <= p2.y and kledY + 100 + jumpVelocity >= p2.y) and (p2.x <= kledX + 50 <= p2.x + p2.width):
            platNum = '2'
        if ontop and (kledY + 100 <= p3.y and kledY + 100 + jumpVelocity >= p3.y) and (p3.x <= kledX + 50 <= p3.x + p3.width):
            platNum = '3'
        if ontop and (kledY + 100 <= p4.y and kledY + 100 + jumpVelocity >= p4.y) and (p4.x <= kledX + 50 <= p4.x + p4.width):
            platNum = '4'
        if ontop and (kledY + 100 <= p5.y and kledY + 100 + jumpVelocity >= p5.y) and (p5.x <= kledX + 50 <= p5.x + p5.width):
            platNum = '5'
        if ontop and (kledY + 100 <= p6.y and kledY + 100 + jumpVelocity >= p6.y) and (p6.x <= kledX + 50 <= p6.x + p6.width):
            platNum = '6'
        if ontop and (kledY + 100 <= p7.y and kledY + 100 + jumpVelocity >= p7.y) and (p7.x <= kledX + 50 <= p7.x + p7.width):
            platNum = '7'
        if ontop and (kledY + 100 <= p8.y and kledY + 100 + jumpVelocity >= p8.y) and (p8.x <= kledX + 50 <= p8.x + p8.width):
            platNum = '8'

    def drawPlat(self):
        pygame.draw.rect(gameDisplay, self.color, (self.x, self.y, self.width, self.height))

    def do(self):
        self.onPlatform()
        self.whichPlatform()
        self.drawPlat()

class Rocket():
    def __init__(self, speedLim, x = 800, y = 300, xVelocity = 5, gameSpeed = 0, invisScore = 0):
        self.x = x
        self.y = y 
        self.xVelocity = xVelocity
        self.gameSpeed = gameSpeed
        self.gameSpeed = 5
        self.invisScore = invisScore
        self.speedLim = speedLim

    def newRocket(self):
        global nextRocket
        global nextRocket2
        self.invisScore += 1
        self.y = random.randint(0, displayHeight - 150)
        self.x = displayWidth + 200
        self.xVelocity = self.gameSpeed
        if self.gameSpeed < 15:
            self.gameSpeed += 1
        if self.gameSpeed > self.speedLim:
            self.gameSpeed = self.speedLim

        elif self.invisScore >= 15:
            nextRocket = True

        if self.invisScore >= 30:
            nextRocket2 = True


    def move(self):
        global imageNum
        global tock
        animationSpeed = 6

        tock += 1
        if tock > 6:
            imageNum = 0
        elif tock <= 6:
            imageNum = 1
        if tock >= animationSpeed * 2:
            tock = 0

        self.x -= self.xVelocity
        if self.x <= -200:
            self.newRocket()

    def draw(self):
        global imageNum
        global gameDisplay
        global rocketImage
        gameDisplay.blit(rocketImage[imageNum], (self.x, self.y))


    def isHit(self):
        global kledX
        global kledY
        global nextRocket
        global nextRocket2
        if ((kledX <= self.x + 10 <= kledX + 90) and (kledY <= self.y + 10 <= kledY + 90)) or ((kledX <= self.x + 10 <= kledX + 90) and (kledY <= self.y + 90 <= kledY + 90)) or ((kledX <= self.x +90 <= kledX + 90) and (kledY <= self.y <= kledY + 90)) or ((kledX <= self.x +90 <= kledX + 90) and (kledY <= self.y +90 <= kledY + 90)):    
            self.invisScore = 0
            self.gameSpeed = 5
            self.x = -199
            self.y = 300
            lose()



    def do(self):
        self.isHit()
        self.move()
        self.draw()

class Items():
    def __init__(self, x, y, image, value, spawnArea):
        self.x = x
        self.y = y
        self.image = image
        self.value = value
        self.spawnArea = spawnArea

    def spawn(self):
        global displayHeight
        global displayWidth
        if self.spawnArea == 'close':
            self.x = random.randint(0, displayWidth - 400)
            self.y = random.randint(0, displayHeight - 100)
        if self.spawnArea == 'far':
            self.x = random.randint(displayWidth -200, displayWidth - 100)
            self.y = random.randint(0, displayHeight - 100)

    def pickUp(self):
        picked = False
        global kledX
        global score
        if ((kledX <= self.x <= kledX + 100) and (kledY <= self.y <= kledY + 100)) or ((kledX <= self.x <= kledX + 100) and (kledY <= self.y + 50 <= kledY + 100)) or ((kledX <= self.x + 50 <= kledX + 100) and (kledY <= self.y <= kledY + 100)) or ((kledX <= self.x + 50 <= kledX + 100) and (kledY <= self.y + 50 <= kledY + 100)):
            picked = True
        if picked == True:
            score += self.value
            self.spawn()
            picked = False

    def draw(self):
        global gameDisplay
        gameDisplay.blit(self.image, (self.x, self.y))

    def do(self):
        self.draw()
        self.pickUp()


# images
rocketImage = [pygame.image.load('rocket1.png'), pygame.image.load('rocket2.png')]
midleft = pygame.image.load('midleft.png')
midright = pygame.image.load('midright.png')
left = [pygame.image.load('left1.png'), pygame.image.load('left2.png')]
right = [pygame.image.load('right1.png'), pygame.image.load('right2.png')]
leftjump = pygame.image.load('jumpleft.png')
rightjump = pygame.image.load('jumpright.png')
rightUPjump = pygame.image.load('jumpUPright.png')
leftUPjump = pygame.image.load('jumpUPleft.png')
background = pygame.image.load('noxus.png')

# screen initialize
pygame.init()
pygame.display.set_caption('The Adventures of Kled and Skaarl')
displayWidth = 800
displayHeight = 600
gameDisplay = pygame.display.set_mode((displayWidth, displayHeight))
clock = pygame.time.Clock()
FPS = 30
tock = 0



# defining variables
direction = 'left'
onPlatform = False
imageC = 0
animationSpeed = 4 
isMoving = False
ontop = False
platNum = '0'
jumpVelocity = 10
jumpYchange = 10
falling = True
jumpCount = 0
jumpHeight = 15
isJump = False
velocity = 10
kledX = 50
kledY = displayHeight - 400
gameRun = True
black = (0,0,0)
blue = (137, 207, 240)
green = (34, 139, 34)
white = (255,255,255)
fontSize = 40
font = pygame.font.SysFont(None, fontSize)

# instances platform
p0 = Platform(0, displayHeight - 50, displayWidth, 1)
p1 = Platform(200, 450, 100, 20) #x, y, width, height, color
p2 = Platform(400, 450, 100, 20)
p3 = Platform(300, 350, 100, 20)
p4 = Platform(100, 250,  100, 20)
p5 = Platform(500, 250, 100, 20)
p6 = Platform(600, 150, 100, 20)
p7 = Platform(300, 150, 100, 20)
p8 = Platform(0, 450, 100, 20)

# instances rocket
r1 = Rocket(15)
r2 = Rocket(10)
r3 = Rocket(5)
nextRocket = False
nextRocket2 = False

# instances items
i1 = Items(random.randint(0, displayWidth - 200), random.randint(0, displayHeight - 100), pygame.image.load('spat1.png'), 1, 'close')
i2 = Items(random.randint(displayWidth - 300, displayWidth - 90), random.randint(0, displayHeight - 100), pygame.image.load('spat2.png'), 2, 'far')
score = 0
GA = 0

intro()
while gameRun:
    # EVENT HANDELING
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameRun = False

    k = pygame.key.get_pressed()

    if k[K_LEFT] and kledX + velocity > 0:
        direction = 'left'
        kledX -= velocity
        isMoving = True
    elif k[K_RIGHT] and kledX + 100 + velocity < 800:
        direction = 'right'
        kledX += velocity
        isMoving = True
    else: 
        isMoving = False

    if k[K_UP] and isJump == False and falling == False:
        isJump = True
        ontop = False
        platNum = ''
    if k[K_DOWN] and isJump == False and falling == False and not platNum == '0': 
        falling = True
        platNum = ''

    if isJump:
        jumpCount += 1
        jumpVelocity = -jumpYchange
        if jumpCount >= jumpHeight or kledY + velocity < 0:
            falling = True
            ontop = False
            isJump = False
    else:
        jumpVelocity = 0
        jumpCount = 0

    if falling:
        jumpVelocity = jumpYchange
        ontop = False

    kledY += jumpVelocity
    imageC += 1
    if imageC >= animationSpeed:
        imageNumber = 0
    elif imageC < animationSpeed:
        imageNumber = 1
    if imageC > animationSpeed*2:
            imageC = 0

    # REDRAW
    if direction == 'right' and not isMoving and not (isJump or falling):
        gameDisplay.blit(midright, (kledX, kledY))
    elif direction == 'left' and not isMoving and not(isJump or falling):
        gameDisplay.blit(midleft, (kledX, kledY))
    elif direction == 'right' and isMoving and not (isJump or falling):
        gameDisplay.blit(right[imageNumber], (kledX, kledY)) 
    elif direction == 'left' and isMoving and not (isJump or falling):
        gameDisplay.blit(left[imageNumber], (kledX, kledY)) 
    elif direction == 'left' and falling:
        gameDisplay.blit(leftjump, (kledX, kledY))
    elif direction == 'right' and falling:
        gameDisplay.blit(rightjump, (kledX, kledY))
    elif direction == 'left' and isJump:
        gameDisplay.blit(leftUPjump, (kledX, kledY))
    elif direction =='right' and isJump:
        gameDisplay.blit(rightUPjump, (kledX, kledY))

    pygame.display.update()
    gameDisplay.blit(background, (0,0))
    message_to_screen('score: {}'.format(score), black, 0, 0)
    pygame.draw.rect(gameDisplay, black, (0, displayHeight-50, displayWidth, 50))
    p0.do()
    p1.do()
    p2.do()
    p3.do()
    p4.do()
    p5.do()
    p6.do()
    p7.do()
    p8.do()
    r1.do()
    if nextRocket:
        r2.do()

    if nextRocket2:
        r3.do()
    i1.do()
    i2.do()


    # load the previous score if it exists
    clock.tick(FPS)

pygame.quit()
quit()
...