用Python写简单游戏的一般步骤
前言
自己用python写过几个简单的游戏后,发现对于已经写过的这些游戏而言,其创作流程都有一些相通性,自此小结一下用python写游戏的一般步骤。
python写游戏
一、python写游戏的关键是什么?
从我看来,目前python仍然是写游戏的主流语言,其拥有功能强大的pygame库。pygame库也是用python写游戏最关键的一环。pygame库的下载可以在windows的控制台下载,当然也有其他的很多方法,百度上有很多,这里就不赘述了。
下边是我模拟《球球大作战》写的一个及其简单且丑陋的脚本,但是比较有代表意义,拿出来做一下解释说明。
二、python写游戏的步骤
1.初始化游戏界面
代码如下(示例):
pygame.init()
DISPLAY = pygame.display.set_mode((640, 480)) //初始化游戏界面的大小
pygame.display.set_caption('Ball-Ball') //给游戏起个标题
FPSLOCK = pygame.time.Clock() //设置时钟,用来控制游戏进度
BASICFONT = pygame.font.SysFont('arial', 80) //设置字体,第一个参数是字体名称,第二个是字体大小
directions = [1, 2, 3, 4] //定义方向集合,可以视具体情况增删
# 定义颜色
Black = pygame.Color(0, 0, 0) //颜色需要自己定义
White = pygame.Color(255, 255, 255)
Red = pygame.Color(255, 0, 0)
Grey = pygame.Color(150, 150, 150)
2.定义PC和NPC
通过类及类内的函数来定义player和NPC,包括但不限于初始化函数、绘制函数、更新位置函数等等。
代码如下(示例):
#定义玩家控制对象
class Player:
def __init__(self, x, y, radius):
self.radius = radius //半径
self.x = x //横坐标
self.y = y //纵坐标
# 画有操控小球
def drawControlBall(self):
# for i in control_ball_pos:
pygame.draw.circle(DISPLAY, White, (control_ball.x, control_ball.y), control_ball.radius) //操控对象为小球
# 定义无操控小球
class Ball:
def __init__(self, x, y, radius, direct):
self.radius = radius
self.x = x
self.y = y
self.direct = direct //方向(本文只实现了NPC单方向运动的功能)
def drawUncontrolBall(self):
pygame.draw.circle(DISPLAY, Red, (self.x, self.y), self.radius)
if self.direct == 1:
self.y -= 1
elif self.direct == 2:
self.y += 1
elif self.direct == 3:
self.x -= 1
elif self.direct == 4:
self.x += 1
def update(self): //每次被吃掉后需要更新位置
self.radius = random.randrange(5, 40)
self.x = random.randrange(self.radius, 640 - self.radius)
self.y = random.randrange(self.radius, 480 - self.radius)
self.direct = random.choice(directions)
3.定义一些函数
在类外定义一些必要函数,比如显示分数的函数,或者Gameover函数。
代码如下(示例):
# 显示分数
def drawScore(score):
# 设置分数的显示颜色
score_Surf = BASICFONT.render('%s' % (score), True, Grey)
# 设置分数的位置
score_Rect = score_Surf.get_rect()
score_Rect.midtop = (320, 0)
# 绑定以上设置到句柄
DISPLAY.blit(score_Surf, score_Rect)
# 设置游戏结束
def GameOver():
# 设置GameOver的显示颜色
GameOver_Surf = BASICFONT.render('Game Over!', True, Red)
# 设置GameOver的位置
GameOver_Rect = GameOver_Surf.get_rect()
GameOver_Rect.midtop = (320, 240)
# 绑定以上设置到句柄
DISPLAY.blit(GameOver_Surf, GameOver_Rect)
pygame.display.flip()
# 等待5秒
time.sleep(5)
# 退出游戏
pygame.quit()
# 退出程序
sys.exit()
4.定义主函数,使得游戏可以运作
我是通过while循环来使游戏可以运作起来,不然运行之后就会闪退。
代码如下(示例):
game_flag = True
score = 0
control_ball = Player(200, 100, 20) //初始化玩家
b1 = Ball(100, 100, 10, 2) //初始化一个NPC
b2 = Ball(300, 200, 40, 3) //初始化第二个NPC
balls = [b1, b2]
direction = "Right"
while game_flag:
DISPLAY.fill(Black) //游戏底色为黑色
#绘制出player和npc
control_ball.drawControlBall()
b1.drawUncontrolBall()
b2.drawUncontrolBall()
drawScore(score)
#更新整个待显示的Surface对象到屏幕上
pygame.display.flip()
#控制游戏速度
FPSLOCK.tick(7)
for event in pygame.event.get(): # 监听用户的操作
if event.type == QUIT:
# 接收到退出事件后,退出程序
pygame.quit()
sys.exit()
# 判断键盘事件,用 方向键 或 wsad 来表示上下左右
elif event.type == KEYDOWN: # KEYDOWM 用于检查用户是否按了键盘
if event.key == K_UP or event.key == K_w: # and direction != "DOWN":
direction = "UP"
if event.key == K_DOWN or event.key == K_s: # and direction != "UP":
direction = "DOWN"
if event.key == K_LEFT or event.key == K_a: # and direction != "RIGHT":
direction = "LEFT"
if event.key == K_RIGHT or event.key == K_d: # and direction != "LEFT":
direction = "RIGHT"
'''if event.key == K_ESCAPE:
game_flag = False'''
if direction == "LEFT":
control_ball.x -= 10
if direction == "RIGHT":
control_ball.x += 10
if direction == "UP":
control_ball.y -= 10
if direction == "DOWN":
control_ball.y += 10
for ball in balls:
if (control_ball.x - ball.x) ** 2 + (control_ball.y - ball.y) ** 2 <= (ball.radius + control_ball.radius) ** 2: //俩球相接触,遵循大球吃小球
if control_ball.radius > ball.radius:
score = score + 1
control_ball.radius += 1 # ball.radius
ball.update()
elif control_ball.radius <= ball.radius:
GameOver()
#玩家超出游戏界面,则游戏结束
if control_ball.x < 0 or control_ball.x > 640:
GameOver()
if control_ball.y < 0 or control_ball.y > 480:
GameOver()
三、封装
写完游戏后,但是你怎么让别人在别人的电脑上也能运行呢?当然你可以直接把py文件发给你的小伙伴,但是对方要想运行,还必须要下载游戏需要的功能包,非常的不方便,这就需要我们对写好的py文件进行封装。
1.安装封装工具
首先在控制台下载封装文件pyinstaller:
pip3 install pyinstaller
2.生成exe文件
首先在控制台切换到py脚本所在的文件夹***(注:“cd+空格+文件位置”可以跳转到目标文件路径下,“d:”可以跳转到D盘)***,然后执行下面代码:
pyinstaller -F -w "py脚本名称".py
执行完毕之后,会生成几个文件夹,其中在dist文件夹里就会生成exe文件。
其中’-F’参数表示覆盖打包,这样在打包时,不管我们打包几次,都是最新的。
'-w’参数可以避免运行以后显示黑洞洞的控制台。
如果想要修改exe文件的图标,可以准备一个ico格式的图标文件,然后执行下面代码:
pyinstaller -F -w -i '图标文件名称'.ico '脚本名称'.py
3.把exe文件拖到和py平级的目录
4.运行exe文件
总结
我认为按照本文的这几个步骤,可以写出来大部分的简单游戏。因为本文是这个简单游戏的完整源码,所以读者如果有需要,可以复制本文的源码到python的IDE中尝试。