0

我不明白如何制作 1 个被克隆多次的盒子,其中每个第二个块都有不同的颜色。我想制作一个主框并对其进行整形,然后制作一个循环,在其中我多次克隆它,但我无法制作循环将它始终克隆到另一个克隆旁边。另外,当涉及到颜色时,我定义了一个列表,它给了我一个错误,因为这个变量没有被使用,我想使用它,所以每隔一个块就用另一种颜色。

def draw_boxes(box_list):

    box = Turtle()
    box.shape("square")
    box.shapesize(1, 3)

    color_list = ["cyan", "pink"]

    box_list = []

    #Box_layer1
    for box_layer1 in range(9):
        box_layer1 = box.clone()
        box_layer1.goto() # not filled in since i dont know how to make the clone go to the other clone

    # Box_layer2

    # Box_layer3
    pass

如果有人知道这将是惊人的,这似乎给我带来了很多麻烦。

4

1 回答 1

1

我看到您在调用函数Turtle时正在定义一个对象draw_boxes。这将导致太多Turtle的 s。相反,定义boxes_list函数的外部。

要遍历box_list每个框的索引,以便在每次迭代期间可以访问前一个框,请使用enumerate.

下面的代码是一个演示,其中Turtles 在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()

在此处输入图像描述

于 2020-11-27T14:17:46.207 回答