我看到您在调用函数Turtle
时正在定义一个对象draw_boxes
。这将导致太多Turtle
的 s。相反,定义boxes_list
函数的外部。
要遍历box_list
每个框的索引,以便在每次迭代期间可以访问前一个框,请使用enumerate
.
下面的代码是一个演示,其中Turtle
s 在Slinky运动中移动:
from turtle import Turtle, Screen
wn = Screen()
box_list = []
color_list = ["cyan", "pink"]
for i in range(10):
box = Turtle("square")
box.color(color_list[i%2])
box_list.append(box)
def draw_boxes(head):
for i, box in enumerate(box_list):
if i:
box.goto(box_list[i-1].pos())
else:
box.goto(head.pos())
box.color(color_list[i%2])
head = Turtle("square")
head.color("pink")
wn.listen()
wn.onkey(lambda: head.right(90), "Right")
wn.onkey(lambda: head.left(90), "Left")
while True:
head.forward(40)
draw_boxes(head)
输出:
如果你想要标准的蛇游戏动作:
from turtle import Turtle, Screen
from time import sleep
wn = Screen()
wn.tracer(0)
box_list = []
color_list = ["cyan", "pink"]
for i in range(10):
box = Turtle("square")
box.color(color_list[i%2])
box_list.append(box)
def draw_boxes(head):
for i, box in enumerate(box_list):
if i < len(box_list) - 1:
box.goto(box_list[i+1].pos())
else:
box.goto(head.pos())
head = Turtle("square")
head.color('yellow')
wn.listen()
wn.onkey(lambda: head.right(90), "Right")
wn.onkey(lambda: head.left(90), "Left")
while True:
draw_boxes(head)
head.forward(20)
wn.update()
sleep(0.2)
输出:
更新:
原来这应该是一个盒子破坏游戏,而不是蛇游戏。
对于盒子破坏者游戏:
from turtle import Turtle, Screen
wn = Screen()
wn.setup(600, 600)
wn.tracer(0)
def create_boxes(rows, cols, x, y, w, h):
color_list = ["cyan", "pink"]
boxes_list = []
for i in range(rows):
for j in range(cols):
box = Turtle("square")
box.penup()
box.shapesize(w, h, 3) # The 3 is the outline's width. If you don't want it, simply remove that argument.
box.color("white", color_list[(j + i) % 2]) # The first argument, "white", is the outline color. If you don't want it, simply remove that argument.
box.goto(x + h * 20 * j, y + w * 20 * i)
boxes_list.append(box)
return boxes_list
boxes_list = create_boxes(3, 9, -245, 230, 1, 3)
wn.update()