【程序源代码】python像素贪吃蛇

程序源代码

共 7653字,需浏览 16分钟

 ·

2020-07-16 05:15

关键字:python 游戏 贪吃蛇

8a39bc2e5944ed7283b58f33fceaee26.webp

正文 | 内容

介绍

python像素贪吃蛇小游戏,可以通过上下左右键控制蛇头转向,点击回车键开始游戏。简单好玩

软件架构

基于python3.0以上版本 基于pygame模块开发

安装教程

  1. 基于python3.0以上版本开发.开发时使用的是python3.7版本。

使用说明

  1. 基于python3.0以上版本开发,开发时使用的是python3.7版本。建议开发前本地安装pygame/random/sys模块

  2. 用pycharm打开源文件(一般pycharm会自动提示需要安装的插件或者模块)

  3. 点击retroSnaker.py,直接运行即可

游戏截图

  1. 游戏开始 50ca48495cefae0f39bb286bbfc76ab8.webp

  2. 游戏中 b97d23b28b7a1650fd2679e77ac1dabe.webp

  3. 游戏结束

e679f67721f76e4f38fa13635cdfb7fb.webp

02

【一条蛇】

"""

功能:python像素贪吃蛇

作者:程序源代码

时间:2020-07-15

"""


# 导入相关模块与函数

import random

import pygame

import sys

from pygame.locals import *


# 初始化pygame

pygame.init()

# 表明四个全局变量

global Speed

global Trackingtime

global Displayobject

global WindowTypeface

Speed = 8

Trackingtime = pygame.time.Clock()  # 创建跟踪时间对象

Displayobject = pygame.display.set_mode((640, 480))  # 设置窗口高宽640*480

WindowTypeface = pygame.font.SysFont('Calibri.ttf', 25)  # 创建Typeface对象并设置字体和字号

pygame.display.set_caption('像素贪吃蛇')  # 设置窗口标题

backgroundcolor = (255, 255, 255)  # 设置窗口底色为纯白色



# 侦测键盘操作

def CheckKeyboardPress():

    if len(pygame.event.get(QUIT)) > 0:

        pygame.quit()

        sys.exit()

    keyUpEvents = pygame.event.get(KEYUP)

    if len(keyUpEvents) == 0:

        return None

    return keyUpEvents[0].key



# 游戏开始界面设计

def DesignStartScreen():

    global Speed

    titleTypeface1 = pygame.font.SysFont('Calibri.ttf', 200)

    titleTypeface2 = pygame.font.SysFont('Calibri.ttf', 60)

    titleContent1 = titleTypeface1.render('RETRO SNAKER', True, (0, 0, 0), (0, 0, 0))  # 设置主界面文字和大小

    titleContent2 = titleTypeface2.render('RETRO SNAKER', True, (255, 0, 0))

    KeyboardContent = WindowTypeface.render('Press any key to start', True, (0, 0, 0))

    Displayobject.fill(backgroundcolor)

    revolveContent1 = pygame.transform.rotate(titleContent1, 0)

    revolveRect1 = revolveContent1.get_rect()

    revolveRect1.center = (640 / 2, 480 / 2)

    Displayobject.blit(revolveContent1, revolveRect1)

    revolveContent2 = pygame.transform.rotate(titleContent2, 0)

    revolveRect2 = revolveContent2.get_rect()

    revolveRect2.center = (640 / 2, 480 / 2)

    Displayobject.blit(revolveContent2, revolveRect2)


    # 获得一个对象的rect,以便于设置其坐标位置

    KeyboardRect = KeyboardContent.get_rect()

    KeyboardRect.topleft = (640 - 200, 480 - 30)

    Displayobject.blit(KeyboardContent, KeyboardRect.topleft)

    pygame.display.update()

    Trackingtime.tick(Speed)

    while True:

        if CheckKeyboardPress():

            pygame.event.get()  # 清除事件队列

            return



# 游戏结束界面设计

