从零开始实现贪吃蛇(完整代码)

前言

本文将分为三个部分来讲解贪吃蛇的实现,分为贪吃蛇开始前的游戏画面、游戏中画面、游戏结束画面,那我们开始吧!

游戏开始界面

游戏在开始前都会有一个的画面,一般而言是提供选择,如童年回忆《坦克大战》,在开始前会提供一个画面供玩家选择,单人模式或者双人模式,而我们的贪吃蛇可以用动态的画面,当玩家按下键盘上除了Esc之外的键就会直接进入游戏中。下面我们开始来讲解代码吧。

def showStartScreen():  
    titleFont = pygame.font.Font('freesansbold.ttf', 100)  
    titleSurf1 = titleFont.render('strive', True, WHITE, DARKGREEN)  
    titleSurf2 = titleFont.render('strive', True, GREEN)  
    degrees1 = 0  
    degrees2 = 0  
    while True:  
        DISPLAYSURF.fill(BGCOLOR)  
        rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)  
        rotatedRect1 = rotatedSurf1.get_rect()  
        rotatedRect1.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)  
        DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)  
        rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2)  
        rotatedRect2 = rotatedSurf2.get_rect()  
        rotatedRect2.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)  
        DISPLAYSURF.blit(rotatedSurf2, rotatedRect2)    
        if checkForKeyPress():  
            pygame.event.get()   
            return  
        pygame.display.update()  
        FPSCLOCK.tick(FPS)  
        degrees1 += 3  
        degrees2 += 7 

首先我们先设置字体和字体大小(titleFont),,然后在渲染的时候设置字体的颜色和背景,如果没有设置背景颜色,默认为黑色。最后degrees1和degrees2用于设置旋转的角度。

titleFont = pygame.font.Font('freesansbold.ttf', 100)  
titleSurf1 = titleFont.render('Wormy!', True, WHITE, DARKGREEN)  
titleSurf2 = titleFont.render('Wormy!', True, GREEN)  
degrees1 = 0  
degrees2 = 0 

同样的我们先将背景色填充为黑色,至于为什么这样做,大家可以自己把这行代码注释掉,然后运行看看效果。pygame中旋转图像的方法,pygame.transform.rotate(surface, angle),我们需要传入一个surface和旋转的角度,接着获取它的矩形对象,让它居中显示,center表示矩形的中心坐标,最后将它绘制到屏幕上,下面的几行代码效果是相同的就不再讲了。

DISPLAYSURF.fill(BGCOLOR)  
rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)  
rotatedRect1 = rotatedSurf1.get_rect()  
rotatedRect1.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)  
DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)  

checkForKeyPress()这是我们自己写的一个函数方法,具体的功能是表示用户是否按下键盘,如果按了将会进入游戏。pygame.display.update()更新游戏画面,degress1和degress2累加,旋转的角度一步一步增大。

if checkForKeyPress():  
            pygame.event.get()   
            return  
pygame.display.update()  
FPSCLOCK.tick(FPS)  # 设置帧数
degrees1 += 3  
degrees2 += 7 

让我们来看看效果图
从零开始实现贪吃蛇(完整代码)_第1张图片

我们也可以做一个选择界面,可以是单人游戏或者双人游戏,当然我们这就还是选择第一种,下面开始展示吧。

import pygame  
import sys  
pygame.init()  

DISPLAYSURF = pygame.display.set_mode((640, 480))  
DARKGREEN = (0, 155, 0)  
titleFont = pygame.font.Font('freesansbold.ttf', 100)  
titleFont1 = pygame.font.Font('freesansbold.ttf', 20)  
titleSurf = titleFont.render('strive', True, (255, 255, 255), DARKGREEN)  
rect_titleSurf = titleSurf.get_rect()  
rect_titleSurf.center = 320, 120  
one_game = titleFont1.render('Single player game', True, DARKGREEN)  
rect_one = one_game.get_rect()  
rect_one.topleft = 240, 240  
double_game = titleFont1.render('Two player game', True, DARKGREEN)  
rect_double = double_game.get_rect()  
rect_double.topleft = 240, 270  
flag = 1  
  
