用纸做五子棋游戏很简单。

#!/usr/bin/python

来自Tkinter import *

随机导入

蛇类(框架):

def __init__(self,master=None):

框架。__init__(自身,主)

self.body = [(0,0)]

self.bodyid = []

self.food = [ -1,-1 ]

self.foodid = -1

self.gridcount = 10

self.size = 500

self.di = 3

自身速度= 500

self.top = self.winfo_toplevel()

self.top.resizable(False,False)

self.grid()

self.canvas = Canvas(self)

self.canvas.grid()

self . canvas . config(width = self . size,height=self.size,relief=RIDGE)

self.drawgrid()

s = self.size/self.gridcount

id = self . canvas . create _ rectangle(self . body[0][0]* s,self.body[0][1]*s,

(self.body[0][0]+1)*s,(self . body[0][1]+1)* s,fill="yellow ")

self.bodyid.insert(0,id)

self . bind _ all(" & lt;KeyRelease >,self.keyrelease)

self.drawfood()

self.after(self.speed,self.drawsnake)

定义绘图网格(自身):

s = self.size/self.gridcount

对于范围内的I(0,self.gridcount+1):

self.canvas.create_line(i*s,0,i*s,self.size)

self.canvas.create_line(0,i*s,self.size,i*s)

def drawsnake(自身):

s = self.size/self.gridcount

head = self.body[0]

new = [head[0],head[1]]

如果self.di == 1:

new[1]=(head[1]-1)% self . grid count

elif self.di == 2:

new[0]=(head[0]+1)% self . grid count

elif self.di == 3:

new[1]=(head[1]+1)% self . grid count

否则:

new[0]=(head[0]-1)% self . grid count

next = ( new[0],new[1])

如果在self.body中下一个:

退出()

elif next == (self.food[0],self.food[1]):

self.body.insert(0,下一个)

self.bodyid.insert(0,self.foodid)

self.drawfood()

否则:

tail = self.body.pop()

id = self.bodyid.pop()

self.canvas.move(id,(next[0]-tail[0])*s,(next[1]-tail[1])*s)

self.body.insert(0,下一个)

self.bodyid.insert(0,id)

self.after(self.speed,self.drawsnake)

def drawfood(自身):

s = self.size/self.gridcount

x = random.randrange(0,self.gridcount)

y = random.randrange(0,self.gridcount)

while (x,y) in self.body:

x = random.randrange(0,self.gridcount)

y = random.randrange(0,self.gridcount)

id = self . canvas . create _ rectangle(x * s,y*s,(x+1)*s,(y+1)*s,fill="yellow ")

self.food[0] = x

self.food[1] = y

self.foodid = id

def按键释放(自身,事件):

if event.keysym == "Up "和self.di!= 3:

self.di = 1

elif event.keysym == "Right "和self.di!=4:

self.di = 2

elif event.keysym == "Down "和self.di!= 1:

self.di = 3

elif event.keysym == "Left "和self.di!= 2:

self.di = 4

app = snake()

app.master.title("贪婪的蛇")

App.mainloop()蛇