一.写程序
# -*- 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
执行效果如下: