在好例子网,分享、交流、成长!
您当前所在位置:首页Python 开发实例Python语言基础 → pygame贪吃蛇

pygame贪吃蛇

Python语言基础

下载此实例
  • 开发语言:Python
  • 实例大小:0.02M
  • 下载次数:25
  • 浏览次数:350
  • 发布时间:2020-05-31
  • 实例类别:Python语言基础
  • 发 布 人:用户19800331
  • 文件格式:.rar
  • 所需积分:2
 相关标签: pygame game 贪吃蛇 py

实例介绍

【实例简介】

pygame贪吃蛇

【实例截图】

from clipboard

【核心代码】


import random

import pygame

import sys

from pygame.locals import *

Snakespeed = 17

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

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

    showStartScreen()

    while True:
        runGame()

        showGameOverScreen()


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:

                terminate()

            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 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 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!', 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 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.time.wait(500)

    checkForKeyPress()  # clear out any key presses in the event queue

    while True:

        if checkForKeyPress():
            pygame.event.get()  # clear event queue

            return


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


标签: pygame game 贪吃蛇 py

实例下载地址

pygame贪吃蛇

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

第 1 楼 用户19800331 发表于: 2020-06-14 10:32 08

支持(0) 盖楼(回复)

第 2 楼 jianggl 发表于: 2020-09-11 16:13 06
注释少了点,但是代码比较规范,很好的案例

支持(0) 盖楼(回复)

发表评论

(您的评论需要经过审核才能显示)

查看所有2条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警