製作小遊戲貪喫蛇即解決將python製作成exe

一.寫程序

# -*- coding:utf-8 -*-
import random
import pygame
import sys
from pygame.locals import *


pygame.init()
pygame.mixer.init()

#創建窗口
ScreenX = 800
ScreenY = 800
ScreenSize = (ScreenX, ScreenY)
Screen = pygame.display.set_mode(ScreenSize, 0, 32)
pygame.display.set_caption("楚楚的 small snake")

Difficulty = 11

#背景音樂
pygame.time.delay(100)#等待1秒讓mixer完成初始化

pygame.mixer.music.load('D://game//a.mp3')
pygame.mixer.music.play(-1, 0.0) #第一個參數爲播放次數,如果是-1表示循環播放,省略表示只播放1次。第二個參數和第三個參數分別表示播放的起始和結束位置。

# 蛇
class snake():
    def __init__(self):
        self.Direction = K_RIGHT
        self.Body = []
        self.AddBody()
        self.AddBody()

    def AddBody(self):
        NewAddLeft, NewAddTop = (0, 0)
        if self.Body:
            NewAddLeft, NewAddTop = (self.Body[0].left, self.Body[0].top)
        NewAddBody = pygame.Rect(NewAddLeft, NewAddTop, 20, 20)
        if self.Direction == K_LEFT:
            if NewAddBody.left == 0:
                NewAddBody.left = 780
            else:
                NewAddBody.left -= 20
        elif self.Direction == K_RIGHT:
            if NewAddBody.left == 780:
                NewAddBody.left = 0
            else:
                NewAddBody.left += 20
        elif self.Direction == K_UP:
            if NewAddBody.top == 0:
                NewAddBody.top = 780
            else:
                NewAddBody.top -= 20
        elif self.Direction == K_DOWN:
            if NewAddBody.top == 780:
                NewAddBody.top = 0
            else:
                NewAddBody.top += 20
        self.Body.insert(0, NewAddBody)

    def DelBody(self):
        self.Body.pop()

    def IsDie(self):
        if self.Body[0] in self.Body[1:]:
            return True
        return False

    def Move(self):
        self.AddBody()
        self.DelBody()

    def ChangeDirection(self, Curkey):
        LR = [pygame.K_LEFT, pygame.K_RIGHT]
        UD = [pygame.K_UP, pygame.K_DOWN]
        if Curkey in LR + UD:
            if (Curkey in LR) and (self.Direction in LR):
                return
            if (Curkey in UD) and (self.Direction in UD):
                return
            self.Direction = Curkey

# 食物
class food():
    def __init__(self):
        self.Obj = pygame.Rect(-20, 0, 20, 20)

    def Remove(self):
        self.Obj.x = -20

    def SendFood(self):
        if self.Obj.x == -20:
            AllPos = []
            for pos in range(20, ScreenX - 20, 20):
                AllPos.append(pos)

            self.Obj.left = random.choice(AllPos)
            self.Obj.top = random.choice(AllPos)


# 難度選擇及遊戲
def GameMain():
    global Difficulty
    FPSClock = pygame.time.Clock()
    Score = 0

    Snake = snake()
    Food = food()

    BackgroungImg = pygame.image.load('D://game//b.jpg').convert()
    DifficultyChoiceImg = pygame.image.load('D://game//a.jpg').convert()

    ChoiceHintFont = pygame.font.SysFont('arial',35)
    ChoiceFont = pygame.font.SysFont('arial', 130)
    # DifficultyChoice
    while True:
        IsChoice = False
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                if event.key == K_SPACE:
                    IsChoice = True
                    break
            if event.type == KEYDOWN:
                if event.key == K_UP:
                    Difficulty = Difficulty + 1
                elif event.key == K_DOWN:
                    if Difficulty > 1:
                        Difficulty = Difficulty - 1
        if IsChoice:
            break
        #按上下鍵選擇你稀罕我的程度(小蛇的速度)按空格鍵開始你奇妙的旅程
        Screen.blit(DifficultyChoiceImg, (0, 0))
        ChoiceHintSurface = ChoiceHintFont.render('choose a difficulty(the degree of missing) by direction key:', True, (0, 0, 0))
        Screen.blit(ChoiceHintSurface, (30, 60))
        ChoiceSurface = ChoiceFont.render(str(Difficulty), True, (0, 0, 0))
        Screen.blit(ChoiceSurface, (620, 150))
        EntranceHintSurface = ChoiceHintFont.render('Press Space (journey of love) to enter the game(my heart):', True, (0, 0, 0))
        Screen.blit(EntranceHintSurface, (20, 650))
        pygame.display.update()

    ScoreFont = pygame.font.SysFont('arial', 30)
    while True:     # main game loop
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                #ClickMusic.play()
                Snake.ChangeDirection(event.key)

        Screen.blit(BackgroungImg, (0, 0))
        pygame.draw.rect(Screen, (0, 0, 0), Food.Obj, 0)
        Snake.Move()

        for rect in Snake.Body:
            pygame.draw.rect(Screen, (0, 0, 0), rect, 0)

        if Snake.IsDie():
            return Score

        if Food.Obj == Snake.Body[0]:
            #EatFoodMusic.play()
            Score += Difficulty
            Food.Remove()
            Snake.AddBody()

        Food.SendFood()

        ScoreSurface = ScoreFont.render(str(Score), True, (0, 0, 0))
        Screen.blit(ScoreSurface, (0, 0))

        pygame.draw.rect(Screen, (0, 0, 0), Food.Obj, 0)

        pygame.display.update()
        FPSClock.tick(Difficulty)

