我应该怎么做才能让我的游戏在exe格式的工作?

2024-10-08 22:29:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用py2exe转换游戏代码。但是每次我在命令提示符中键入语法python setup.py py2exe,它都会引发一个错误,表示python不能被识别为可操作的批处理文件。你知道吗

我对这些东西完全陌生,在参考了许多网站和我自己的教科书之后,我完全不知道我应该做什么。你知道吗

我将附上游戏代码和其他代码(我不知道是正确的一个使用或不)。你知道吗

import random
from random import randint
import pygame
import sys
from pygame.locals import *

Snakespeed= 9
Snakespeed1 = 17
size = [580,580]
screen = pygame.display.set_mode((580, 580), FULLSCREEN)
background_position = [0,0]


Window_Width= 580
Window_Height= 580
Cell_Size = 20      #Width and height of the cells
assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size."    #Ensuring that the cells fit perfectly in the window. eg if cell size was 10     and window width or windowheight were 15 only 1.5 cells would fit.
assert Window_Height % Cell_Size == 0, "Window height must be a multiple of cell size."  #Ensuring that only whole integer number of cells fit perfectly in the window.
Cell_W= int(Window_Width / Cell_Size) #Cell Width 
Cell_H= int(Window_Height / Cell_Size) #Cellc Height

#******************************************************************************

White= (255,255,255)
Black= (0,0,0)
Red= (255,0,0)         #Defining element colors for the program.
Green= (0,255,0)
DARKGreen= (0,155,0)
DARKGRAY= (40,40,40)
YELLOW= (255,255,0)
Red_DARK= (150,0,0)
BLUE= (0,0,255)
BLUE_DARK= (0,0,150)
BROWN = (165,42,42)


BGCOLOR = Black        # Background color
BGCOLOR1 = YELLOW      # background color for snakes screen.


#*********************************************************************************


UP = 'up'
DOWN = 'down'      # Defining keyboard keys.  
LEFT = 'left'
RIGHT = 'right'

HEAD = 0           # Index of the snake's head

#*********************************************************************************


def main():
    import time
    time.sleep(8)
    global SnakespeedCLOCK, screen, BASICFONT

    pygame.init()
    SnakespeedCLOCK = pygame.time.Clock()
    screen = pygame.display.set_mode((Window_Width, Window_Height), FULLSCREEN)
    BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
    pygame.display.set_caption('Snake')


    #Game Music
    pygame.mixer.init()
    pygame.mixer.music.load('startmusic.mp3')
    pygame.mixer.music.play(-1,0.0)

    showStartScreen()
    while True:
        runGame()
        #Game Music
        pygame.mixer.init()
        pygame.mixer.music.load('WahWah.wav')
        pygame.mixer.music.play(-1,0.0)
        showGameOverScreen()

#wormCoords = [{'x': startx,     'y': starty},
              #{'x': startx - 1, 'y': starty},
              #{'x': startx - 2, 'y': starty}]

def runGame():

    #Game Music
    pygame.mixer.init()
    pygame.mixer.music.load('gamebackground.mp3')
    pygame.mixer.music.play(-1,0.0)


    #Set a random start point.
    #screenSize = user32.GetSystemMetrics(0)/2, user32.GetSystemMetrics(1)/2
    #size = (screenSize)
    pygame.display.set_mode(size, FULLSCREEN)
    global wormCoords
    startx = random.randint(5, Cell_W - 6)
    starty = random.randint(5, Cell_H - 6)

    wormCoords = [{'x': startx,     'y': starty},
                  {'x': startx - 1, 'y': starty},
                  {'x': startx - 2, 'y': starty}]


    direction = RIGHT

    # Start the apple in a random place.
    apple = getRandomLocation()

    while True: # main game loop
        for event in pygame.event.get(): # event handling loop
            if event.type == QUIT:
                terminate()
            elif event.type == KEYDOWN:
                if (event.key == K_LEFT ) and direction != RIGHT:
                    direction = LEFT
                elif (event.key == K_RIGHT ) and direction != LEFT:
                    direction = RIGHT
                elif (event.key == K_UP ) and direction != DOWN:
                    direction = UP
                elif (event.key == K_DOWN ) and direction != UP:
                    direction = DOWN
                elif event.key == K_ESCAPE:
                    terminate()

        # check if the Snake has hit itself or the edge
        if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == Cell_H:

            return # game over 

        for wormBody in wormCoords[1:]:
            if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]    ['y']:

                return # game over


        # check if Snake has eaten an apply
        if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
            # don't remove worm's tail segment

            apple = getRandomLocation() # set a new apple somewhere
        else:
            del wormCoords[-1] # remove worm's tail segment

        # move the worm by adding a segment in the direction it is moving
        if direction == UP:
            newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] - 1}
        elif direction == DOWN:
            newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] + 1}
        elif direction == LEFT:
            newHead = {'x': wormCoords[HEAD]['x'] - 1, 'y': wormCoords[HEAD]['y']}
        elif direction == RIGHT:
            newHead = {'x': wormCoords[HEAD]['x'] + 1, 'y': wormCoords[HEAD]['y']}
        wormCoords.insert(0, newHead)
        background_image = pygame.image.load("snakey.png")
        screen.blit(background_image, background_position)

        #screen.fill(BLUE_DARK)