while True:  
    DISPLAYSURF.fill((0, 0, 0))  
    for event in pygame.event.get():  
        if event.type == pygame.QUIT:  
            pygame.quit()  
            sys.exit()  
    get_key = pygame.key.get_pressed()  
    if get_key[pygame.K_w] or get_key[pygame.K_UP]:  
        flag = 1  
    elif get_key[pygame.K_s] or get_key[pygame.K_DOWN]:  
        flag = 2  
    elif get_key[pygame.K_j]:  
        print('开始游戏了!')  
    if flag == 1:  
        select_cursor = pygame.draw.circle(DISPLAYSURF, DARKGREEN, [220, 250], 10, 0)  
    elif flag == 2:  
        select_cursor = pygame.draw.circle(DISPLAYSURF, DARKGREEN, [220, 280], 10, 0)  
  
    DISPLAYSURF.blit(one_game, rect_one)  
    DISPLAYSURF.blit(double_game, rect_double)  
    DISPLAYSURF.blit(titleSurf, rect_titleSurf)  
    pygame.display.update()

运行效果图
从零开始实现贪吃蛇(完整代码)_第2张图片

游戏部分

蛇移动(核心)

下面代码是关于蛇的移动以及蛇的绘画(可单独运行)。因为我们要画格子,而格子要和蛇相契合,换句话说,每一个格子的大小和组成蛇的格子大小是相同的。所以这里按比例缩小,除以20,方便一些。

import pygame  
import sys  
import random  
from pygame.locals import *  
  
pygame.init()  
  
FPS = 15  # 帧
WINDOWWIDTH = 640   # 高
WINDOWHEIGHT = 480  # 宽
CELLSIZE = 20  # 蛇宽高
  
# 按比例缩小  都除以20 
CELLWIDTH = int(WINDOWWIDTH / CELLSIZE)  
CELLHEIGHT = int(WINDOWHEIGHT / CELLSIZE)  
  
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))  
  
FPSCLOCK = pygame.time.Clock()  

# 方向
UP = 'up'  
DOWN = 'down'  
LEFT = 'left'  
RIGHT = 'right'  
  
# 蛇的头部索引  
HEAD = 0  
  
BLACK = (0, 0, 0)  
# 蛇身  
GREEN = (0, 255, 0)  
DARKGREEN = (0, 155, 0)  
# 格子颜色  
DARKGRAY = (40, 40, 40)  
  
BGCOLOR = BLACK  
  
  
# 画格子  
def drawGrid():  
    # 先画竖线  
    for x in range(0, WINDOWWIDTH, CELLSIZE):  
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, WINDOWHEIGHT))  
    # 再画横线  
    for y in range(0, WINDOWHEIGHT, CELLSIZE):  
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (WINDOWWIDTH, y))  
  
  
# 画蛇  
def drawWorm(wormCoords):  
    for coord in wormCoords:  
        x = coord['x'] * CELLSIZE  # 20  
        y = coord['y'] * CELLSIZE  
        wormSegmentRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)  
        pygame.draw.rect(DISPLAYSURF, DARKGREEN, wormSegmentRect)  
        # 在画小正方形,加深蛇身颜色  
        wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, CELLSIZE - 8, CELLSIZE - 8)  
        pygame.draw.rect(DISPLAYSURF, GREEN, wormInnerSegmentRect)  
  
  
