Implementación de Snake desde cero (código completo)

prefacio

Este artículo se dividirá en tres partes para explicar la implementación de Snake, dividida en la pantalla del juego antes de que comience Snake, la pantalla en el juego y la pantalla final del juego, ¡luego comencemos!

interfaz de inicio del juego

Habrá una pantalla antes de que comience el juego, en términos generales, es para brindar opciones, como recuerdos de la infancia "Tank War", habrá una pantalla para que los jugadores elijan antes de comenzar, modo de un jugador o modo de dos jugadores, y nuestra serpiente puede Con gráficos dinámicos, cuando el jugador presione una tecla diferente a Esc en el teclado, irá directamente al juego. Empecemos a explicar el código.

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 

Primero, configuramos la fuente y el tamaño de fuente (titleFont), y luego configuramos el color y el fondo de la fuente al renderizar.Si el color de fondo no está configurado, el valor predeterminado es negro. Finalmente, los grados 1 y los grados 2 se utilizan para establecer el ángulo de rotación.

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

Del mismo modo, primero llenamos el color de fondo con negro. En cuanto a por qué hacemos esto, puede comentar esta línea de código usted mismo y luego ejecutarlo para ver el efecto. El método de rotar una imagen en pygame, pygame.transform.rotate(superficie, ángulo), necesitamos pasar una superficie y el ángulo de rotación, luego obtener su objeto rectangular, dejar que se muestre en el centro, el centro representa el centro coordenadas del rectángulo, y finalmente poner It draws en la pantalla, y el efecto de las siguientes líneas de código es el mismo, así que no hablaré más de eso.

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

checkForKeyPress() Este es un método de función escrito por nosotros mismos, la función específica es indicar si el usuario presiona el teclado y, de ser así, ingresará al juego. pygame.display.update() actualiza la pantalla del juego, se acumulan degress1 y degress2, y el ángulo de rotación aumenta paso a paso.

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

Echemos un vistazo a la representación.
![[Serpiente antes del comienzo de la pantalla.png]]

También podemos hacer una interfaz de selección, que puede ser un juego de un solo jugador o un juego de dos jugadores, por supuesto, seguimos eligiendo el primero, comencemos a mostrarlo a continuación.

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()

Diagrama de efecto de carrera
![[Imagen de selección de serpiente.png]]

parte del juego

Movimiento de serpiente (básico)

El siguiente código trata sobre el movimiento de la serpiente y el dibujo de la serpiente (se puede ejecutar por separado). Porque queremos dibujar una cuadrícula, y la cuadrícula debe caber en la serpiente, en otras palabras, el tamaño de cada cuadrícula es el mismo que el tamaño de la cuadrícula que forma la serpiente. Así que aquí está reducido y dividido por 20, lo que es más conveniente.

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()

En primer lugar, primero aleatorizamos la posición de la cabeza de la serpiente y luego, de acuerdo con la posición de la cabeza de la serpiente, x es -1, -2 para obtener las coordenadas completas de la serpiente. Tenga en cuenta que 1 aquí significa 20 píxeles y 2 significa 40 píxeles La dirección de avance predeterminada es hacia la derecha.

# 随机出现位置  
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  

Esta es la estructura familiar nuevamente, pygame.event.get() obtiene el evento, cuando el jugador hace clic en la X en la esquina superior derecha, se activa el evento de cierre (QUIT) y la lógica que escribimos a continuación saldrá del juego. Presionamos el teclado para activar el evento del teclado (KEYDOWN), y luego determinamos específicamente qué tecla se presiona, y esas teclas corresponden a controlar el movimiento de la serpiente. Cuando la serpiente se mueve hacia la derecha, no puede moverse hacia la izquierda, es decir, se mueve en la dirección opuesta. Puedes eliminar el código similar a y dirección != DERECHA para ver qué efecto tendrá. La práctica es el único criterio. para probar la verdad.

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() 

Este código es una restricción en el movimiento de la serpiente, si la serpiente se mueve más allá de la pantalla, el juego terminará, y también terminará el juego si toca su propio cuerpo.

# 出界就挂了  
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  

Eliminamos el último diccionario en wormCoords, insertamos un nuevo diccionario en la primera posición en wormCoords, eliminamos uno y agregamos uno para lograr el efecto del movimiento de la serpiente.

 # 删除最后一个矩形  
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)  

Dibujar una serpiente se divide en dos pasos. El primer paso es dibujar bien la serpiente, y el segundo paso es optimizar y profundizar el color de la serpiente para que se vea mejor.

# 画蛇  
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)

Dibujamos una línea cada 20 píxeles según el ancho y el alto, y la cuadrícula está terminada.

# 画格子  
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)) 

dibujar comida

La comida aparece aleatoriamente, y el cuerpo de la serpiente aumentará en una cuadrícula cuando coma la comida. Cuando eliminamos el último diccionario de wormCoords, la serpiente no lo eliminará cuando toque la comida, lo que equivale a aumentar la serpiente en una rejilla

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()

número de fracciones

Dibuja la puntuación, calcula la puntuación según la cantidad de comida que come el jugador, una comida equivale a un punto.

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()

juego terminado pantalla

El juego termina cuando la serpiente sale de la pantalla o toca su propio cuerpo.

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()

código completo

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])  
        # <Event(769-KeyUp {'unicode': '\x1b', 'key': 27, 'mod': 4096, 'scancode': 41, 'window': None})>  
        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()

fin

Las montañas son altas y el camino está lejos, ¡adiós a todos! ! ! ¡Bienvenido a la atención y recompensas de todos! ! !

Supongo que te gusta

Origin blog.csdn.net/qq_65898266/article/details/131406624
Recomendado
Clasificación