我想使用Python 3
在Tkinter
创建一个蛇游戏。一切都有效,除了有时候我的苹果(一个红色的长方形)在蛇吃它之前消失了。我尝试使用print
来监控删除方法,但似乎它确实可以正常工作......
这是我的代码:
from tkinter import *
import time
from random import randint
class Snake(Tk):
def __init__(self):
Tk.__init__(self)
self.WIDTH = 600
self.HEIGHT = 600
def init(self):
self.kp = [(30,0),(30,0),(30,0),(30,0)]
self.vx = 30
self.vy = 0
self.x , self.y = 300 , 300
self.taille = 30
self.queue = 1
self.nb = 1
self.pos = [(300,300)]
def init_graph(self):
self.cnv = Canvas(self,width = self.WIDTH, height = self.HEIGHT , bg = 'white')
self.cnv.pack()
self.cnv.create_rectangle(self.x , self.y ,self.x+ self.taille ,self.y + self.taille , fill = 'black',tag='1')
self.new_pomme()
self.score()
def new_pomme(self):
self.pomme = [randint(0,19)*30,randint(0,19)*30]
self.cnv.create_rectangle(self.pomme[0],self.pomme[1],self.pomme[0] + self.taille,self.pomme[1] + self.taille, fill = 'red',tag = 'pomme')
def maj(self):
self.kp.append((self.vx,self.vy))
self.nb += 1
if [self.x,self.y] == self.pomme:
print("Pomme ! ",self.pomme)
self.cnv.delete('pomme')
self.new_pomme()
self.queue += 1
self.text.destroy()
self.score()
else:
self.cnv.delete(str(self.nb-self.queue))
del self.pos[0]
self.x += self.vx
self.y += self.vy
if (self.x,self.y) in self.pos:
self.perdu()
else:
self.pos.append((self.x,self.y))
self.cnv.create_rectangle(self.x , self.y ,self.x+ self.taille ,self.y + self.taille , fill = 'black', tag =str(self.nb))
print(round(time.clock(),2))
if self.kp[-1] == self.kp[-2]:
if len(self.kp) > 10:
for i in range(5):
del self.kp[i]
self.after(500,self.maj)
def bouger(self):
self.bind("<Up>", self.haut)
self.bind("<Down>", self.bas)
self.bind("<Left>", self.gauche)
self.bind("<Right>", self.droite)
self.mainloop()
def haut(self,event):
self.vy = -30
self.vx = 0
self.maj()
def bas(self,event):
self.vy = 30
self.vx = 0
self.maj()
def gauche(self,event):
self.vy = 0
self.vx = -30
self.maj()
def droite(self,event):
self.vy = 0
self.vx = 30
self.maj()
def perdu(self):
print("Perdu !")
self.text_perdu = Label(self,text='Perdu ! Score final : ' + str(self.queue-1))
self.text_perdu.pack(side = TOP)
Button(self,text='Recommencer',command=jeu()).pack(side = BOTTOM)
def score(self):
self.text = Label(self,text='Score : ' +str(self.queue-1))
self.text.pack(side = BOTTOM)
def jeu():
snake = Snake()
snake.init()
snake.init_graph()
snake.bouger()
snake.mainloop()
jeu()
请注意:复制/粘贴存在缩进错误,所有类中只有一个类和一个fuction jeu()。所有其余的都在课堂内
答案 0 :(得分:0)
每次使用“移动”而不是销毁和创建新的移动。一个简单的例子。
import Tkinter as tk
import time
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
rc1 = canvas.create_rectangle(20, 260, 120, 360,
outline='white', fill='blue')
rc2 = canvas.create_rectangle(20, 10, 120, 110,
outline='white', fill='red')
y = x = 5
for ctr in range(50):
time.sleep(0.025)
canvas.move(rc1, x, -y)
canvas.move(rc2, x, y)
canvas.update()
root.mainloop()