# 开始游戏  
def runGame():  
    # 随机出现位置  
    startx = random.randint(5, CELLWIDTH - 6)  
    starty = random.randint(5, CELLHEIGHT - 6)  
    # 蛇身体  
    wormCoords = [{'x': startx, 'y': starty},  
                  {'x': startx - 1, 'y': starty},  
                  {'x': startx - 2, 'y': starty}]  
    # 默认方向为右  
    direction = RIGHT  
  
    while True:  
        for event in pygame.event.get():  
            if event.type == QUIT:  
                pygame.quit()  
                sys.exit()  
            elif event.type == KEYDOWN:  
                if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:  
                    direction = LEFT  
                elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:  
                    direction = RIGHT  
                elif (event.key == K_UP or event.key == K_w) and direction != DOWN:  
                    direction = UP  
                elif (event.key == K_DOWN or event.key == K_s) and direction != UP:  
                    direction = DOWN  
                elif event.key == K_ESCAPE:  
                    pygame.quit()  
                    sys.exit()  
        # 出界就挂了  
        if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == CELLWIDTH or wormCoords[HEAD]['y'] == -1 or \  
                wormCoords[HEAD]['y'] == CELLHEIGHT:  
            return  
            # 撞到自己的身体也挂了  
        for wormBody in wormCoords[1:]:  
            if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:  
                return  
  
        # 删除最后一个矩形  
        del wormCoords[-1]  
  
        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)  
        DISPLAYSURF.fill(BGCOLOR)  
        # 画格子  
        drawGrid()  
        # 画蛇  
        drawWorm(wormCoords)  
  
        pygame.display.update()  
        FPSCLOCK.tick(FPS)  
  
  
if __name__ == '__main__':  
    runGame()

首先我们先随机蛇头出现的位置,然后根据蛇头的位置,x分别-1,-2得到完整蛇坐标,注意这里的1代表是20像素,2就是40像素。默认前进方向是向右。

# 随机出现位置  
startx = random.randint(5, CELLWIDTH - 6)  
starty = random.randint(5, CELLHEIGHT - 6)  
# 蛇身+蛇头  
wormCoords = [{'x': startx, 'y': starty},  
			  {'x': startx - 1, 'y': starty},  
			  {'x': startx - 2, 'y': starty}]  
# 默认方向为右  
direction = RIGHT  

又是这熟悉的结构,pygame.event.get()获取事件,当玩家点击右上角的X时,触发关闭事件(QUIT),我们在下面写的逻辑会退出游戏。我们按下键盘会触发键盘事件(KEYDOWN),然后具体判断按下哪个键,那些键对应着控制蛇移动。蛇向右移动时,是不能向左移动,即反方向移动,大家可以把and direction != RIGHT类似的代码去掉,看看会产生怎们样的效果,实践是检验真理的唯一标准。

while True:  
        for event in pygame.event.get():  
            # 退出游戏
            if event.type == QUIT:  
                pygame.quit()  
                sys.exit()  
            # 获取键盘事件
            elif event.type == KEYDOWN:  
                if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:  
                    direction = LEFT  
                elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:  
                    direction = RIGHT  
                elif (event.key == K_UP or event.key == K_w) and direction != DOWN:  
                    direction = UP  
                elif (event.key == K_DOWN or event.key == K_s) and direction != UP:  
                    direction = DOWN  
                elif event.key == K_ESCAPE:  
                    pygame.quit()  
                    sys.exit() 

这份代码是对蛇移动的限制,如果蛇移动超出了屏幕,游戏就会结束,同样碰到自己的身体也会结束游戏。

# 出界就挂了  
if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == CELLWIDTH or wormCoords[HEAD]['y'] == -1 or \  
		wormCoords[HEAD]['y'] == CELLHEIGHT:  
	return  
	# 撞到自己的身体也挂了  
for wormBody in wormCoords[1:]:  
	if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:  
	return  

我们删除wormCoords中最后一个字典,在wormCoords中第一位置插入新的字典,一删一加从而达到蛇移动的效果。

 # 删除最后一个矩形  
del wormCoords[-1]  

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)  

画蛇分为两步,第一步将蛇画好,第二步优化,加深蛇的颜色,这样看起来效果更佳。

# 画蛇  
def drawWorm(wormCoords):  
    for coord in wormCoords:  
        x = coord['x'] * CELLSIZE  # 20  
        y = coord['y'] * CELLSIZE  
        wormSegmentRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)  
        pygame.draw.rect(DISPLAYSURF, DARKGREEN, wormSegmentRect)  
        # 在画小正方形,加深蛇身颜色  
        wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, CELLSIZE - 8, CELLSIZE - 8)  
        pygame.draw.rect(DISPLAYSURF, GREEN, wormInnerSegmentRect)

