猫史档案馆


【Python作品分享】贪吃蛇

用户:老秦Lanny老秦Lanny查看:0 回复:0 评论:0 创建时间:2022-08-07T11:31:11


【作品展示】

center_image

 

【作品介绍】

 

【作品源代码】

import random
import pygame
import sys,time
from pygame.locals import *
Snakespeed = 17
Window_Width = 1920
Window_Height = 1080
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 = (200, 200, 0)
Red_DARK = (150, 0, 0)
BLUE = (0, 0, 255)
BLUE_DARK = (0, 0, 150)
BGCOLOR = Black # Background color
UP = 'up'
DOWN = 'down'      # Defining keyboard keys.
LEFT = 'left'
RIGHT = 'right'
HEAD = 0  # Syntactic sugar: index of the snake's head
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'S GAME")
 
    showStartScreen()
    runGame()
    showGameOverScreen()
    drawPressKeyMsg()
def runGame():
    # Set a random start point.
    startx = random.randint(5, Cell_W - 6)
    starty = random.randint(5, Cell_H - 6)
    wormCoords = [{'x': startx, 'y': starty},
                  {'x': startx - 1, 'y': starty},
                  {'x': startx - 2, 'y': starty}]
    direction = RIGHT
 
    # Start the apple in a random place.
    apple = getRandomLocation()
 
    while True:  # main game loop
        for event in pygame.event.get():  # event handling loop
            if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
            elif event.type == KEYDOWN:
                if (event.key == K_LEFT) and direction != RIGHT:
                    direction = LEFT
                elif (event.key == K_RIGHT) and direction != LEFT:
                    direction = RIGHT
                elif (event.key == K_UP) and direction != DOWN:
                    direction = UP
                elif (event.key == K_DOWN) 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:
            return  # game over
        for wormBody in wormCoords[1:]:
            if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
                return  # game over
 
        # check if Snake has eaten an apply
        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
        else:
            del wormCoords[-1]  # remove worm's tail segment
 
        # 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']}
        wormCoords.insert(0, newHead)
        DISPLAYSURF.fill(BGCOLOR)
        drawGrid()
        drawWorm(wormCoords)
        drawApple(apple)
        drawScore(len(wormCoords) - 3)
        pygame.display.update()
        SnakespeedCLOCK.tick(Snakespeed)
def drawPressKeyMsg():
    pressKeySurf = BASICFONT.render('Press any key to continue . . .', True, Red)    
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (Window_Width - 280, Window_Height - 25)
    DISPLAYSURF.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 showStartScreen():
    titleFont = pygame.font.Font('freesansbold.ttf', 100)
    titleSurf1 = titleFont.render("SNAKE'S GAME", 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(Snakespeed)
        degrees1 += 3  # rotate by 3 degrees each frame
        degrees2 += 7  # rotate by 7 degrees each fram
def terminate():
    pygame.time.wait(500)
    pygame.quit()
    sys.exit()
def getRandomLocation():
    return {'x': random.randint(2, Cell_W - 3), 'y': random.randint(3, Cell_H - 3)}
def showGameOverScreen():
    gameOverFont = pygame.font.Font('freesansbold.ttf', 95)
    gameSurf = gameOverFont.render("Game Over!", True, White)
    overSurf = gameOverFont.render("Thank you for playing Snake's Game!", True,White)
    gameRect = gameSurf.get_rect()
    overRect = overSurf.get_rect()
    gameRect.midtop = (Window_Width / 2, 25)
    overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 40)
 
    DISPLAYSURF.blit(gameSurf, gameRect)
    DISPLAYSURF.blit(overSurf, overRect)
    pygame.display.update()
    pygame.time.wait(1000)
    checkForKeyPress()  # clear out any key presses in the event queue
 
    while True:
        if checkForKeyPress():
            pygame.event.get()  # clear event queue
            return
def drawScore(score):
    time_score=int(pygame.time.get_ticks()/15000)   #time=seconds+'000'
    thisScore=score*10+time_score*10
    with open('bestscore.txt','r')as file_object:
        count=int(file_object.read())
        if thisScore>count:
            file_object.close()
            with open('bestscore.txt','w')as file_objet:
                file_objet.write (str(thisScore))
    roundScore=int(round(thisScore,-1))
    ScoreStr='{:,}'.format(roundScore)
    roundfile_object=round(count,-1)
    fojStr='{:,}'.format(roundfile_object)
    BASICFONT = pygame.font.Font('freesansbold.ttf', 25)
    scoreSurf = BASICFONT.render('*(^_^)*Warm prompt:you can press ESC to exit*(^_^)*  Best score:%s Score:%s Time score:%s Food score:%s' % (fojStr,ScoreStr,time_score*10,score*10), True, White)
    scoreRect = scoreSurf.get_rect()
    scoreRect.midtop = (Window_Width/2, 1)
    DISPLAYSURF.blit(scoreSurf, scoreRect)
    #scoresurf1 = BASICFONT.render('Score: %s' % (score1), True, White)
    #scoresurf2 = BASICFONT.render('Score: %s' % (score2), True, White)
    #scoreRect1 = scoreSurf1.get_rect()
    #scoreRect2 = scoreSurf2.get_rect()
    #scoreRect1.topleft = (Window_Width - 120, 10)
    #scoreRect2.topleft = (Window_Width - 120, 20)
    #DISPLAYSURF.blit(scoreSurf1, scoreRect1)
    #DISPLAYSURF.blit(scoreSurf2, scoreRect2)
    #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):
    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)
        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 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))
if __name__ == '__main__':
    try:
        main()
    except SystemExit:
        pass

 

【提示】

部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:

https://python.codemao.cn


回复

上一页1 页 / 共 0下一页