使用Python写一个贪吃蛇游戏实例代码


Posted in Python onAugust 21, 2017

我在程序中加入了分数显示,三种特殊食物,将贪吃蛇的游戏逻辑写到了SnakeGame的类中,而不是在Snake类中。

特殊食物:

1.绿色:普通,吃了增加体型

2.红色:吃了减少体型

3.金色:吃了回到最初体型

4.变色食物:吃了会根据食物颜色改变蛇的颜色

#coding=UTF-8
from Tkinter import *
from random import randint
import tkMessageBox
class Grid(object):
  def __init__(self, master=None,height=16, width=24, offset=10, grid_width=50, bg="#808080"):
    self.height = height
    self.width = width
    self.offset = offset
    self.grid_width = grid_width
    self.bg = bg
    self.canvas = Canvas(master, width=self.width*self.grid_width+2*self.offset, height=self.height*self.grid_width+
                                              2*self.offset, bg=self.bg)
    self.canvas.pack(side=RIGHT, fill=Y)
  def draw(self, pos, color, ):
    x = pos[0] * self.grid_width + self.offset
    y = pos[1] * self.grid_width + self.offset
    #outline属性要与网格的背景色(self.bg)相同,要不然会很丑
    self.canvas.create_rectangle(x, y, x + self.grid_width, y + self.grid_width, fill=color, outline=self.bg)
class Food(object):
  def __init__(self, grid, color = "#23D978"):
    self.grid = grid
    self.color = color
    self.set_pos()
    self.type = 1
  def set_pos(self):
    x = randint(0, self.grid.width - 1)
    y = randint(0, self.grid.height - 1)
    self.pos = (x, y)
  def display(self):
    self.grid.draw(self.pos, self.color)
class Snake(object):
  def __init__(self, grid, color = "#000000"):
    self.grid = grid
    self.color = color
    self.body = [(8, 11), (8, 12), (8, 13)]
    self.direction = "Up"
    for i in self.body:
      self.grid.draw(i, self.color)
  #这个方法用于游戏重新开始时初始化贪吃蛇的位置
  def initial(self):
    while not len(self.body) == 0:
      pop = self.body.pop()
      self.grid.draw(pop, self.grid.bg)
    self.body = [(8, 11), (8, 12), (8, 13)]
    self.direction = "Up"
    self.color = "#000000"
    for i in self.body:
      self.grid.draw(i, self.color)
  #蛇像一个指定点移动
  def move(self, new):
    self.body.insert(0, new)
    pop = self.body.pop()
    self.grid.draw(pop, self.grid.bg)
    self.grid.draw(new, self.color)
  #蛇像一个指定点移动,并增加长度
  def add(self ,new):
    self.body.insert(0, new)
    self.grid.draw(new, self.color)
  #蛇吃到了特殊食物1,剪短自身的长度
  def cut_down(self,new):
    self.body.insert(0, new)
    self.grid.draw(new, self.color)
    for i in range(0,3):
      pop = self.body.pop()
      self.grid.draw(pop, self.grid.bg)
  #蛇吃到了特殊食物2,回到最初长度
  def init(self, new):
    self.body.insert(0, new)
    self.grid.draw(new, self.color)
    while len(self.body) > 3:
      pop = self.body.pop()
      self.grid.draw(pop, self.grid.bg)
   #蛇吃到了特殊食物3,改变了自身的颜色,纯属好玩
  def change(self, new, color):
    self.color = color
    self.body.insert(0, new)
    for item in self.body:
      self.grid.draw(item, self.color)