我们根据宽高,每隔20像素画一条线,格子就画完了。

# 画格子  
def drawGrid():  
    # 先画竖线  
    for x in range(0, WINDOWWIDTH, CELLSIZE):  
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, WINDOWHEIGHT))  
    # 再画横线  
    for y in range(0, WINDOWHEIGHT, CELLSIZE):  
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (WINDOWWIDTH, y)) 

画食物

随机出现食物,蛇吃到食物身体就会增长一格,我们在删除wormCoords最后一个字典的时候,蛇碰到食物就不删除,相当于蛇增长了一格。

import pygame  
import sys  
import random  
from pygame.locals import *  
  
pygame.init()  
  
WINDOWWIDTH = 640  
WINDOWHEIGHT = 480  
CELLSIZE = 20  
CELLWIDTH = int(WINDOWWIDTH / CELLSIZE)  
CELLHEIGHT = int(WINDOWHEIGHT / CELLSIZE)  
  
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))  
  
RED = (255, 0, 0)  
  
  
# 画食物  
def drawApple(coord):  
    x = coord['x'] * CELLSIZE  
    y = coord['y'] * CELLSIZE  
    appleRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)  
    pygame.draw.rect(DISPLAYSURF, RED, appleRect)  
  
  
cord = {'x': random.randint(0, CELLWIDTH - 1), 'y': random.randint(0, CELLHEIGHT - 1)}  
  
while True:  
    for event in pygame.event.get():  
        if event.type == QUIT:  
            pygame.quit()  
            sys.exit()  
    drawApple(cord)  
    pygame.display.update()

画分数

画分数,根据玩家吃到多少食物来算分,一个食物等于一分。

import pygame  
import sys  
import random  
from pygame.locals import *  
  
pygame.init()  
  
WINDOWWIDTH = 640  
WINDOWHEIGHT = 480  
  
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))  
  
WHITE = (255, 255, 255)  
  
  
# 画食物  
def drawScore(score):  
    BASICFONT = pygame.font.Font('freesansbold.ttf', 18)  
    scoreSurf = BASICFONT.render('Score: %s' % (score), True, WHITE)  
    scoreRect = scoreSurf.get_rect()  
    scoreRect.topleft = (WINDOWWIDTH - 120, 10)  
    DISPLAYSURF.blit(scoreSurf, scoreRect)  
  
  
while True:  
    for event in pygame.event.get():  
        if event.type == QUIT:  
            pygame.quit()  
            sys.exit()  
    drawScore(5)  
    pygame.display.update()

游戏结束画面

当蛇超出屏幕或者碰到自己身体时,游戏就结束了。

import pygame  
import sys  
import random  
from pygame.locals import *  
  
pygame.init()  
  
WINDOWWIDTH = 640  
WINDOWHEIGHT = 480  
  
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))  
  
WHITE = (255, 255, 255)  
  
  
def showGameOverScreen():  
    gameOverFont = pygame.font.Font('freesansbold.ttf', 150)  
    gameSurf = gameOverFont.render('Game', True, WHITE)  
    overSurf = gameOverFont.render('Over', True, WHITE)  
    gameRect = gameSurf.get_rect()  
    overRect = overSurf.get_rect()  
    gameRect.midtop = (WINDOWWIDTH / 2, 10)  
    overRect.midtop = (WINDOWWIDTH / 2, gameRect.height + 10 + 25)  
  
    DISPLAYSURF.blit(gameSurf, gameRect)  
    DISPLAYSURF.blit(overSurf, overRect)  
    pygame.display.update()  

     
  
while True:  
    for event in pygame.event.get():  
        if event.type == QUIT:  
            pygame.quit()  
            sys.exit()  
    showGameOverScreen()  
    pygame.display.update()

完整代码

import random  
import pygame  
import sys  
from pygame.locals import *  
  
'''游戏开始前动画  
   蛇的移速  
'''  
  
