首页 > 编程语言 >Python 简易版贪食蛇(源代码)

Python 简易版贪食蛇(源代码)

时间:2022-10-28 16:04:11浏览次数:58  
标签:direction Python self snakePosition 简易版 pygame 源代码 changeDirection event

Python 简易版贪食蛇

简易版贪食蛇代码如下,直接运行即可。

1. 效果图

在这里插入图片描述

2.源代码

源代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pygame as pygame
import random
import sys

from pygame.rect import Rect


class Snake(object):
    def __init__(self):
        self.black = pygame.Color(0, 0, 0)
        self.green = pygame.Color(0, 255, 0)
        self.white = pygame.Color(255, 255, 255)

    def gameover(self):
        pygame.quit()
        sys.exit()

    def initialize(self):
        pygame.init()
        clock = pygame.time.Clock()

        playSurface = pygame.display.set_mode((800, 600))

        pygame.display.set_caption('tanshishe')

        snakePosition = [80, 80]

        snakebody = [[80, 80], [60, 80], [40, 80]]

        targetPosition = [200, 400]
        targetflag = 1
        direction = 'right'

        changeDirection = direction
        self.main(snakebody, targetPosition, targetflag, direction, changeDirection, snakePosition, playSurface, clock)

    def main(self, snakebody, targetPosition, targetflag, direction, changeDirection, snakePosition, playSurface,
             clock):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RIGHT:
                        changeDirection = 'right'
                        print("向右转")
                    if event.key == pygame.K_LEFT:
                        changeDirection = 'left'
                        print("向左转")
                    if event.key == pygame.K_DOWN:
                        changeDirection = 'down'
                        print("向上走")
                    if event.key == pygame.K_UP:
                        changeDirection = 'up'
                        print("向下走")
                    if event.key == pygame.K_ESCAPE:
                        pygame.event.post(pygame.event.Event(pygame.QUIT))

            if (changeDirection == 'left' and not direction == 'right'):
                direction = changeDirection
            if (changeDirection == 'right' and not direction == 'left'):
                direction = changeDirection
            if (changeDirection == 'down' and not direction == 'up'):
                direction = changeDirection
            if (changeDirection == 'up' and not direction == 'down'):
                direction = changeDirection

            if direction == 'right':
                snakePosition[0] += 20
            if direction == 'left':
                snakePosition[0] -= 20
            if direction == 'down':
                snakePosition[1] += 20
            if direction == 'up':
                snakePosition[1] -= 20

            snakebody.insert(0, list(snakePosition))
            if (snakePosition[0] == targetPosition[0] and snakePosition[1] == targetPosition[1]):
                targetflag = 0
            else:
                snakebody.pop()
            if targetflag == 0:
                x = random.randrange(1, 40)
                y = random.randrange(1, 30)
                targetPosition = [int(x * 20), int(y * 20)]
                targetflag = 1

            playSurface.fill(self.black)
            for position in snakebody:
                pygame.draw.rect(playSurface, self.white, Rect(position[0], position[1], 20, 20))
                pygame.draw.rect(playSurface, self.green, Rect(targetPosition[0], targetPosition[1], 20, 20))

            pygame.display.flip()
            if (snakePosition[0] > 900 or snakePosition[0] < 0):
                snake.gameover()
            elif (snakePosition[1] > 800 or snakePosition[0] < 0):
                snake.gameover()
            for i in snakebody[1:]:
                if (snakePosition[0] == i[0] and snakePosition[1] == i[1]):
                    snake.gameover()
            clock.tick(5)


snake = Snake()
snake.initialize()

标签:direction,Python,self,snakePosition,简易版,pygame,源代码,changeDirection,event
From: https://blog.51cto.com/zhemeshenqi/5804916

相关文章

  • 使用python 绘制中国人口热气图
    使用pythonmatlib绘制热力图绘制世界地图点击查看代码importmatplotlib.pyplotaspltfrommpl_toolkits.basemapimportBasemapplt.figure(figsize=(16,8))m......
  • python-threading.Event()
    threading模块提供Event类实现线程之间的通信threading.Event可以使一个线程等待其他线程的通知。其内置了一个标志,初始值为False。线程通过wait()方法进入等待状态,直到另......
  • python 脚本实现XCode自动打包/上传蒲公英/钉钉机器人通知
    通常我们使用XCode打包要archive然后导出,然后上传到蒲公英,再然后拿到蒲公英的截图去打包群里通知打包完成,既然这些动作都是由一个个步骤完成,那么何不使用python写一个脚......
  • 求大神解答:利用python爬取各县GDP结果为空,求大神看看我的代码问题在哪?
    目标url=红黑人口库代码importrequestsfromlxmlimportetreeimporttimeif__name__=='__main__':  url='https://pagead2.googlesyndication.com/getconfig/soda......
  • python3.9不支持win7
    安装:Anaconda3-2022.10-Windows-x86_64.exe会报错:FailedtocreateAnacondamenus详细信息:ErrorloadingPythonDLLxxxpython39.dll,LoadLibrary:PyInstaller:Forma......
  • python自学 简单的网站开发 1
     URL路由配置 1、先在PyCharm中创建个Django项目,然后在PyCharm中的终端窗口输入。pythonmanage.pystartappmyapp 创建一个名字为myapp的应用2、然后在终......
  • c# - mono - 调用 python 脚本 .py 文件
    c#-mono-调用python脚本.py文件一、定义命令行工具:在windows下是cmd.exe,在mac下使用bash。二、踩过的坑使用Process类,启动一个“命令行工具”,在通过向标准......
  • python - 字符串、日期时间转+格式化
    python-字符串、日期时间转+格式化 #!/usr/bin/envpython3#coding=utf-8importosimportsysimportargparseimportcodecsimporttime,datetimedeftest():#"24/......
  • python - 定时拆分备份 nginx 日志
    python-定时拆分备份nginx日志一、背景:nginx的log不会自动按天备份,而且记录时间格式不统一,此程序专门解决这两个问题;二、windows部署方式1.在nginx目录,创建一个n......
  • python - 分析 iis 日志 wwwlogs
    python-解析iis日志iis日志分析工具比较多,基本都支持windows(不夸平台),统计维度也有限。有找工具的时间还不如自己写一个!!!分析时注意iis日志是格林尼治时间,没有加时区。分......