def DesignGameOverScreen():

    gameOverTypeface = pygame.font.SysFont('Calibri.ttf', 100)

    gameoverContent = gameOverTypeface.render('Game Over', True, (0, 0, 0))

    KeyboardContent = WindowTypeface.render('Press any key to restart', True, (0, 0, 0))

    gameoverRect = gameoverContent.get_rect()

    gameoverRect.center = (640 / 2, 480 / 2)

    Displayobject.blit(gameoverContent, gameoverRect)


    # 获得一个对象的rect,以便于设置其坐标位置

    KeyboardRect = KeyboardContent.get_rect()

    KeyboardRect.topleft = (640 - 220, 480 - 30)

    Displayobject.blit(KeyboardContent, KeyboardRect.topleft)

    pygame.display.update()

    pygame.time.wait(600)

    while True:

        if CheckKeyboardPress():

            pygame.event.get()  # 清除事件队列

            return



# 贪吃蛇蛇身设计

def DesignRetroSnaker(RetroSnakerCoords):

    for coord in RetroSnakerCoords:

        x = coord['x'] * 20  # 规定每行单元格的大小为20

        y = coord['y'] * 20

        RetroSnakerSegmentRect = pygame.Rect(x, y, 20, 20)

        pygame.draw.rect(Displayobject, (0, 0, 255), RetroSnakerSegmentRect)

        RetroSnakerInnerSegmentRect = pygame.Rect(x + 4, y + 4, 20 - 8, 20 - 8)

        pygame.draw.rect(Displayobject, (173, 216, 230), RetroSnakerInnerSegmentRect)



# 苹果设计

def DesignApple(coord):

    x = coord['x'] * 20  # 规定单元格的大小为20

    y = coord['y'] * 20

    appleRect = pygame.Rect(x, y, 20, 20)

    pygame.draw.rect(Displayobject, (255, 0, 0), appleRect)



# 得分分数设计

def DesignScore(score):

    scoreContent = WindowTypeface.render('Score: %s' % (score), True, (0, 0, 0))

    scoreRect = scoreContent.get_rect()

    scoreRect.topleft = (640 - 100, 10)

    Displayobject.blit(scoreContent, scoreRect)



# 边框线设计

def DesignBorderline():

    for x in range(0, 640, 640 - 1):  # 绘制垂直线

        pygame.draw.line(Displayobject, (0, 0, 0), (x, 0), (x, 480), 5)

    for y in range(0, 480, 480 - 1):  # 绘制平行线

        pygame.draw.line(Displayobject, (0, 0, 0), (0, y), (640, y), 5)



# 设置游戏主要运行机制

def GameRunning():

    global Speed

    # 设置随机起点

    startx = random.randint(5, 26)  # 初始单元格位置横向在(5, 26)范围中选一个随机数

    starty = random.randint(5, 18)  # 初始单元格位置纵向在(5, 18)范围中选一个随机数

    RetroSnakerCoords = [{'x': startx, 'y': starty},

                         {'x': startx - 1, 'y': starty},

                         {'x': startx - 2, 'y': starty}]  # RetroSnakerCoords:列表,贪吃蛇坐标位置

    direction = 'right'  # 初始方向朝右

    # 设置苹果在一个随机位置

    apple = {'x': random.randint(0, 31), 'y': random.randint(0, 23)}


    while True:  # 游戏主循环

        # 判断键盘事件

        for event in pygame.event.get():  # 事件处理循环

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


        # 根据方向改变蛇头的坐标

        if direction == 'up':

            m = {'x': RetroSnakerCoords[0]['x'], 'y': RetroSnakerCoords[0]['y'] - 1}

        elif direction == 'down':

            m = {'x': RetroSnakerCoords[0]['x'], 'y': RetroSnakerCoords[0]['y'] + 1}

        elif direction == 'left':

            m = {'x': RetroSnakerCoords[0]['x'] - 1, 'y': RetroSnakerCoords[0]['y']}

        elif direction == 'right':

            m = {'x': RetroSnakerCoords[0]['x'] + 1, 'y': RetroSnakerCoords[0]['y']}


        # 通过向贪吃蛇移动的方向添加一个单元格来加长贪吃蛇

        RetroSnakerCoords.insert(0, m)


        # 侦测贪吃蛇是否吃到苹果

        if RetroSnakerCoords[0]['x'] == apple['x'] and RetroSnakerCoords[0]['y'] == apple['y']:

            apple = {'x': random.randint(0, 31), 'y': random.randint(0, 23)}  # 在随机位置放置一个苹果

            Speed = Speed + 0.2

        else:

            del RetroSnakerCoords[-1]  # 去除贪吃蛇的尾段


        # 侦测贪吃蛇是否触碰到窗口边缘或自身

        if RetroSnakerCoords[0]['x'] == -1 or RetroSnakerCoords[0]['x'] == 32 or RetroSnakerCoords[0]['y'] == -1 or \

                RetroSnakerCoords[0]['y'] == 24:

            return  # 游戏结束

        for RetroSnakerBody in RetroSnakerCoords[1:]:

            if RetroSnakerCoords[0]['x'] == RetroSnakerBody['x'] and RetroSnakerCoords[0]['y'] == RetroSnakerBody['y']:

                return  # 游戏结束


        # 绘制相关角色在窗口中

        Displayobject.fill(backgroundcolor)

        DesignRetroSnaker(RetroSnakerCoords)

        DesignApple(apple)

        DesignScore(len(RetroSnakerCoords) - 3)

        DesignBorderline()

        pygame.display.update()  # 让绘制的东西显示在屏幕上

        Trackingtime.tick(Speed)