FPS = 15  
WINDOWWIDTH = 640  
WINDOWHEIGHT = 480  
CELLSIZE = 20  
# assert 如果为真就执行 为假报错  
# # 整数倍 格子  
assert WINDOWWIDTH % CELLSIZE == 0, "Window width must be a multiple of cell size."  
assert WINDOWHEIGHT % CELLSIZE == 0, "Window height must be a multiple of cell size."  
CELLWIDTH = int(WINDOWWIDTH / CELLSIZE)  
CELLHEIGHT = int(WINDOWHEIGHT / CELLSIZE)  
  
WHITE = (255, 255, 255)  
BLACK = (0, 0, 0)  
RED = (255, 0, 0)  
GREEN = (0, 255, 0)  
DARKGREEN = (0, 155, 0)  
DARKGRAY = (40, 40, 40)  
BGCOLOR = BLACK  
  
UP = 'up'  
DOWN = 'down'  
LEFT = 'left'  
RIGHT = 'right'  
  
# 蛇的头部索引  
HEAD = 0  
  
  
def main():  
    global FPSCLOCK, DISPLAYSURF, BASICFONT  
  
    pygame.init()  
    FPSCLOCK = pygame.time.Clock()  
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))  
    BASICFONT = pygame.font.Font('freesansbold.ttf', 18)  
    pygame.display.set_caption('贪吃蛇')  
  
    showStartScreen()  
    while True:  
        runGame()  
        showGameOverScreen()  
  
def runGame():  
    # 随机蛇头  
    startx = random.randint(5, CELLWIDTH - 6)  
    starty = random.randint(5, CELLHEIGHT - 6)  
    # 初始3个  
    wormCoords = [{'x': startx, 'y': starty},  
                  {'x': startx - 1, 'y': starty},  
                  {'x': startx - 2, 'y': starty}]  
    # 方向为右  
    direction = RIGHT  
  
    # 食物  
    apple = getRandomLocation()  
  
    while True:  
        for event in pygame.event.get():  
            if event.type == QUIT:  
                terminate()  
            elif event.type == KEYDOWN:  
                if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:  
                    direction = LEFT  
                elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:  
                    direction = RIGHT  
                elif (event.key == K_UP or event.key == K_w) and direction != DOWN:  
                    direction = UP  
                elif (event.key == K_DOWN or event.key == K_s) and direction != UP:  
                    direction = DOWN  
                elif event.key == K_ESCAPE:  
                    terminate()  
  
        if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == CELLWIDTH or wormCoords[HEAD]['y'] == -1 or \  
                wormCoords[HEAD]['y'] == CELLHEIGHT:  
            return  
        # 撞到自己的身体也挂了  
        for wormBody in wormCoords[1:]:  
            if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:  
                return  
  
        if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:  
            apple = getRandomLocation()  
        else:  
            # 删除最后一个  
            del wormCoords[-1]  
  
        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)  
        DISPLAYSURF.fill(BGCOLOR)  
        # 画格子  
        drawGrid()  
        # 画蛇  
        drawWorm(wormCoords)  
        # 画食物  
        drawApple(apple)  
        # 画分数  
        drawScore(len(wormCoords) - 3)  
        pygame.display.update()  
        FPSCLOCK.tick(FPS)  
  
# 绘制底部提示消息  
def drawPressKeyMsg():  
    pressKeySurf = BASICFONT.render('Press a key to play.', True, DARKGRAY)  
    pressKeyRect = pressKeySurf.get_rect()  
    pressKeyRect.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT - 30)  
    DISPLAYSURF.blit(pressKeySurf, pressKeyRect)  
  
# 检查按键  
def checkForKeyPress():  
    # QUIT 事件类型 指定获取事件类型  
    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:  
        print(keyUpEvents[0])  
        #   
        print(keyUpEvents[0].key)  
        # 27  
        terminate()  
    return keyUpEvents[0].key  
  
