Python第三方库pygame学习笔记(二)

前言

在之前Python学习笔记中,学习过python第三方库pygame的三大基本机制和最小游戏设计框架。我们对国民偶像蔡徐坤进行了动态展示。之后,闲来无事实现了小时候玩过的小游戏贪食蛇。

具体参考笔记一:python第三方库pygame学习笔记(一)

游戏机制

玩过贪食蛇的朋友对贪食蛇的游戏机制并不会陌生。大致如下:

1、控制初始生成的小蛇进行移动进而吃到随机生成的食物,用于增加自己的长度

2、当小蛇撞墙或头碰到自己的身体则游戏结束

源码参考:python 贪吃蛇小游戏代码

本文中新加的小彩蛋:

1、当小蛇吃到食物达到指定数量的时候,屏幕上会额外刷新一个奖励即生命

2、小蛇的额外生命能用于抵消传统游戏机制2的影响:触墙生命-1,头碰到自己身体则生命清零

3、小蛇会随着吃到的食物数量进而增加自己的移动速度

设计思想

在学习了自顶向下设计和自底向上实现的编程思想后,试着将贪食蛇的代码实现进行模块化编写。大致可以从如下流程图出发

程序代码

import random
import pygame
import sys
from pygame.locals import *

Window_Width = 800
Window_Height = 500
Cell_Size = 20  # Width and height of the cells
# Ensuring that the cells fit perfectly in the window. eg if cell size was
# 10     and window width or windowheight were 15 only 1.5 cells would
# fit.
assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size."
# Ensuring that only whole integer number of cells fit perfectly in the window.
assert Window_Height % Cell_Size == 0, "Window height must be a multiple of cell size."
Cell_W = int(Window_Width / Cell_Size)  # Cell Width
Cell_H = int(Window_Height / Cell_Size)  # Cellc Height

White = (255, 255, 255)
Black = (0, 0, 0)
Red = (255, 0, 0)  # Defining element colors for the program.
Green = (0, 255, 0)
DARKGreen = (0, 155, 0)
DARKGRAY = (40, 40, 40)
YELLOW = (255, 255, 0)
Red_DARK = (150, 0, 0)
BLUE = (0, 0, 255)
BLUE_DARK = (0, 0, 150)
BGCOLOR = Black  # Background color
HEAD = 0  # Syntactic sugar: index of the snake's head


#绘制分数和声明
def drawLife(life):
    lifeSurf=BASICFONT.render('Life: %s' % (life), True, Red)
    lifeRect=lifeSurf.get_rect()
    lifeRect.topleft=(Window_Width-240,10)
    DISPLAYSURF.blit(lifeSurf,lifeRect)

def drawScore(score):
    scoreSurf = BASICFONT.render('Score: %s' % (score), True, White)
    scoreRect = scoreSurf.get_rect()
    scoreRect.topleft = (Window_Width - 120, 10)
    DISPLAYSURF.blit(scoreSurf, scoreRect)



def drawWorm(wormCoords,life,getLife):
    for coord in wormCoords:
        x = coord['x'] * Cell_Size
        y = coord['y'] * Cell_Size
        wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
        pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect)
        wormInnerSegmentRect = pygame.Rect(
            x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)
        if life>0:
            pygame.draw.rect(DISPLAYSURF, (255,255-life*20,life*20), wormInnerSegmentRect)
        else:
            pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect)

# 绘制食物
def drawApple(coord):
    x = coord['x'] * Cell_Size
    y = coord['y'] * Cell_Size
    appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
    pygame.draw.rect(DISPLAYSURF, Red, appleRect)


# 绘制奖励
def drawPrice(coord):
    x = coord['x'] * Cell_Size
    y = coord['y'] * Cell_Size
    priceRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
    pygame.draw.ellipse(DISPLAYSURF, YELLOW, priceRect)


def drawGrid():
    for x in range(0, Window_Width, Cell_Size):  # draw vertical lines
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height))
    for y in range(0, Window_Height, Cell_Size):  # draw horizontal lines
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (Window_Width, y))


def enlargeBody(direction, wormCoords):
    # move the worm by adding a segment in the direction it is moving
    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']}

    return newHead
def drawPressKeyMsg():
    pressKeySurf = BASICFONT.render('Press a key to play.', True, White)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (Window_Width - 200, Window_Height - 30)
    DISPLAYSURF.blit(pressKeySurf, pressKeyRect)


def checkForKeyPress():
    if len(pygame.event.get(QUIT)) > 0:
        terminate()
    keyUpEvents = pygame.event.get(KEYUP)
    if len(keyUpEvents) == 0:
        return False
    elif keyUpEvents[0].key == K_ESCAPE:
        terminate()
    else:
        return keyUpEvents[0].key