##        drawGrid()
        drawWorm(wormCoords)
        drawApple(apple)
        global x
        x = len(wormCoords) - 3
        drawScore(x)
        pygame.display.update()
        SnakespeedCLOCK.tick(Snakespeed)

def drawPressKeyMsg():
    pressKeySurf = BASICFONT.render('Press a key to play.',True, White)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (Window_Width - 200, Window_Height - 30)
    screen.blit(pressKeySurf, pressKeyRect)


def checkForKeyPress():
    if len(pygame.event.get(QUIT)) > 0:
        terminate()
    keyUpEvents = pygame.event.get(KEYUP)
    if len(keyUpEvents) == 0:
        return None
    if keyUpEvents[0].key == K_ESCAPE:
        terminate()
    return keyUpEvents[0].key


def showStartScreen():
    titleFont = pygame.font.Font('freesansbold.ttf', 80 )
    titleSurf1 = titleFont.render('SNAKEY ', True, BLUE_DARK)
    degrees1 = 0
    degrees2 = 0
    titleFont1 = pygame.font.Font('freesansbold.ttf', 20)
    titleSurf11 = titleFont1.render('''MADE BY SHIVANGI AND RAGINI, CLASS 12 A ''', True, BROWN)
    while True:
        #screen.fill(BGCOLOR)
        #background_image = pygame.image.load("J:\class 12 comp proj eddited\gamebackground.png")
        background_image = pygame.image.load("gamebackground.jpeg")
        snake = pygame.image.load("snake.png")
        screen.blit(background_image, background_position)
        rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
        rotatedRect1 = rotatedSurf1.get_rect()
        rotatedRect1.center = (Window_Width / 2, Window_Height / 2)
        screen.blit(rotatedSurf1, rotatedRect1)
        screen.blit(titleSurf11, (50,480))
        screen.blit(snake,(20,20))

        drawPressKeyMsg()

        if checkForKeyPress():
            pygame.event.get() # clear event queue
            return
        pygame.display.update()
        SnakespeedCLOCK.tick(Snakespeed1)
        degrees1 += 3 # rotate by 3 degrees each frame
        degrees2 += 7 # rotate by 7 degrees each frame


def terminate():
    pygame.quit()
    sys.exit()


def getRandomLocation():
    return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}


def showGameOverScreen():
    gameOverFont = pygame.font.Font('freesansbold.ttf', 100)
    gameSurf = gameOverFont.render('Game', True, White)
    overSurf = gameOverFont.render('Over', True, White)
    gameRect = gameSurf.get_rect()
    overRect = overSurf.get_rect()
    gameRect.midtop = (Window_Width / 2, 10)
    overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25)



    screen.blit(gameSurf, gameRect)
    screen.blit(overSurf, overRect)
    drawPressKeyMsg()
    pygame.display.update()
    pygame.time.wait(500)
    checkForKeyPress() # clear out any key presses in the event queue

    while True:
        if checkForKeyPress():
            pygame.event.get() # clear event queue
            return

def drawScore(score):
    scoreSurf = BASICFONT.render('Score: %s' % (score), True, White)
    scoreRect = scoreSurf.get_rect()
    scoreRect.topleft = (Window_Width - 120, 10)
    screen.blit(scoreSurf, scoreRect)


def drawWorm(wormCoords):
    for coord in wormCoords:
        x = coord['x'] * Cell_Size
        y = coord['y'] * Cell_Size
        wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
        pygame.draw.rect(screen, DARKGreen, wormSegmentRect)
        wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)
        pygame.draw.rect(screen, Green, wormInnerSegmentRect)


def drawApple(coord):
    x = coord['x'] * Cell_Size
    y = coord['y'] * Cell_Size
    appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
    pygame.draw.rect(screen, Red, appleRect) # blit an apple


    random_color = (randint(0,255), randint(0,255), randint(0,255))
    random_pos = (randint(0,580), randint(0,580))
    random_radius = randint(1,4)
    pygame.draw.circle(screen, random_color, random_pos, random_radius)


##def drawGrid():
##    for x in range(0, Window_Width, Cell_Size): # draw vertical lines
##        pygame.draw.line(screen,DARKGRAY , (x, 0), (x, Window_Height))
##    for y in range(0, Window_Height, Cell_Size): # draw horizontal lines
##        pygame.draw.line(screen, DARKGRAY , (0, y), (Window_Width, y))


#def newlevel(x):
    #if x > 1 :

        #screen.fill(BGCOLOR1)
        #pygame.display.update()
        #Snakespeed= 12
        #runGame()


if __name__ == '__main__':
    #try:

    #except
    main()
    if x > 1:
        newlevel()
    # except SystemExit:
           # pass

这是我从网站上得到的另一个代码。你知道吗

try:
    from distutils.core import setup
    import py2exe, pygame
    from modulefinder import Module
    import glob, fnmatch
    import sys, os, shutil
    import operator
