我正在编写一个基本的蛇游戏,在屏幕上经过一段时间后,我无法找到一种方法来清除尾巴。有人可以帮忙吗?
答案 0 :(得分:0)
我试图使该示例简洁明了,但是您可以看到有几件事可以跟踪何时使蛇的片段基于计时器消失。本示例从窗口的一个角开始蛇向另一角移动,每1/4秒移动一次。每次您在屏幕上单击时,都会获得一个身体部位。但是每1.5秒,它就会失去一个身体部位:
from turtle import Screen, Turtle
CURSOR_SIZE = 20
def add_segment(x, y):
global locked
screen.onclick(None) # disable handler inside handler
if not locked:
locked = True
head = segments[0]
if spares:
segment = spares.pop()
segment.setposition(head.position())
segment.showturtle()
else:
segment = head.clone()
segment.forward(CURSOR_SIZE)
segments.insert(0, segment)
locked = False
screen.update()
head = segments[0]
if head.distance(target) > CURSOR_SIZE:
screen.onclick(add_segment) # reenable handler
def remove_segment():
global locked
if not locked:
locked = True
if len(segments) > 1:
segment = segments.pop()
segment.hideturtle()
spares.append(segment)
locked = False
screen.update()
head = segments[0]
if head.distance(target) > CURSOR_SIZE:
screen.ontimer(remove_segment, 1500)
else:
screen.onclick(None)
def move_snake():
global locked
if not locked:
locked = True
for segment in segments:
segment.forward(CURSOR_SIZE)
locked = False
screen.update()
head = segments[0]
if head.distance(target) > CURSOR_SIZE:
screen.ontimer(move_snake, 250)
else:
screen.onclick(None)
screen = Screen()
screen.tracer(False)
width, height = screen.window_width(), screen.window_height()
start = CURSOR_SIZE - width/2, CURSOR_SIZE - height/2
target = width/2 - CURSOR_SIZE, height/2 - CURSOR_SIZE
snake = Turtle('circle', visible=False)
snake.penup()
snake.goto(start)
snake.setheading(snake.towards(target))
snake.showturtle()
segments = [snake]
spares = []
locked = False
move_snake()
remove_segment()
screen.onclick(add_segment)
screen.mainloop()
其他人可能建议使用非正式的锁定系统,以防止多个事件试图同时操纵蛇。