# 开始游戏动画  
def showStartScreen():  
    titleFont = pygame.font.Font('freesansbold.ttf', 100)  
    # render(内容,是否抗锯齿,字体颜色,字体背景颜色)  
    # 白字 绿背景  
    titleSurf1 = titleFont.render('strive', True, WHITE, DARKGREEN)  
    # 绿字 无背景  
    titleSurf2 = titleFont.render('strive', True, GREEN)  
    degrees1 = 0  
    degrees2 = 0  
    while True:  
        DISPLAYSURF.fill(BGCOLOR)  
        # 第一个  
        rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)  
        rotatedRect1 = rotatedSurf1.get_rect()  
        rotatedRect1.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)  
        DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)  
        # 第二个  
        # pygame.transform.rotate(surface, angle) 旋转图片  
        rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2)  
        rotatedRect2 = rotatedSurf2.get_rect()  
        rotatedRect2.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)  
        DISPLAYSURF.blit(rotatedSurf2, rotatedRect2)  
  
        # 绘制底部提示消息  
        # drawPressKeyMsg()  
  
        # 检查键盘事件  
        if checkForKeyPress():  
            # 清除之前事件影响  
            pygame.event.get()  # 清除事件队列 从队列中获取所有事件并删除  
            return  
        pygame.display.update()  
        FPSCLOCK.tick(FPS)  
        degrees1 += 3  # 每帧旋转3度  
        degrees2 += 7  # rotate by 7 degrees each frame  
  
# 关闭  
def terminate():  
    pygame.quit()  
    sys.exit()  
  
# 随机食物  
def getRandomLocation():  
    return {'x': random.randint(0, CELLWIDTH - 1), 'y': random.randint(0, CELLHEIGHT - 1)}  
  
# 结束游戏画面  
def showGameOverScreen():  
    gameOverFont = pygame.font.Font('freesansbold.ttf', 150)  
    gameSurf = gameOverFont.render('Game', True, WHITE)  
    overSurf = gameOverFont.render('Over', True, WHITE)  
    gameRect = gameSurf.get_rect()  
    overRect = overSurf.get_rect()  
    gameRect.midtop = (WINDOWWIDTH / 2, 10)  
    overRect.midtop = (WINDOWWIDTH / 2, gameRect.height + 10 + 25)  
  
    DISPLAYSURF.blit(gameSurf, gameRect)  
    DISPLAYSURF.blit(overSurf, overRect)  
    drawPressKeyMsg()  
    pygame.display.update()  
    # 等待事件 wait    
    pygame.time.wait(500)  
    checkForKeyPress()  
  
    while True:  
        if checkForKeyPress():  
            pygame.event.get()  
            return  
  
# 画分数  
def drawScore(score):  
    scoreSurf = BASICFONT.render('Score: %s' % (score), True, WHITE)  
    scoreRect = scoreSurf.get_rect()  
    scoreRect.topleft = (WINDOWWIDTH - 120, 10)  
    DISPLAYSURF.blit(scoreSurf, scoreRect)  
  
# 画蛇  
def drawWorm(wormCoords):  
    for coord in wormCoords:  
        x = coord['x'] * CELLSIZE # 20  
        y = coord['y'] * CELLSIZE  
        wormSegmentRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)  
        pygame.draw.rect(DISPLAYSURF, DARKGREEN, wormSegmentRect)  
        wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, CELLSIZE - 8, CELLSIZE - 8)  
        pygame.draw.rect(DISPLAYSURF, GREEN, wormInnerSegmentRect)  
  
# 画食物  
def drawApple(coord):  
    x = coord['x'] * CELLSIZE  
    y = coord['y'] * CELLSIZE  
    appleRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)  
    pygame.draw.rect(DISPLAYSURF, RED, appleRect)  
  
# 画格子  
def drawGrid():  
    for x in range(0, WINDOWWIDTH, CELLSIZE):  # draw vertical lines  
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, WINDOWHEIGHT))  
    for y in range(0, WINDOWHEIGHT, CELLSIZE):  # draw horizontal lines  
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (WINDOWWIDTH, y))  
  
  
if __name__ == '__main__':  
    main()

结尾

山高路远,各位江湖再见!!!欢迎大家的关注和打赏!!!

你可能感兴趣的:(pygame,pygame,python,开发语言)