class SnakeGame(Frame):
  def __init__(self, master):
    Frame.__init__(self, master)
    self.grid = Grid(master)
    self.snake = Snake(self.grid)
    self.food = Food(self.grid)
    self.gameover = False
    self.score = 0
    self.status = ['run', 'stop']
    self.speed = 300
    self.grid.canvas.bind_all("<KeyRelease>", self.key_release)
    self.display_food()
    #用于设置变色食物
    self.color_c = ("#FFB6C1","#6A5ACD","#0000FF","#F0FFF0","#FFFFE0","#F0F8FF","#EE82EE","#000000","#5FA8D9","#32CD32")
    self.i = 0
    #界面左侧显示分数
    self.m = StringVar()
    self.ft1 = ('Fixdsys', 40, "bold")
    self.m1 = Message(master, textvariable=self.m, aspect=5000, font=self.ft1, bg="#696969")
    self.m1.pack(side=LEFT, fill=Y)
    self.m.set("Score:"+str(self.score))
  #这个方法用于游戏重新开始时初始化游戏
  def initial(self):
    self.gameover = False
    self.score = 0
    self.m.set("Score:"+str(self.score))
    self.snake.initial()
  #type1:普通食物 type2:减少2 type3:大乐透,回到最初状态 type4:吃了会变色
  def display_food(self):
    self.food.color = "#23D978"
    self.food.type = 1
    if randint(0, 40) == 5:
      self.food.color = "#FFD700"
      self.food.type = 3
      while (self.food.pos in self.snake.body):
        self.food.set_pos()
      self.food.display()
    elif randint(0, 4) == 2:
      self.food.color = "#EE82EE"
      self.food.type = 4
      while (self.food.pos in self.snake.body):
        self.food.set_pos()
      self.food.display()
    elif len(self.snake.body) > 10 and randint(0, 16) == 5:
      self.food.color = "#BC8F8F"
      self.food.type = 2
      while (self.food.pos in self.snake.body):
        self.food.set_pos()
      self.food.display()
    else:
      while (self.food.pos in self.snake.body):
        self.food.set_pos()
      self.food.display()
  def key_release(self, event):
    key = event.keysym
    key_dict = {"Up": "Down", "Down": "Up", "Left": "Right", "Right": "Left"}
    #蛇不可以像自己的反方向走
    if key_dict.has_key(key) and not key == key_dict[self.snake.direction]:
      self.snake.direction = key
      self.move()
    elif key == 'p':
      self.status.reverse()
  def run(self):
    #首先判断游戏是否暂停
    if not self.status[0] == 'stop':
      #判断游戏是否结束
      if self.gameover == True:
        message = tkMessageBox.showinfo("Game Over", "your score: %d" % self.score)
        if message == 'ok':
          self.initial()
      if self.food.type == 4:
        color = self.color_c[self.i]
        self.i = (self.i+1)%10
        self.food.color = color
        self.food.display()
        self.move(color)
      else:
        self.move()
    self.after(self.speed, self.run)
  def move(self, color="#EE82EE"):
    # 计算蛇下一次移动的点
    head = self.snake.body[0]
    if self.snake.direction == 'Up':
      if head[1] - 1 < 0:
        new = (head[0], 16)
      else:
        new = (head[0], head[1] - 1)
    elif self.snake.direction == 'Down':
      new = (head[0], (head[1] + 1) % 16)
    elif self.snake.direction == 'Left':
      if head[0] - 1 < 0:
        new = (24, head[1])
      else:
        new = (head[0] - 1, head[1])
    else:
      new = ((head[0] + 1) % 24, head[1])
      #撞到自己,设置游戏结束的标志位,等待下一循环
    if new in self.snake.body:
      self.gameover=True
    #吃到食物
    elif new == self.food.pos:
      if self.food.type == 1:
        self.snake.add(new)
      elif self.food.type == 2:
        self.snake.cut_down(new)
      elif self.food.type == 4:
        self.snake.change(new, color)
      else:
        self.snake.init(new)
      self.display_food()
      self.score = self.score+1
      self.m.set("Score:" + str(self.score))
    #什么都没撞到,继续前进
    else:
      self.snake.move(new)
if __name__ == '__main__':
  root = Tk()
  snakegame = SnakeGame(root)
  snakegame.run()
  snakegame.mainloop()

总结