except ImportError, message:
    raise SystemExit,  "Unable to load module. %s" % message

#hack which fixes the pygame mixer and pygame font
origIsSystemDLL = py2exe.build_exe.isSystemDLL # save the orginal before we edit it
def isSystemDLL(pathname):
    # checks if the freetype and ogg dll files are being included
    if os.path.basename(pathname).lower() in ("libfreetype-6.dll", "libogg-0.dll","sdl_ttf.dll"): # "sdl_ttf.dll" added by arit.
            return 0
    return origIsSystemDLL(pathname) # return the orginal function
py2exe.build_exe.isSystemDLL = isSystemDLL # override the default function with this one

class pygame2exe(py2exe.build_exe.py2exe): #This hack make sure that pygame default font is copied: no need to modify code for specifying default font
    def copy_extensions(self, extensions):
        #Get pygame default font
        pygamedir = os.path.split(pygame.base.__file__)[0]
        pygame_default_font = os.path.join(pygamedir, pygame.font.get_default_font())

        #Add font to list of extension to be copied
        extensions.append(Module("pygame.font", pygame_default_font))
        py2exe.build_exe.py2exe.copy_extensions(self, extensions)

class BuildExe:
    def __init__(self):
        #Name of starting .py
        self.script = "game.py"

        #Name of program
        self.project_name = "MyApps"

        #Project url
        self.project_url = "about:none"

        #Version of program
        self.project_version = "0.0"

        #License of the program
        self.license = "MyApps License"

        #Auhor of program
        self.author_name = "Me"
        self.author_email = "example@example.com"
        self.copyright = "Copyright (c) 2009 Me."

        #Description
        self.project_description = "MyApps Description"

        #Icon file (None will use pygame default icon)
        self.icon_file = None

        #Extra files/dirs copied to game
        self.extra_datas = []

        #Extra/excludes python modules
        self.extra_modules = []
        self.exclude_modules = []

        #DLL Excludes
        self.exclude_dll = ['']
        #python scripts (strings) to be included, seperated by a comma
        self.extra_scripts = []

        #Zip file name (None will bundle files in exe instead of zip file)
        self.zipfile_name = None

        #Dist directory
        self.dist_dir ='dist'

    ## Code from DistUtils tutorial at http://wiki.python.org/moin/Distutils/Tutorial
    ## Originally borrowed from wxPython's setup and config files
    def opj(self, *args):
        path = os.path.join(*args)
        return os.path.normpath(path)

    def find_data_files(self, srcdir, *wildcards, **kw):
        # get a list of all files under the srcdir matching wildcards,
        # returned in a format to be used for install_data
        def walk_helper(arg, dirname, files):
            if '.svn' in dirname:
                return
            names = []
            lst, wildcards = arg
            for wc in wildcards:
                wc_name = self.opj(dirname, wc)
                for f in files:
                    filename = self.opj(dirname, f)

                    if fnmatch.fnmatch(filename, wc_name) and not os.path.isdir(filename):
                        names.append(filename)
            if names:
                lst.append( (dirname, names ) )

        file_list = []
        recursive = kw.get('recursive', True)
        if recursive:
            os.path.walk(srcdir, walk_helper, (file_list, wildcards))
        else:
            walk_helper((file_list, wildcards),
                        srcdir,
                        [os.path.basename(f) for f in glob.glob(self.opj(srcdir, '*'))])
        return file_list

    def run(self):
        if os.path.isdir(self.dist_dir): #Erase previous destination dir
            shutil.rmtree(self.dist_dir)

        #Use the default pygame icon, if none given
        if self.icon_file == None:
            path = os.path.split(pygame.__file__)[0]
            self.icon_file = os.path.join(path, 'pygame.ico')

        #List all data files to add
        extra_datas = []
        for data in self.extra_datas:
            if os.path.isdir(data):
                extra_datas.extend(self.find_data_files(data, '*'))
            else:
                extra_datas.append(('.', [data]))

        setup(
            cmdclass = {'py2exe': pygame2exe},
            version = self.project_version,
            description = self.project_description,
            name = self.project_name,
            url = self.project_url,
            author = self.author_name,
            author_email = self.author_email,
            license = self.license,

            # targets to build
            windows = [{
                'script': self.script,
                'icon_resources': [(0, self.icon_file)],
                'copyright': self.copyright
            }],
            options = {'py2exe': {'optimize': 2, 'bundle_files': 1, 'compressed': True, \
                                  'excludes': self.exclude_modules, 'packages': self.extra_modules, \
                                  'dll_excludes': self.exclude_dll,
                                  'includes': self.extra_scripts} },
            zipfile = self.zipfile_name,
            data_files = extra_datas,
            dist_dir = self.dist_dir
            )

        if os.path.isdir('build'): #Clean up build dir
            shutil.rmtree('build')

if __name__ == '__main__':
    if operator.lt(len(sys.argv), 2):
        sys.argv.append('py2exe')
    BuildExe().run() #Run generation
    raw_input("Press any key to continue")

Tags: thepathinselfeventsizeifdef

热门问题