# 遊戲結果
def GameResult(Score):
    if Score < 666 :
        GameResultBackgroundImg = pygame.image.load('D://game//c.jpg').convert()
        ScoreHintFont = pygame.font.SysFont('arial', 30)
        ScoreFont = pygame.font.SysFont('arial', 150)
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == KEYDOWN:
                    if event.key == K_SPACE:
                        return True

            Screen.blit(GameResultBackgroundImg, (0, 0))
            ChoiceHintSurface = ScoreHintFont.render('Your Score / the degree of your beauty is:', True, (0, 0, 0))
            Screen.blit(ChoiceHintSurface, (100, 50))
            ChoiceSurface = ScoreFont.render(str(Score), True, (0, 0, 0))
            Screen.blit(ChoiceSurface, (450, 100))
            EntranceHintSurface = ScoreHintFont.render('Press Space (journey of love) to restart the game', True,
                                                       (0, 0, 0))
            Screen.blit(EntranceHintSurface, (50, 650))
            pygame.display.update()

    else:
        GameResultBackgroundImg = pygame.image.load('D://game//e.jpg').convert()
        ScoreHintFont = pygame.font.SysFont('arial', 30)
        ScoreFont = pygame.font.SysFont('arial', 150)
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == KEYDOWN:
                    if event.key == K_SPACE:
                        return True

            Screen.blit(GameResultBackgroundImg, (0, 0))
            ChoiceHintSurface = ScoreHintFont.render('Your Score / the degree of your beauty is:', True, (0, 0, 0))
            Screen.blit(ChoiceHintSurface, (40,50))
            ChoiceSurface = ScoreFont.render(str(Score), True, (0, 0, 0))
            Screen.blit(ChoiceSurface, (600, 5))
            EntranceHintSurface = ScoreHintFont.render('chuchu,I miss you !!!', True, (0, 0, 0))
            Screen.blit(EntranceHintSurface, (50, 480))
            pygame.display.update()

if __name__ == '__main__':
    flag = True
    while flag:
        Score = GameMain()
        flag = GameResult(Score)

二,執行效果

三.將python打包成exe文件(複雜安裝)

1、環境


Windows 10 x64

Python 3.6.4

需要包
pyinstaller 3.3

pywin32

這裏需要注意!!!

2.pywin32安裝

在網上找很多使用pyinstaller庫將python程序打包成exe的方法都是需要python3.3版本以前的。而python3.6想要打包pyinstaller庫不支持,但是經過很多輪嘗試之後發現pyinstaller 3.3這個版本的包可以成功將python3.6版本的程序打包成exe。

還有一點需要注意,打包成exe都需要pywin32這個包,但是這個包很頑固,python2可以很好安裝,但是python3安裝時出現很多問題,需要下載本地安裝。但是pywin32本地安裝不像其它庫直接運行python setup.py install就行,pywin32這個包需要下載一個exe文件的安裝包然後點擊運行纔行。pywin32包連接:https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/ 下載時需注意自己python是32位的還是64位的,比如我的是python3.6 64位,我就下載這個:

python3.6無法安裝PYWIN32的問題

下載pywin32後,點擊運行,會發現出現下面的界面

很多同學到這個界面時,會報錯,提示檢測不到系統安裝了python3.6!!!,而且不能手動添加路徑。這個原因是你的python3.6不在系統的註冊表中,所以需要寫一個腳本把python加入到系統註冊表,腳本文件在這sys.py。簡單運行該sys.py程序後,就能添加python3.6到系統註冊表了。下一步就是安裝pywin32這個包了,還是像上面,運行該exe包,這時候就能出現上面那個能檢測到python目錄的界面,一直點擊下一步,完成。
 

import sys
from winreg import *
 
# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix
 
regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
    installpath, installpath, installpath
)
 
def RegisterPy():
    try:
        reg = OpenKey(HKEY_CURRENT_USER, regpath)
    except EnvironmentError as e:
        try:
            reg = CreateKey(HKEY_CURRENT_USER, regpath)
            SetValue(reg, installkey, REG_SZ, installpath)
            SetValue(reg, pythonkey, REG_SZ, pythonpath)
            CloseKey(reg)
        except:
            print ("*** Unable to register!")
            return
        print (" Python", version, "is now registered!")
        return
    if (QueryValue(reg, installkey) == installpath and
        QueryValue(reg, pythonkey) == pythonpath):
        CloseKey(reg)
        print ("=== Python", version, "is already registered!")
        return
    CloseKey(reg)
    print ("*** Unable to register!")
    print ("*** You probably have another Python installation!")
 
if __name__ == "__main__":
    RegisterPy() 

3.pyinstaller 3.3安裝


3.1.pip。

首先直接用pip安裝的pyinstaller是3.2.1版本(我這是17年11月份的情況,後來可能自動安裝更高版本),但是pyinstaller 3.2.1不能打包成exe,會出現很多溢出錯誤。

3.2.替換。

所以需要更新包,網上很多人說去github上下載最新版的pyinstaller,地址:https://github.com/pyinstaller/pyinstaller,下載後解壓安裝運行該包,然後將其中的PyInstaller 文件夾 複製到你安裝pyinstaller的相應目錄Python36\Lib\site-packages,進行替換。

四.將python打包成exe文件(簡易安裝)

環境:

python 3.6.4

pyinstaller 3.4

pywin32

上述包安裝後還是會出問題,跟新包 setuptools
pip install --upgrade  setuptools

步驟

1.準備我的chuchu_small_snake.py

注意:python裏面的文件目錄必須和壓縮成.exe文件的目錄一致(圖片必須放在相應的目錄下一起形成整個文件)

2,將chuchu_small_snake.py放到目錄下。 
3,在CMD命令行進入該目錄,並執行命令:

4.文件查看

一定要在指定目錄下(與代碼中音樂圖片目錄相同)查看有效!!!

pyinstaller -F chuchu_small_snake.py

執行效果如下: 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章