用python写个贪吃蛇

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

FPS = 10
width = 640
height = 480
size = 20
assert width % size == 0, "Window width must be a multiple of cell size."
assert height % size == 0, "Window height must be a multiple of cell size."
cellwidth = int(width / size)
cellheight = int(height / size)

white     = (255, 255, 255)
black     = (  0,   0,   0)
red       = (255,   0,   0)
green     = (  0, 255,   0)
darkgreen = (  0, 155,   0)
darkgray  = ( 40,  40,  40)
bg = black

up = 'up'
down = 'down'
left = 'left'
right = 'right'

head = 0

def main():

    global FPSCLOCK, screen, font

    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    screen = pygame.display.set_mode((width, height))
    font = pygame.font.Font('freesansbold.ttf', 18)
    pygame.display.set_caption('贪吃蛇')

    
    while True:
        runGame()
    showGameOverScreen()
 
 
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

    # 把苹果放在一个随机位置
    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)
        screen.fill(bg)
        drawGrid()
        drawWorm(wormCoords)
        drawApple(apple)
        drawScore(len(wormCoords) - 3)
        pygame.display.update()
        FPSCLOCK.tick(FPS)
 
def drawPressKeyMsg():
    pressKeySurf = font.render('Press a key to play.', True, darkgray)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (width - 200,height - 30)
    screen.blit(pressKeySurf, pressKeyRect)


def checkForKeyPress():
    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:
        terminate()
    return keyUpEvents[0].key

 
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 = (width / 2, 10)
    overRect.midtop = (width / 2, gameRect.height + 10 + 25)

    screen.blit(gameSurf, gameRect)
    screen.blit(overSurf, overRect)
    drawPressKeyMsg()
    pygame.display.update()
    pygame.time.wait(500)
    checkForKeyPress()

    while True:
         if checkForKeyPress():
             pygame.event.get()
             return
 
def drawScore(score):
    scoreSurf = font.render('Score: %s' % (score), True, white)
    scoreRect = scoreSurf.get_rect()
    scoreRect.topleft = (width - 120, 10)
    screen.blit(scoreSurf, scoreRect)


def drawWorm(wormCoords):
    for coord in wormCoords:
        x = coord['x'] * size
        y = coord['y'] * size
        wormSegmentRect = pygame.Rect(x, y, size, size)
        pygame.draw.rect(screen, darkgreen, wormSegmentRect)
        wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, size - 8, size - 8)
        pygame.draw.rect(screen, green, wormInnerSegmentRect)
 
 
def drawApple(coord):
    x = coord['x'] * size
    y = coord['y'] * size
    appleRect = pygame.Rect(x, y, size, size)
    pygame.draw.rect(screen, red, appleRect)
 
 
def drawGrid():
    for x in range(0, width, size):
        pygame.draw.line(screen, darkgray, (x, 0), (x, height))
    for y in range(0, height, size):
        pygame.draw.line(screen, darkgray, (0, y), (width, y))


if __name__ == '__main__':
    main()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_46500711/article/details/122526801
今日推荐