# 主函数

if __name__ == '__main__':

    DesignStartScreen()  # 初始化游戏开始界面

    while True:

        GameRunning()  # 游戏开始

        DesignGameOverScreen()  # 游戏结束


03

最近疫情期,自己憋在家里除了日常的活动外,没有其它事情要做,感觉时间都浪费掉了。同时由于疫情经济和情感上压力也有些大。为了排解压力让自己充实起来,我决定自己用一个月的时候自学一个新语言,选来选去决定学习python。在学习的过程中接有时感觉特别累,每天总体上也坚持自学至少三个小时。学习中发现了一个比较好的软件xmind,通过xmind这个思维导图软件制作了一些自学笔记,把每节的重点整理成图形的方式,很容易直观理解和掌握。最近整理出来一些图例分享给大家一起学习,希望大家能喜欢。自学确实不容易,贵在坚持!


【程序源代码】《零基础学编程-python》源码包1

【程序源代码】《零基础学编程-python》源码包2

【程序源代码】《零基础学编程-python》源码包3

更多精彩内容请关注公众号后续发布文章








微信ID:  itcoder

微信二维码, 扫一扫吧




【投稿邮箱】315997972@qq.com【写作说明】以上文章属于此公众号原创所有,如需转载请注明出处。【免责申明】本公众号不是广告商,也没有为其他三方网站或者个人做广告宣传。文章发布源代码和文章均来源于各类开源网站社区或者是小编在项目中、学习中整理的一些实例项目。主要目的是将开源代码分享给喜欢编程、有梦想的程序员,希望能帮助到你们与他们共同成长。其中用户产生的一些自愿下载或者付费行为,原则与平台没有直接关系。如果涉及开源程序侵犯到原作者相关权益,可联系小编进行相关处理。
目前已有100000+优秀的程序员加入我们1d091cbeac6166098843def293f1ebaf.webp     9010b446e611bfd833a1e0219d50f120.webp     a6043dc17e2828710c1d210420af210c.webp     362a18453b554750a323605f04926e1a.webp     811ac94b7228e17a457c8684ccfe8231.webp     c924ed9ebbaa060c5fd3c1e3d8c01388.webp 049bda5cf86fc88e6f35226fee57eeff.webp     55ac4d64490207f4b41588e2d1552e66.webp     2cb07b7e5097a96cd55acec10acd8b79.webp     63abc0db4b5ef1297eac4f500ec1c296.webp     0c3a7574920e9587d6f5bd032db89999.webp     a8a2366efa7abd5977d2a57783d8eb0b.webp

——————d821ede688f1988a659f9213d4876dd4.webpd821ede688f1988a659f9213d4876dd4.webpd821ede688f1988a659f9213d4876dd4.webp————————


【你的每一份打赏就是对我最真诚的鼓励】
浏览 30
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报