导语

贪吃蛇,大家应该都玩过。当初第一次接触贪吃蛇的时候 ,还是我爸的数字手机,考试成绩比较好,就会得到一些小奖励,玩手机游戏肯定也在其中首位,毕竟小孩子天性都喜欢~

当时都能玩的不亦乐乎。今天,我们用Python编程一个贪吃蛇游戏哦~

正文

1.将使用两个主要的类(蛇和立方体)。

#Snake Tutorial Pythonimport math
import random
import pygame
import tkinter as tk
from tkinter import messageboxclass cube(object):rows = 20w = 500def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)):passdef move(self, dirnx, dirny):passdef draw(self, surface, eyes=False):passclass snake(object):def __init__(self, color, pos):passdef move(self):passdef reset(self, pos):passdef addCube(self):passdef draw(self, surface):passdef drawGrid(w, rows, surface):passdef redrawWindow(surface):passdef randomSnack(rows, item):passdef message_box(subject, content):passdef main():passmain()

2.创造游戏循环:

在所有的游戏中,我们都有一个叫做“主循环”或“游戏循环”的循环。该循环将持续运行,直到游戏退出。它主要负责检查事件,并基于这些事件调用函数和方法。

我们将在main()功能。在函数的顶部声明一些变量,然后进入while循环,这将代表我们的游戏循环。

def main(): global width, rows, swidth = 500  # Width of our screenheight = 500  # Height of our screenrows = 20  # Amount of rowswin = pygame.display.set_mode((width, height))  # Creates our screen objects = snake((255,0,0), (10,10))  # Creates a snake object which we will code laterclock = pygame.time.Clock() # creating a clock objectflag = True# STARTING MAIN LOOPwhile flag:pygame.time.delay(50)  # This will delay the game so it doesn't run too quicklyclock.tick(10)  # Will ensure our game runs at 10 FPSredrawWindow(win)  # This will refresh our screen  

​3.更新屏幕:通常,在一个函数或方法中绘制所有对象是一种很好的做法。我们将使用重绘窗口函数来更新显示。我们在游戏循环中每一帧调用一次这个函数。稍后我们将向该函数添加更多内容。然而,现在我们将简单地绘制网格线。

def redrawWindow(surface):surface.fill((0,0,0))  # Fills the screen with blackdrawGrid(surface)  # Will draw our grid linespygame.display.update()  # Updates the screen

4.绘制网格:现在将绘制代表20x20网格的线条。

def drawGrid(w, rows, surface):sizeBtwn = w // rows  # Gives us the distance between the linesx = 0  # Keeps track of the current xy = 0  # Keeps track of the current yfor l in range(rows):  # We will draw one vertical and one horizontal line each loopx = x + sizeBtwny = y + sizeBtwnpygame.draw.line(surface, (255,255,255), (x,0),(x,w))pygame.draw.line(surface, (255,255,255), (0,y),(w,y))

5.现在当我们运行程序时,我们可以看到网格线被画出来。

6.开始制作贪吃蛇:蛇对象将包含一个代表蛇身体的立方体列表。我们将把这些立方体存储在一个名为body的列表中,它将是一个类变量。我们还将有一个名为turns的类变量。为了开始蛇类,对__init__()方法并添加类变量。

class snake(object):body = []turns = {}def __init__(self, color, pos):self.color = colorself.head = cube(pos)  # The head will be the front of the snakeself.body.append(self.head)  # We will add head (which is a cube object)# to our body list# These will represent the direction our snake is movingself.dirnx = 0 self.dirny = 1

7.这款游戏最复杂的部分就是翻蛇。我们需要记住我们把我们的蛇转向了哪里和哪个方向,这样当头部后面的立方体到达那个位置时,我们也可以把它们转向。这就是为什么每当我们转向时,我们会将头部的位置添加到转向字典中,其中值是我们转向的方向。这样,当其他立方体到达这个位置时,我们就知道如何转动它们了。