以上所述是小编给大家介绍的使用Python写一个贪吃蛇游戏实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
python正则表达式match和search用法实例
Mar 26 Python
python中的装饰器详解
Apr 13 Python
Python自动生产表情包
Mar 17 Python
Python实现PS滤镜碎片特效功能示例
Jan 24 Python
python批量读取txt文件为DataFrame的方法
Apr 03 Python
浅析Python装饰器以及装饰器模式
May 28 Python
Django 迁移、操作数据库的方法
Aug 02 Python
python2和python3应该学哪个(python3.6与python3.7的选择)
Oct 01 Python
Python调用OpenCV实现图像平滑代码实例
Jun 19 Python
python怎么自定义捕获错误
Jun 29 Python
Python定时任务APScheduler安装及使用解析
Aug 07 Python
Python修改DBF文件指定列
Dec 19 Python
virtualenv实现多个版本Python共存
Aug 21 #Python
基于Python对象引用、可变性和垃圾回收详解
Aug 21 #Python
python 垃圾收集机制的实例详解
Aug 20 #Python
python 实现tar文件压缩解压的实例详解
Aug 20 #Python
详解Python 序列化Serialize 和 反序列化Deserialize
Aug 20 #Python
Python中input与raw_input 之间的比较
Aug 20 #Python
Python 基础教程之str和repr的详解
Aug 20 #Python
You might like
PHP针对JSON操作实例分析
2015/01/12 PHP
PHP中substr_count()函数获取子字符串出现次数的方法
2016/01/07 PHP
php微信公众账号开发之前五个坑(一)
2016/09/18 PHP
Laravel框架实现的使用smtp发送邮件功能示例
2019/03/12 PHP
JQuery里选择超链接的实现代码
2011/05/22 Javascript
SinaEditor使用方法详解
2013/12/28 Javascript
jQuery+ajax实现鼠标单击修改内容的方法
2014/06/27 Javascript
编写高性能Javascript代码的N条建议
2015/10/12 Javascript
javascript实现抽奖程序的简单实例
2016/06/07 Javascript
ES6 Proxy实现Vue的变化检测问题
2019/06/11 Javascript
微信小程序JS加载esmap地图的实例详解
2019/09/04 Javascript
Vue 使用Props属性实现父子组件的动态传值详解
2019/11/13 Javascript
js中火星坐标、百度坐标、WGS84坐标转换实现方法示例
2020/03/02 Javascript
[01:02:47]EG vs Secret 2019国际邀请赛淘汰赛 胜者组 BO3 第一场 8.21.mp4
2020/07/19 DOTA
Python中几个比较常见的名词解释
2015/07/04 Python
python数据结构之图深度优先和广度优先实例详解
2015/07/08 Python
使用Python求解最大公约数的实现方法
2015/08/20 Python
python 回调函数和回调方法的实现分析
2016/03/23 Python
Django objects.all()、objects.get()与objects.filter()之间的区别介绍
2017/06/12 Python
通过python将大量文件按修改时间分类的方法
2018/10/17 Python
对python中的try、except、finally 执行顺序详解
2019/02/18 Python
Python 操作 ElasticSearch的完整代码
2019/08/04 Python
Django错误:TypeError at / 'bool' object is not callable解决
2019/08/16 Python
Python数据处理篇之Sympy系列(五)---解方程
2019/10/12 Python
Python for循环与getitem的关系详解
2020/01/02 Python
Python for循环通过序列索引迭代过程解析
2020/02/07 Python
PYQT5 vscode联合操作qtdesigner的方法
2020/03/24 Python
在pycharm中debug 实时查看数据操作(交互式)
2020/06/09 Python
爬虫代理的cookie如何生成运行
2020/09/22 Python
French Connection官网:女装、男装及家居用品
2019/03/18 全球购物
培训研修方案
2014/06/06 职场文书
2014年法制宣传日活动方案
2014/11/02 职场文书
土建施工员岗位职责
2015/04/11 职场文书
2015年房产销售工作总结范文
2015/05/22 职场文书
Mybatis-plus配置分页插件返回统一结果集
2022/06/21 Java/Android
uniapp引入支付宝原生扫码插件步骤详解
2022/07/23 Javascript