第一步:蛇形
运行IDLE,打开一个新的文本编辑窗口。输入以下的代码:
# -*- coding: UTF-8 -*-
# 1 - 引入模块
import pygame
from pygame.locals import *
import sys,random,time,math# 2 - 初始化pygame
pygame.init()
fpsClock = pygame.time.Clock()#时间
playSurface = pygame.display.set_mode((640,480))#创建pygame显示层
pygame.display.set_caption('Snake go!')#定义标题# 3 - 初始化颜色
blackColour = pygame.Color(0,0,0)
whileColour = pygame.Color(255,255,255)
lightColour = pygame.Color(220,220,220)# 4 - 初始化变量
snakePosition = [100,100]#蛇头位置
snakeSegments = [[100,100],[80,100],[60,100]] #初始长度为3个单位 # 5 - 定义函数# 6 - 保持循环通过
while 1:# 7 - 将蛇头的位置加入列表中snakeSegments.insert(0,list(snakePosition))# 8 - 绘制py显示层playSurface.fill(blackColour)for position in snakeSegments[1:]:#蛇身为白色pygame.draw.rect(playSurface,whileColour,Rect(position[0],position[1],20,20))#蛇头为灰色pygame.draw.rect(playSurface,lightColour,Rect(snakePosition[0],snakePosition[1],20,20)) # 9 - 刷新py显示层pygame.display.flip()# 10 - 循环事件for event in pygame.event.get():#检测按键等py事件if event.type == QUIT:pygame.quit()sys.exit()
把文件保存到你的游戏文件夹里,把它命名为 game.py 。我们现在看看这段代码做了什么:
- 导入pygame库,这一步能让你使用库里提供的功能
- 初始化pygame,设置展示窗口
- 设置颜色
- 初始化变量
- 定义函数部分(暂时空着)
- 不停地循环执行接下来的部分
- 将蛇头的位置加入列表
- 在给屏幕画任何东西之前用黑色进行填充,画蛇形
- 更新屏幕
- 检查一些新的事件,如果有退出命令,则终止程序的执行。
在运行这段代码后,你会看到一下的画面:
第二步:让蛇移动
比如让蛇能够随着按键移动。
在#4 加上以下代码,定义初始方向:
direction = 'right' #初始方向
changeDirection = direction
把以下代码加入到 game.py 里#10后面:
elif event.type == KEYDOWN:#判断键盘事件if event.key == K_RIGHT or event.key == ord('d'):changeDirection = 'right'if event.key == K_LEFT or event.key == ord('a'):changeDirection = 'left'if event.key == K_UP or event.key == ord('w'):changeDirection = 'up'if event.key == K_DOWN or event.key == ord('s'):changeDirection = 'down'if event.key == K_ESCAPE: #按esc退出游戏pygame.event.post(pygame.event.Event(QUIT))
贪吃蛇运动有一个特点:不能反方向运动。所以我们需要加入限制条件。在for循环之外的下面加以下代码:
#该游戏比较特殊,不能反方向运动if changeDirection == 'right' and not direction == 'left':direction = changeDirectionif changeDirection == 'left' and not direction == 'right':direction = changeDirectionif changeDirection == 'up' and not direction == 'down':direction = changeDirectionif changeDirection == 'down' and not direction == 'up':direction = changeDirection#根据方向移动蛇头坐标if direction == 'right':snakePosition[0] += 20if direction == 'left':snakePosition[0] -= 20if direction == 'up':snakePosition[1] -= 20if direction == 'down':snakePosition[1] += 20snakeSegments.pop() #每次讲最后一单位蛇身踢出列表fpsClock.tick(2) #运动速度
运行这个游戏,那么你应该会看到一下的画面。试着按WASD,耶!好使了!
第三步:显示食物
在#3加上:
redColour = pygame.Color(255,0,0)
在#4加上
raspberrySpawned = 1 #食物个数
raspberryPosition = [300,300] #食物位置
在#8加上
#食物为红色pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0],raspberryPosition[1],20,20))
运行游戏,可见:
第四步:蛇吃食物
在#4 加上:
score = 0 #初始分数
将#10倒数第二行(具体视自己的情况而定)的snakeSegments.pop()改成:
#判断是否吃到树莓if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:raspberrySpawned = 0else:snakeSegments.pop() #每次讲最后一单位蛇身踢出列表#如果吃掉树莓,重新生成树莓if raspberrySpawned == 0:x = random.randrange(1,32)y = random.randrange(1,24)raspberryPosition = [int(x*20),int(y*20)]raspberrySpawned = 1score +=1
运行游戏,可正常吃食物,并增长蛇身的长度
第五步:碰撞墙壁和吃自己游戏结束
在#3定义颜色,结束时,显示的字体颜色:
greyColour = pygame.Color(155,155,155)
在#5加上函数,代码如下:
def gameOver(playSurface,score):#显示game over并定义字体以及大小gameOverFont = pygame.font.Font(None,180)gameOverSurf = gameOverFont.render('game over',True,greyColour)gameOverRect = gameOverSurf.get_rect()playSurface.blit(gameOverSurf,gameOverRect)#显示分数并定义字体和大小scoreFont = pygame.font.Font(None,48)scoreSurf = scoreFont.render('SCORE:'+str(score),True,greyColour)scoreRect = scoreSurf.get_rect()playSurface.blit(scoreSurf,scoreRect)#刷新显示界面pygame.display.flip()#休眠5s 自动关闭time.sleep(10)pygame.quit()sys.exit()
在#10 while的循环里的最后,加上:
#判断是否死亡if snakePosition[0] > 620 or snakePosition[0] < 0:#左右gameOver(playSurface,score)if snakePosition[1] > 460 or snakePosition[1] < 0:#上下gameOver(playSurface,score)for snakeBody in snakeSegments[1:]:#蛇身if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:gameOver(playSurface,score)
运行,如图所示,贪吃蛇成功