class snake(object):...def move(self):for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()keys = pygame.key.get_pressed()for key in keys:if keys[pygame.K_LEFT]:self.dirnx = -1self.dirny = 0self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]elif keys[pygame.K_RIGHT]:self.dirnx = 1self.dirny = 0self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]elif keys[pygame.K_UP]:self.dirnx = 0self.dirny = -1self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]elif keys[pygame.K_DOWN]:self.dirnx = 0self.dirny = 1self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]for i, c in enumerate(self.body):  # Loop through every cube in our bodyp = c.pos[:]  # This stores the cubes position on the gridif p in self.turns:  # If the cubes current position is one where we turnedturn = self.turns[p]  # Get the direction we should turnc.move(turn[0],turn[1])  # Move our cube in that directionif i == len(self.body)-1:  # If this is the last cube in our body remove the turn from the dictself.turns.pop(p)else:  # If we are not turning the cube# If the cube reaches the edge of the screen we will make it appear on the opposite sideif c.dirnx == -1 and c.pos[0] <= 0: c.pos = (c.rows-1, c.pos[1])elif c.dirnx == 1 and c.pos[0] >= c.rows-1: c.pos = (0,c.pos[1])elif c.dirny == 1 and c.pos[1] >= c.rows-1: c.pos = (c.pos[0], 0)elif c.dirny == -1 and c.pos[1] <= 0: c.pos = (c.pos[0],c.rows-1)else: c.move(c.dirnx,c.dirny)  # If we haven't reached the edge just move in our current direction

8.画蛇:我们只需画出身体中的每个立方体对象。我们将在蛇身上做这个绘制()方法。

class snake(object):...def draw(self):for i, c in enumerate(self.body):if i == 0:  # for the first cube in the list we want to draw eyesc.draw(surface, True)  # adding the true as an argument will tell us to draw eyeselse:c.draw(surface)  # otherwise we will just draw a cube 

9.结束游戏当我们的蛇物体与自己碰撞时,我们就输了。为了检查这一点,我们在main()游戏循环中的功能。

for x in range(len(s.body)):if s.body[x].pos in list(map(lambda z:z.pos,s.body[x+1:])): # This will check if any of the positions in our body list overlapprint('Score: ', len(s.body))message_box('You Lost!', 'Play again...')s.reset((10,10))break

10.蛇类–重置()方法现在我们将对重置()方法。所有这些将会做的是重置蛇,这样我们可以在之后再次玩。

class snake():...def reset(self, pos):self.head = cube(pos)self.body = []self.body.append(self.head)self.turns = {}self.dirnx = 0self.dirny = 1

下面我们先看看效果:

总结

好了

