这是我的作业:
编辑此代码以确保参数反映超级矩形(例如,行= 6,正方形= 60,超级矩形将有6行,每行10个正方形)。
代码如下:
import turtle
import time
bob = turtle.Turtle()
def make_square(bob, length):
for x in range(4):
bob.rt(90)
bob.fd(length)
def super_rectangle(bob, rows=2, squares=4, length=100):
height = (length / rows)
columns = int(squares / rows)
for row in range(rows):
for column in range(columns):
bob.fd(length)
make_square(bob, length)
bob.rt(90)
bob.fd(length * 2)
bob.rt(90)
time.sleep(1)
super_rectangle(bob, length=100)
答案 0 :(得分:1)
我不清楚操作人员到底在问什么。但是,运行代码很显然是错误的,如目标部分所述:
例如行= 6,正方形= 60,那么您的超级矩形将有6 一排10平方。
不起作用。调用super_rectangle(bob, 6, 60, 30)
时,修复代码缩进后,您将得到:
是多次提取的时间。我们可以在OP的代码上使用创可贴来解决这种情况:
from turtle import Screen, Turtle
def make_square(turtle, length):
for _ in range(4):
turtle.left(90)
turtle.forward(length)
def super_rectangle(turtle, rows=2, squares=4, length=100):
columns = squares // rows
parity = 1
for row in range(rows):
for _ in range(columns):
turtle.forward(length)
make_square(bob, length)
turtle.right(parity * 90)
if parity < 1 and row < rows - 1:
turtle.forward(length * 2)
turtle.right(parity * 90)
parity = 0 - parity
screen = Screen()
bob = Turtle()
bob.speed('fastest') # because I have no patience
super_rectangle(bob, 6, 60, 30)
screen.exitonclick()
哪个绘制了描述的输出:
但是,如果我们按字面意思拿到OP的头衔:
以不同的方式重写此python代码吗?
然后我建议使用冲压而不是 drawing 是解决此问题的正确方法。这种方法使代码更简单,更快捷:
from turtle import Screen, Turtle
CURSOR_SIZE = 20
def super_rectangle(turtle, rows=2, squares=4, length=100):
columns = squares // rows
turtle.shapesize(length / CURSOR_SIZE)
parity = 1
for _ in range(rows):
for _ in range(columns):
turtle.stamp()
turtle.forward(parity * length)
x, y = turtle.position()
turtle.setposition(x + -parity * length, y + length)
parity = 0 - parity
screen = Screen()
bob = Turtle('square', visible=False)
bob.color("black", "white")
bob.penup()
super_rectangle(bob, 6, 60, 30)
screen.exitonclick()
我需要画图而不是盖印。
我们可以使用 drawing 来以一种完全不同的方式来实现此方法,该方法比修补的代码更简单,效率更高。关键是解决图纸中的大量冗余。我们先绘制所有水平线,然后再绘制所有垂直线,而不是绘制单个正方形:
from turtle import Screen, Turtle
def make_serpentine(turtle, length, rows, columns, parity=1):
for _ in range(rows):
turtle.forward(length * columns)
turtle.left(parity * 90)
turtle.forward(length)
turtle.left(parity * 90)
parity = 0 - parity
def super_rectangle(turtle, rows=2, squares=4, length=100):
columns = squares // rows
make_serpentine(turtle, length, rows, columns)
turtle.forward(length * columns)
turtle.right(90)
make_serpentine(turtle, length, columns, rows, -1) # reverse sense of rows & columns
turtle.forward(length * rows)
turtle.left(90) # leave things as we found them
screen = Screen()
bob = Turtle()
super_rectangle(bob, 6, 60, 30)
screen.exitonclick()