python语言实现贪吃蛇游戏


Posted in Python onNovember 13, 2020

本文实例为大家分享了python实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下

新手自学python(简易贪吃蛇代码)
环境python3.7

刚刚大学毕业进入工作岗位,发现同事基本都会写py脚本,于是自学了一下,并写了一个简单的贪吃蛇代码,我觉得写的还是比较容易看懂,适合新手接触python。

# -*- coding: utf-8 -*-
import tkinter as tk 
# 使用Tkinter前需要先导入
import tkinter.messagebox
import pickle
import random
import time

# 第1步,实例化object,建立窗口window
window = tk.Tk() 
# 第2步,给窗口的可视化起名字
window.title('Greedy snake')
# 第3步,设定窗口的大小(长 * 宽)
# window.geometry('1004x504') # 这里的乘是小x

# 第5步,创建一个主frame,长在主window窗口上
frame = tk.Frame(window, bg = 'blue', bd = 2, relief = tk.FLAT)
frame.pack(side = 'left')
#当前框架被选中,意思是键盘触发,只对这个框架有效
frame.focus_set()
Labellist = [] #存放所有方块的label
Blocklist = [] #存放背景方块的值 1:被占用 0:空闲
Snakelist = [] #存放snake的坐标
height = 15
width = 20
#snack前进方向
left = 0
right = 1
up = 2
down =3
pause = 0
start = 1
class App(tk.Frame): 
 def __init__(self,master):  
  self.window = master  
  tk.Frame.__init__(self)  
  master.bind('<Up>',self.Up)  
  master.bind('<Left>',self.Left)  
  master.bind('<Right>',self.Right)  
  master.bind('<Down>',self.Down)  
  master.bind('<p>',self.Pause)  
  master.bind('<s>',self.Start)  
  master.bind('<r>',self.Restart)  
  self.Init_snake() #初始化界面方法
  self.time = 1000  
  self.Onetime()     
 def Up(self, event):  
  if self.Istart:   
   self.direction = up 
 def Down(self, event):  
  if self.Istart:   
   self.direction = down 
 def Left(self, event):  
  if self.Istart:   
   self.direction = left 
 def Right(self, event):  
  if self.Istart:   
   self.direction = right
 def Init_snake(self):  
  del Labellist[:]  
  del Blocklist[:]  
  del Snakelist[:]    
  #初始化背景方块  
  LabelRowList = []  
  BlockRowlist = []  
  c = r = 0  
  for k in range(width*height):   
   LN=tk.Label(frame,text = ' ', bg = 'black', fg = 'white', relief = tk.FLAT, bd = 4)   
   LN.grid(row=r,column=c,sticky=tk.N+tk.E+tk.S+tk.W)   
   LabelRowList.append(LN)   
   BlockRowlist.append(0)   
   c=c+1 
   if c>=20:
    r=r+1
    c=0    
    Labellist.append(LabelRowList)    
    Blocklist.append(BlockRowlist)    
    LabelRowList = []    
    BlockRowlist = []  
  #初始化snake  
  self.Istart = 0  
  self.direction = left
  self.direction_last = left
  self.overflag = 0 
  #snake head的初始位置  
  self.x = 7  
  self.y = 8  
  #snake tail的初始位置  
  self.x_tail = 7  
  self.y_tail = 10  
  Snakelist.append((7,8))  
  Snakelist.append((7,9))  
  Snakelist.append((7,10))  
  self.snakelen = len(Snakelist)


  Blocklist[self.x][self.y] = 1  
  Blocklist[self.x][self.y+1] = 1  
  Blocklist[self.x][self.y+2] = 1  
  Labellist[self.x][self.y].config(bg = 'green', relief = tk.RAISED)  
  Labellist[self.x][self.y+1].config(bg = 'white', relief = tk.RAISED)  
  Labellist[self.x][self.y+2].config(bg = 'white', relief = tk.RAISED)  
  #初始化food  
  self.food_x = random.randint(0,14)  
  self.food_y = random.randint(0,19)  
  while Blocklist[self.food_x][self.food_y] == 1:   
   self.food_x = random.randint(0,14)   
   self.food_y = random.randint(0,19)     
  Blocklist[self.food_x][self.food_y] = 1  
  Labellist[self.food_x][self.food_y].config(bg = 'red', relief = tk.RIDGE)
 def Pause(self, event):  
  self.Istart = pause 
 def Start(self, event):  
  self.Istart = start 
 def Restart(self, event):  
  self.Init_snake()
 def Onetime(self): #每1000ms做一次界面刷新  
  if self.Istart and self.overflag == 0: 
   if (self.direction_last == down and self.direction == up )or(self.direction_last == up and self.direction == down )or(self.direction_last ==left and self.direction == right )or(self.direction_last ==right and self.direction == left ):
    self.direction = self.direction_last
   self.direction_last = self.direction 
   x0 = self.x   
   y0 = self.y   
   if self.direction == left:    
    if x0 == self.food_x and y0-1 == self.food_y:          
     Labellist[x0][y0-1].config(bg = 'green', relief = tk.RAISED)     
     Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)
     self.food_x = random.randint(0,14)     
     self.food_y = random.randint(0,19)     
     while Blocklist[self.food_x][self.food_y] == 1:      
      self.food_x = random.randint(0,14)      
      self.food_y = random.randint(0,19)     
     Blocklist[self.food_x][self.food_y] = 1     
     Labellist[self.food_x][self.food_y].config(bg = 'red', relief = tk.RIDGE)
     self.snakelen += 1     
     Snakelist.insert(0,(x0,y0-1))      
     self.x = x0     
     self.y = y0 - 1    
    elif (x0>=0 and x0<height and y0-1>=0 and y0-1<width and Blocklist[x0][y0-1] == 0) or (self.x_tail == x0 and self.y_tail == y0 - 1):               
     Blocklist[self.x_tail][self.y_tail] = 0     
     Labellist[self.x_tail][self.y_tail].config(bg = 'black', relief = tk.FLAT)     
     Blocklist[x0][y0-1] = 1     
     Labellist[x0][y0-1].config(bg = 'green', relief = tk.RAISED)     
     Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)           
     del Snakelist[self.snakelen - 1]     
     Snakelist.insert(0,(x0,y0-1))      
     self.x = x0     
     self.y = y0 - 1     
     self.x_tail = Snakelist[self.snakelen - 1][0]     
     self.y_tail = Snakelist[self.snakelen - 1][1]    
    else:     
     tk.messagebox.showinfo(title = 'snake', message = 'game over!!!')     
     self.overflag = 1     
   elif self.direction == up:    
    if x0-1 == self.food_x and y0 == self.food_y:           
     Labellist[x0-1][y0].config(bg = 'green', relief = tk.RAISED)     
     Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)
     self.food_x = random.randint(0,14)     
     self.food_y = random.randint(0,19)     
     while Blocklist[self.food_x][self.food_y] == 1:      
      self.food_x = random.randint(0,14)      
      self.food_y = random.randint(0,19)     
     Blocklist[self.food_x][self.food_y] = 1     
     Labellist[self.food_x][self.food_y].config(bg = 'red', relief = tk.RIDGE) 
     self.snakelen += 1     
     Snakelist.insert(0,(x0-1,y0))      
     self.x = x0 - 1     
     self.y = y0 
    elif (x0-1 >=0 and x0-1<height and y0>=0 and y0<width and Blocklist[x0-1][y0] == 0) or (self.x_tail == x0-1 and self.y_tail == y0):          
     Blocklist[self.x_tail][self.y_tail] = 0     
     Labellist[self.x_tail][self.y_tail].config(bg = 'black', relief = tk.FLAT)     
     Blocklist[x0-1][y0] = 1     
     Labellist[x0-1][y0].config(bg = 'green', relief = tk.RAISED)     
     Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)
     del Snakelist[self.snakelen - 1]     
     Snakelist.insert(0,(x0 - 1,y0))      
     self.x = x0 - 1     
     self.y = y0     
     self.x_tail = Snakelist[self.snakelen - 1][0]     
     self.y_tail = Snakelist[self.snakelen - 1][1]    
    else:     
     tk.messagebox.showinfo(title = 'snake', message = 'game over!!!')     
     self.overflag = 1   
   elif self.direction == down:    
    if x0+1 == self.food_x and y0 == self.food_y:          
     Labellist[x0+1][y0].config(bg = 'green', relief = tk.RAISED)     
     Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)
     self.food_x = random.randint(0,14)     
     self.food_y = random.randint(0,19)     
     while Blocklist[self.food_x][self.food_y] == 1:      
      self.food_x = random.randint(0,14)      
      self.food_y = random.randint(0,19)     
     Blocklist[self.food_x][self.food_y] = 1     
     Labellist[self.food_x][self.food_y].config(bg = 'red', relief = tk.RIDGE) 
     self.snakelen += 1     
     Snakelist.insert(0,(x0+1,y0))      
     self.x = x0 + 1     
     self.y = y0 
    elif (x0+1 >=0 and x0+1 <height and y0>=0 and y0<width and Blocklist[x0+1][y0] == 0) or (self.x_tail == x0+1 and self.y_tail == y0):               
     Blocklist[self.x_tail][self.y_tail] = 0     
     Labellist[self.x_tail][self.y_tail].config(bg = 'black', relief = tk.FLAT)     
     Blocklist[x0+1][y0] = 1     
     Labellist[x0+1][y0].config(bg = 'green', relief = tk.RAISED)     
     Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED) 
     del Snakelist[self.snakelen - 1]     
     Snakelist.insert(0,(x0 + 1,y0))      
     self.x = x0 + 1     
     self.y = y0     
     self.x_tail = Snakelist[self.snakelen - 1][0]     
     self.y_tail = Snakelist[self.snakelen - 1][1]    
    else:     
     tk.messagebox.showinfo(title = 'snake', message = 'game over!!!')     
     self.overflag = 1   
   elif self.direction == right:    
    if x0 == self.food_x and y0+1 == self.food_y:          
     Labellist[x0][y0+1].config(bg = 'green', relief = tk.RAISED)     
     Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED)
     self.food_x = random.randint(0,14)     
     self.food_y = random.randint(0,19)     
     while Blocklist[self.food_x][self.food_y] == 1:      
      self.food_x = random.randint(0,14)      
      self.food_y = random.randint(0,19)     
     Blocklist[self.food_x][self.food_y] = 1     
     Labellist[self.food_x][self.food_y].config(bg = 'red', relief = tk.RIDGE) 
     self.snakelen += 1     
     Snakelist.insert(0,(x0,y0 + 1))      
     self.x = x0     
     self.y = y0 + 1 
    elif (x0>=0 and x0<height and y0+1>=0 and y0+1<width and Blocklist[x0][y0+1] == 0) or (self.x_tail == x0 and self.y_tail == y0+1):              
     Blocklist[self.x_tail][self.y_tail] = 0     
     Labellist[self.x_tail][self.y_tail].config(bg = 'black', relief = tk.FLAT)     
     Blocklist[x0][y0+1] = 1     
     Labellist[x0][y0+1].config(bg = 'green', relief = tk.RAISED)     
     Labellist[x0][y0].config(bg = 'white', relief = tk.RAISED) 
     del Snakelist[self.snakelen - 1]     
     Snakelist.insert(0,(x0,y0 + 1))      
     self.x = x0     
     self.y = y0 + 1     
     self.x_tail = Snakelist[self.snakelen - 1][0]     
     self.y_tail = Snakelist[self.snakelen - 1][1]    
    else:     
     tk.messagebox.showinfo(title = 'snake', message = 'game over!!!')     
     self.overflag = 1  
  self.after(self.time,self.Onetime)