Pygame实战:用 Python 写个贪吃蛇大冒险,保姆级教程。相关推荐

  1. 贪吃蛇博弈算法python_算法应用实践:如何用Python写一个贪吃蛇AI

    原标题:算法应用实践:如何用Python写一个贪吃蛇AI 前言 这两天在网上看到一张让人涨姿势的图片,图片中展示的是贪吃蛇游戏, 估计大部分人都玩过.但如果仅仅是贪吃蛇游戏,那么它就没有什么让人涨姿势 ...

  2. python写一个游戏多少代码-使用Python写一个贪吃蛇游戏实例代码

    我在程序中加入了分数显示,三种特殊食物,将贪吃蛇的游戏逻辑写到了SnakeGame的类中,而不是在Snake类中. 特殊食物: 1.绿色:普通,吃了增加体型 2.红色:吃了减少体型 3.金色:吃了回到 ...

  3. python游戏脚本实例-使用Python写一个贪吃蛇游戏实例代码

    我在程序中加入了分数显示,三种特殊食物,将贪吃蛇的游戏逻辑写到了SnakeGame的类中,而不是在Snake类中. 特殊食物: 1.绿色:普通,吃了增加体型 2.红色:吃了减少体型 3.金色:吃了回到 ...

  4. python小游戏编程实例-10分钟教你用Python写一个贪吃蛇小游戏,适合练手项目

    另外要注意:光理论是不够的.这里顺便总大家一套2020最新python入门到高级项目实战视频教程,可以去小编的Python交流.裙 :七衣衣九七七巴而五(数字的谐音)转换下可以找到了,还可以跟老司机交 ...

  5. python圆形按钮_小白用python写个贪吃蛇给小白看

    每个初学写代码的人可能都想在学习了一些基础知识后,希望能够写出一点拿得出手,秀的出来,但又在自己能力范围内的东西(没错,说的是我自己). 本人是个在读大学生,python小白,就想完成个多年前&quo ...

  6. 情人节用python写个贪吃蛇安慰自己

      这几天除了吃就是睡(不知道为啥,吃饱就想睡),从大年三十到现在感觉啥都没做,写个代码安慰安慰自己吧哈哈哈哈.给大家分享几部最近看的电影(要学英语的一定要get起来)--<彩虹照耀>&l ...

  7. python贪吃蛇控制台_如何用Python写一个贪吃蛇AI

    前言 这两天在网上看到一张让人涨姿势的图片,图片中展示的是贪吃蛇游戏, 估计大部分人都玩过.但如果仅仅是贪吃蛇游戏,那么它就没有什么让人涨姿势的地方了. 问题的关键在于,图片中的贪吃蛇真的很贪吃XD, ...

  8. python贪吃蛇_如何用Python写一个贪吃蛇?

    阅读文本大概需要 5 分钟 作者:Hawstein http://hawstein.com/2013/04/15/snake-ai/ 前言 这两天在网上看到一张让人涨姿势的图片,图片中展示的是贪吃蛇游 ...

  9. c++编写手机小游戏代码_玩过自己开发的贪吃蛇吗?点这里,教你用Python写一个贪吃蛇小游戏!(附源代码)...

    后台回复'0816',加入Python交流群~ 往日回顾:Python必读好书,这9本份量十足~ 本文代码的实现效果,获取源代码,请直接滑到文末~都说Python除了生孩子,什么都能干.咱们今天,就用 ...

最新文章

  1. Fiddler抓包使用教程-会话图标
  2. 最严谨的计算机语言p,用于PLC的华P语言编译器设计及实现.pdf
  3. java 封装 继承和多态
  4. linux elf命令,linux strings 命令——ELF文件格式与“链接和装载”
  5. 什么是latex科技排版系统,有对比word有何不同?
  6. Flex网站作品“妙句网”简化版推出(服务端为.Net WebService)
  7. java打印倒立直角三角形
  8. python中if的输入格式_Python基础之输出格式和If判断
  9. mysql中完成登陆注册_Flask+MySql实现用户登录注册
  10. 20190814 On Java8 第四章 运算符
  11. 用户故事拆分与MFQ
  12. 面试阿里,看这一篇就够了!
  13. POI Word表格复制行2种方式(copy()、手动复制行)
  14. 解决Win7的svchost进程占内存过大,计算机运行过慢的方法
  15. 2018年最值得投资的十大行业版图
  16. Cloud Chou's Tech Blog编译相关
  17. 群晖安装Calibre(含格式转换豆瓣元数据推送kindle)221211
  18. PS 2019 Mac版 自学入门系列(二)——区域选中
  19. RTX3060功耗多大 RTX3060配什么电源
  20. css的inherit属性

热门文章

  1. shell 小米system锁adb_忘记锁屏密码不用怕?支招小米手机解锁四种简单常用的方法...
  2. buildroot_buildroot-我对多平台发行版创作的经验
  3. docker操作时使用https时报错问题解决
  4. Peekaboo——项目系统设计与数据库设计
  5. 邓俊辉《数据结构》-向量学习笔记
  6. Android 多平台AR SDK 集成使用
  7. 大童保险确认获得投资:德弘资本等出资15亿元,获得约33%股权
  8. wifi情况下使用fiddler_如何对手机http进行抓包?Fiddler工具超好用
  9. 深信服技术认证之容灾与备份(一)
  10. mysql order field_mysql 使用order by filed,locate和instr自定义排序