python语言实现贪吃蛇游戏

本文实例为大家分享了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()

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

(0)

相关推荐

  • 利用python实现简易版的贪吃蛇游戏(面向python小白)

    引言 作为python 小白,总是觉得自己要做好百分之二百的准备,才能开始写程序.以至于常常整天在那看各种语法教程,学了几个月还是只会print('hello world'). 这样做效率太低,正确的做法,是到身边找问题,然后编程实现.比如说,我学了高等数学,我是不是应该考虑下如何去用编程实现求导或者积分操作,如果想不出怎么办,是不是应该 baidu 一下,别人是如何实现数值积分或是符号积分的.我们每天买东西都要用到加减甚至乘除,那么我是否能编写个简单的计算器,如果命令行太丑的话,我是否能够快速

  • 教你一步步利用python实现贪吃蛇游戏

    0 引言 前几天,星球有人提到贪吃蛇,一下子就勾起了我的兴趣,毕竟在那个Nokia称霸的年代,这款游戏可是经典中的经典啊!而用Python(蛇)玩Snake(贪吃蛇),那再合适不过了

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

    我在程序中加入了分数显示,三种特殊食物,将贪吃蛇的游戏逻辑写到了SnakeGame的类中,而不是在Snake类中. 特殊食物: 1.绿色:普通,吃了增加体型 2.红色:吃了减少体型 3.金色:吃了回到最初体型 4.变色食物:吃了会根据食物颜色改变蛇的颜色 #coding=UTF-8 from Tkinter import * from random import randint import tkMessageBox class Grid(object): def __init__(self,

  • Python贪吃蛇游戏编写代码

    最近在学Python,想做点什么来练练手,命令行的贪吃蛇一般是C的练手项目,但是一时之间找不到别的,就先做个贪吃蛇来练练简单的语法. 由于Python监听键盘很麻烦,没有C语言的kbhit(),所以这条贪吃蛇不会自己动,运行效果如下: 要求:用#表示边框,用*表示食物,o表示蛇的身体,O表示蛇头,使用wsad来移动 Python版本:3.6.1 系统环境:Win10 类: board:棋盘,也就是游戏区域 snake:贪吃蛇,通过记录身体每个点来记录蛇的状态 game:游戏类 本来还想要个foo

  • python实现贪吃蛇游戏

    本文实例为大家分享了python实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下 本文稍作改动,修复一些bug,原文链接:python实现贪吃蛇游戏 #!/usr/bin/env python #__*__ coding: utf-8 __*__ import pygame,sys,time,random from pygame.locals import * redColour = pygame.Color(255,0,0) blackColour = pygame.Color(0,0,0)

  • python贪吃蛇游戏代码

    本文实例为大家分享了python贪吃蛇游戏的具体代码,供大家参考,具体内容如下 贪吃蛇游戏截图: 首先安装pygame,可以使用pip安装pygame: pip install pygame 运行以下代码即可: #!/usr/bin/env python import pygame,sys,time,random from pygame.locals import * # 定义颜色变量 redColour = pygame.Color(255,0,0) blackColour = pygame.

  • python实现贪吃蛇游戏源码

    本文实例为大家分享了python实现贪吃蛇的具体代码,供大家参考,具体内容如下 import pygame import sys import random SCREEN_X=600 SCREEN_Y=600 class Snake(object): def __init__(self): self.direction=pygame.K_RIGHT self.body = [] for i in range(5): self.addnode() def addnode(self): left,

  • Python 实现 贪吃蛇大作战 代码分享

    感觉游戏审核新政实施后,国内手游市场略冷清,是不是各家的新游戏都在排队等审核.媒体们除了之前竞相追捧<Pokemon Go>热闹了一把,似乎也听不到什么声音了.直到最近几天,突然听见好几人都提到同一个游戏,网上还有人表示朋友圈被它刷屏了.(不过现在微信已经悍然屏蔽了它的分享) 这个游戏就是现在iOS免费榜排名第一的<贪吃蛇大作战>.一个简单到不行的游戏,也不知道怎么就火了.反正一款游戏火了,各路媒体.专家总能说出种种套路来,所以我就不发表意见了.不过这实在是一个挺好实现的游戏,于是

  • python实现贪吃蛇小游戏

    关于编写游戏,是博主非常向往的东西(博主喜爱游戏),编写游戏得一步一步的走!今天我简单的编写一下非常经典的游戏贪吃蛇!!!! 效果图: 首先引入pygame模块 pip install pygame 关于编写贪吃蛇有如下几个步骤!依次思考 1.设置背景大小,即游戏框大小,---像素(px) 2.设置颜色,蛇的颜色,背景颜色,豆子的颜色 #pygame游戏库,sys操控python运行的环境 import pygame,sys,random #这个模块包含所有pygame所使用的常亮 from p

  • Python写的贪吃蛇游戏例子

    第一次用Python写这种比较实用且好玩的东西,权当练手吧 游戏说明: * P键控制"暂停/开始"* 方向键控制贪吃蛇的方向 源代码如下: 复制代码 代码如下: from Tkinter import *import tkMessageBox,sysfrom random import randint class Grid(object):    def __init__(self,master=None,window_width=800,window_height=600,grid_

随机推荐