def Start_Stop(): 
 app.Istart = 1 - app.Istart 
def Restart(): 
 app.Restart(0) 
#主菜单
mainmenu = tk.Menu(window)
window['menu'] = mainmenu
#二级菜单:game
gamemenu=tk.Menu(mainmenu)
mainmenu.add_cascade(label='游戏',menu=gamemenu)
gamemenu.add_command(label = '开始/暂停',command=Start_Stop)
gamemenu.add_command(label = '重置',command=Restart)
gamemenu.add_command(label = '退出',command=window.quit)
app = App(window)  
window.mainloop()

更多有趣的经典小游戏实现专题,分享给大家:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
巧用Python装饰器 免去调用父类构造函数的麻烦
May 18 Python
python创建线程示例
May 06 Python
python实现一个简单的并查集的示例代码
Mar 19 Python
Python多线程应用于自动化测试操作示例
Dec 06 Python
python flask解析json数据不完整的解决方法
May 26 Python
详解使用python绘制混淆矩阵(confusion_matrix)
Jul 14 Python
Python 使用 docopt 解析json参数文件过程讲解
Aug 13 Python
Python3.6 中的pyinstaller安装和使用教程
Mar 16 Python
python网络编程之五子棋游戏
May 14 Python
Python-opencv实现红绿两色识别操作
Jun 04 Python
python中format函数如何使用
Jun 22 Python
如何利用Python给自己的头像加一个小国旗(小月饼)
Oct 02 Python
Python使用struct处理二进制(pack和unpack用法)
Nov 12 #Python
python切割图片的示例
Nov 12 #Python
教你使用Sublime text3搭建Python开发环境及常用插件安装另分享Sublime text3最新激活注册码
Nov 12 #Python
Django执行源生mysql语句实现过程解析
Nov 12 #Python
Django Model层F,Q对象和聚合函数原理解析
Nov 12 #Python
在Python中字典按值排序的实现方法
Nov 12 #Python
Sublime Text3最新激活注册码分享适用2020最新版 亲测可用
Nov 12 #Python
You might like
PHP自动生成月历代码
2006/10/09 PHP
PHP 中文乱码解决办法总结分析
2009/07/30 PHP
PHP获取数组长度或某个值出现次数的方法
2015/02/11 PHP
JavaScript 编程引入命名空间的方法与代码
2007/08/13 Javascript
jquery 操作DOM的基本用法分享
2012/04/05 Javascript
将json对象转换为字符串的方法
2014/02/20 Javascript
JQuery做的一个简单的点灯游戏分享
2014/07/16 Javascript
浅谈Javascript中匀速运动的停止条件
2014/12/19 Javascript
基于Jquery实现仿百度百科右侧导航代码附源码下载
2015/11/27 Javascript
Node.js环境下JavaScript实现单链表与双链表结构
2016/06/12 Javascript
多种jQuery绑定事件的实现方式
2016/06/13 Javascript
Jquery Easyui进度条组件Progress使用详解(8)
2020/03/26 Javascript
详细讲解vue2+vuex+axios
2017/05/27 Javascript
vue.js学习之UI组件开发教程
2017/07/03 Javascript
详解Vue学习笔记入门篇之组件的内容分发(slot)
2017/07/17 Javascript
小程序实现列表删除功能
2018/10/30 Javascript
记一次vue-webpack项目优化实践详解
2019/02/17 Javascript
小程序转发探索示例
2019/02/19 Javascript
vue+element项目中过滤输入框特殊字符小结
2019/08/07 Javascript
js中位数不足自动补位扩展padLeft、padRight实现代码
2020/04/06 Javascript
JavaScript中CreateTextFile函数
2020/08/30 Javascript
python实现socket端口重定向示例
2014/02/10 Python
python去除文件中空格、Tab及回车的方法
2016/04/12 Python
详解python uiautomator2 watcher的使用方法
2019/09/09 Python
Python爬虫Scrapy框架CrawlSpider原理及使用案例
2020/11/20 Python
美国最大的城市服装和运动鞋零售商:Jimmy Jazz
2016/11/19 全球购物
世界最大的票务市场:viagogo
2017/02/16 全球购物
汽车专业大学生职业生涯规划范文
2014/01/07 职场文书
魅力教师事迹材料
2014/01/10 职场文书
埃及王子观后感
2015/06/16 职场文书
2016年春季运动会广播稿
2015/08/19 职场文书
2019客服个人年终工作总结范文
2019/07/08 职场文书
创业计划书之餐饮
2019/09/02 职场文书
用React Native制作一个简单的游戏引擎
2021/05/27 Javascript
CSS巧用渐变实现高级感背景光动画
2021/12/06 HTML / CSS
win10忘记pin密码登录不了怎么办?win10忘记pin密码登不进去的解决方法
2022/07/07 数码科技