def showStartScreen():
    titleFont = pygame.font.Font('freesansbold.ttf', 100)
    titleSurf1 = titleFont.render('Snake!', True, White, DARKGreen)
    degrees1 = 0
    degrees2 = 0
    while True:
        DISPLAYSURF.fill(BGCOLOR)
        rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
        rotatedRect1 = rotatedSurf1.get_rect()
        rotatedRect1.center = (Window_Width / 2, Window_Height / 2)
        DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)
        drawPressKeyMsg()

        if checkForKeyPress():
            pygame.event.get()  # clear event queue
            return
        pygame.display.update()
        SnakespeedCLOCK.tick(17)
        degrees1 += 3  # rotate by 3 degrees each frame
        degrees2 += 7  # rotate by 7 degrees each frame


def terminate():
    pygame.quit()
    sys.exit()


def getRandomLocation():
    return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}


def showGameOverScreen():
    gameOverFont = pygame.font.Font('freesansbold.ttf', 100)
    gameSurf = gameOverFont.render('Game', True, White)
    overSurf = gameOverFont.render('Over', True, White)
    gameRect = gameSurf.get_rect()
    overRect = overSurf.get_rect()
    gameRect.midtop = (Window_Width / 2, 10)
    overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25)

    DISPLAYSURF.blit(gameSurf, gameRect)
    DISPLAYSURF.blit(overSurf, overRect)
    drawPressKeyMsg()
    pygame.display.update()
    pygame.event.get()
    while True:
        if checkForKeyPress():
            pygame.event.get()  # clear event queue
            return
def main():
    global SnakespeedCLOCK, DISPLAYSURF, BASICFONT

    pygame.init()
    SnakespeedCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))
    BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
    pygame.display.set_caption('Snake')

    showStartScreen()
    while True:
        runGame()
        showGameOverScreen()

def runGame():
    # Set a random start point.
    checkForKeyPress()
    cnt = 0
    life = 0  # 初始分数和奖励为0
    getLife=0
    Snakespeed=10
    startx = random.randint(20, Cell_W - 8)
    starty = random.randint(6, Cell_H - 6)
    wormCoords = [{'x': startx, 'y': starty},
                  {'x': startx - 1, 'y': starty},
                  {'x': startx - 2, 'y': starty}]
    initialDir = ['up', 'down', 'right']
    statusDir = random.randint(0, 2)
    direction = initialDir[statusDir]

    # Start the apple in a random place.
    apple = getRandomLocation()
    priceInitial = {'x':Window_Width,'y':Window_Height}
    price=priceInitial
    while True:  # main game loop
        for event in pygame.event.get():  # event handling loop
            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()


        # check if the Snake has hit itself or the edge
        if (wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or \
            wormCoords[HEAD]['y'] == Cell_H) and life != 0:
            if life > 0:
                if wormCoords[HEAD]['x'] == -1:
                    wormCoords[HEAD]['x'] = Cell_W - 1
                    life -= 1
                elif wormCoords[HEAD]['x'] == Cell_W:
                    wormCoords[HEAD]['x'] = 0
                    life -= 1
                elif wormCoords[HEAD]['y'] == -1:
                    wormCoords[HEAD]['y'] = Cell_H - 1
                    life -= 1
                elif wormCoords[HEAD]['y'] == Cell_H:
                    wormCoords[HEAD]['y'] = 0
                    life -= 1
        elif (wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or \
              wormCoords[HEAD]['y'] == Cell_H) and life == 0:
            return True
        for wormBody in wormCoords[1:]:
            if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
                if life == 0:
                    return True  # game over
                else:
                    life=0



        # check if Snake has eaten an apple or price
        if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
            # don't remove worm's tail segment
            apple = getRandomLocation()  # set a new apple somewhere
            cnt += 1
            newHead = enlargeBody(direction, wormCoords)
            wormCoords.insert(0, newHead)
            #游戏加速
            Snakespeed+=cnt//5
            if cnt in [1,3,5,7,9]:
                price = getRandomLocation()
                getLife+=1
        if wormCoords[HEAD]['x'] == price['x'] and wormCoords[HEAD]['y'] == price['y']:
            getLife-=1
            life += 1
            price = priceInitial

        else:
            del wormCoords[-1]  # remove worm's tail segment
        # 奖励机制


        newHead = enlargeBody(direction, wormCoords)
        wormCoords.insert(0, newHead)
        DISPLAYSURF.fill(BGCOLOR)
        drawGrid()
        drawWorm(wormCoords,life,getLife)
        drawApple(apple)
        drawPrice(price)
        drawScore(cnt)
        drawLife(life)
        pygame.display.update()
        SnakespeedCLOCK.tick(Snakespeed)

if __name__ == '__main__':
    try:
        main()
    except SystemExit:
        pass

后记

感觉贪食蛇如果彩蛋加的比较多的话,可玩性也不是没有。比如当我们碰到自己身体的时候,不单单是清空生命,而是咬掉这一段。。积分过了多少,出现反键状态,得分double。想想都好玩。如果后续实现了,会继续贴出来的。毕竟我是个菜鸡。

猜你喜欢

转载自blog.csdn.net/weixin_42686879/article/details/90078024