下面是我的“Snake 项目”的 Python 代码(使用 Turtle 和 Tkinter)。
该程序的目的是创建一个海龟链,称为追随者,它们相互跟随,链中的第一只海龟跟随一个特殊的海龟:领导者。领导者本身跟随鼠标的移动。 当按下
“Del”键时,它会从链中删除最后一个追随者。 由于无法从内存中物理删除追随者,因此当删除链中的最后一个追随者时,它会被添加到包含所有
“已删除”追随者的另一个链的第一个位置。
当需要将新的Follower
添加到链中时,我们首先检查已删除列表中是否有,如果有则重用;否则,必须创建一个新的。
但是,使用我的Python代码,当我单击“Del”键时,即使按了几次,也只会删除最后一个Turtle。 (正常情况下,每次都会删除最后一个关注者)。
我认为问题与方法有关:
remove_last_follower(self, event)
“领导者”班级。
您知道如何解决这个问题吗?非常感谢您的支持。
我的Python代码:
from turtle import Turtle, Screen, window_width, window_height # Importation du module Turtle
D = 30 # Distance entre les tortues
screen = Screen()
class Follower(Turtle):
def __init__(self, name):
Turtle.__init__(self)
self.shape("circle")
self.color("lightblue")
self.penup()
self.Prev = None
self.Next = None
self.Name = "T" + str(name)
self.coucou = False
def move(self, x, y):
angle = self.towards(x, y)
self.setheading(angle)
self.setposition(x,y)
self.back(20)
if self.Next:
x, y = self.pos()
self.Next.move(x,y)
class Leader(Follower):
def __init__(self):
super().__init__('tkz')
self.shape("turtle")
self.color("lightgreen")
self.Last = None
self.is_moving = False
self.freeze = False
self.deleted_followers = []
def freeeze(self, event):
self.freeze = not self.freeze
def add_follower(self, name):
if self.deleted_followers:
new_follower = self.deleted_followers.pop()
new_follower.showturtle()
new_follower.goto(new_follower.Prev.pos())
new_follower.setheading(new_follower.Prev.heading())
else:
new_follower = Follower(name)
if self.Last == None:
self.Last = new_follower
self.Next = new_follower
new_follower.Prev = self
else:
self.Last.Next = new_follower
self.Last = new_follower
new_follower.Prev = self.Last
new_follower.Next = None
def move(self, event):
if self.freeze == False:
x, y = event.x - window_width()/2, -event.y + window_height()/2
angle = self.towards(x, y)
self.setheading(angle)
self.goto(x, y)
#self.forward(-20)
if self.Next:
self.Next.move(x, y)
def on_move(self, event):
if self.is_moving:
return
self.is_moving = True
self.move(event)
self.is_moving = False
def remove_last_follower(self, event):
if self.Last:
last_follower = self.Last
if last_follower.Prev:
self.Last = last_follower.Prev
self.Last.Next = None
else:
self.Last = None
self.Next = None
last_follower.hideturtle()
self.deleted_followers.append(last_follower)
screen.delay(0)
try:
le = Leader()
except:
le = Leader()
screen.cv.bind("<Button-1>", le.add_follower)
screen.cv.bind("<Button-3>", le.freeeze)
screen.cv.bind("<Delete>", le.remove_last_follower)
screen.cv.bind("<Motion>", le.on_move)
screen.listen()
screen.mainloop()
add_follower
中的链表未正确更新。
改变:self.Last.Next = new_follower
self.Last = new_follower # self.Last updated
new_follower.Prev = self.Last # should be the *old* version of self.Last
致:
self.Last.Next = new_follower
temp = self.Last # save previous Last
self.Last = new_follower # assign new Last
new_follower.Prev = temp # assign previous correctly
甚至:
self.Last.Next = new_follower
self.Last, new_follower.Prev = new_follower, self.Last