Código fuente del juego Puthon
Desde Tkinter import *
Importación aleatoria
Snake (framework):
def __init__ ( self, master=Ninguno):
Marco.
__init__(self, main)
self.body = [(0, 0)]
self.bodyid = []
self.food = [ - 1, -1 ]
self.foodid = -1
self.gridcount = 10
self.size = 500
self .di = 3
Autovelocidad = 500
self.top = self.winfo_toplevel()
self.top.resizable(False, False)
p>self.grid()
self.canvas = Lienzo(self)
self.canvas.grid()
self . canvas config(ancho = self. tamaño, alto = self.size, relieve = RIDGE)
self.drawgrid()
s = self.size/self.gridcount<. /p>
id = self . lienzo . crear _ rectángulo(self . body[0][0]*s, self.body[0][1]*s,
(self. cuerpo[0 ][0]+1)*s, (self . cuerpo[0][1]+1)* s, fill="amarillo ")
self.bodyid.insert(0, id)
self . bind_all(" <KeyRelease>, self.keyrelease)
self.drawfood()
self.after(self.speed, self.drawsnake)
Definir cuadrícula de dibujo (self):
s = self.size/self.gridcount
Para 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(self):
s = self.size/self.gridcount
cabeza = self .body[0 ]
nuevo = [cabeza[0], cabeza[1]]
si self.di == 1:
nuevo[1 ]=(cabeza [1]-1)% self . recuento de cuadrícula
elif self.di == 2:
new[0]=(head[0]+1) % self . count
elif self.di == 3:
new[1]=(head[1]+1)% self . grid count
De lo contrario:
nuevo[0]=(head[0]-1)% self . recuento de cuadrícula
siguiente = (nuevo[0], nuevo[1])
Si es el siguiente en self.body:
Salir()
elif siguiente == (self.food[0], self.food[1]):
auto.cuerpo.insertar(
0, siguiente)
self.bodyid.insert(0, self.foodid)
self.drawfood()
De lo contrario:
cola = self.body.pop()
id = self.bodyid.pop()
self.canvas.move(id, (siguiente[0]-tail[ 0 ])*s, (siguiente[1]-tail[1])*s)
self.body.insert(0, siguiente)
self.bodyid.insert (0 , id)
self.after(self.speed, self.drawsnake)
def drawfood(self):
s = self.size/ self. gridcount
x = random.randrange(0, self.gridcount)
y = random.randrange(0, self.gridcount)
mientras ( x, y) en self.body:
x = random.randrange(0, self.gridcount)
y = random.randrange(0, self.gridcount)
id = self lienzo. crear _ rectángulo(x * s, y*s, (x+1)*s, (y+1)*s, fill="amarillo ")
self. .food[0] = x
self.food[1] = y
self.foodid = id
liberación de clave def (self, evento):
if event.keysym == "Arriba "y self.di! = 3:
self.di = 1
elif event.keysym == "Correcto" y self.di! =4:
self.di = 2
elif event.keysym == "Abajo" y self.di! = 1:
self.di = 3
elif event.keysym == "Izquierda" y self.di! = 2:
self.di = 4
app = serpiente()
app.master.title("Serpiente codiciosa")
App.mainloop() serpiente