我正在尝试制作一个棋盘格。我有这个代码来制作一个棋盘 - 它可以工作,但行不匹配。如何让每一行从头开始,例如向后退150?我尝试了一行向后150,然后第二回向120.
import turtle
turtle.speed(0)
def go_to_start():
turtle.pu()
turtle.backward(150)
turtle.left(90)
turtle.forward(250)
turtle.right(90)
turtle.pd()
def colour():
turtle.fillcolor('black')
for j in range(5):
turtle.begin_fill()
for i in range (4):
turtle.forward(30)
turtle.right(90)
turtle.end_fill()
turtle.pu()
turtle.forward(60)
turtle.pd()
def first_row():
turtle.pu()
turtle.backward(180)
turtle.right(90)
turtle.forward(30)
turtle.right(270)
turtle.pd()
def second_row():
turtle.pu()
turtle.backward(150)
turtle.right(90)
turtle.right(270)
turtle.pd()
go_to_start()
for j in range (5):
for i in range (5):
colour()
second_row()
first_row()
答案 0 :(得分:0)
对于表格的每一行,这将返回相同的距离,这是不正确的。您需要实现一些逻辑以返回每行的正确数量。例如,您可以使用:
替换first_row,second_row和for循环def reset():
turtle.pu()
turtle.backward(300)
turtle.right(90)
turtle.forward(30)
turtle.right(270)
turtle.pd()
for j in range (5):
for i in range (5):
colour()
#if the row is even, then go forward 30
if j %2 == 0:
turtle.forward(30)
#if the row is odd, then go backward 30
else:
turtle.backward(30)
reset()
答案 1 :(得分:0)
我提出了一些建议,使您的程序更简单,更快捷。首先,棋盘是 盖章 的绝佳机会,而不是 draw 。其次,不要再从左到右思考,而是双向思考:
import turtle
CURSOR_SIZE = 20
SQUARE_SIZE = 30
turtle.shape('square')
turtle.shapesize(SQUARE_SIZE / CURSOR_SIZE)
turtle.penup()
distance = 2 * SQUARE_SIZE
for j in range(8):
for _ in range(4):
turtle.stamp()
turtle.forward(distance)
# if row is odd, go forward one square else go backward one square
turtle.forward(SQUARE_SIZE if j % 2 else -SQUARE_SIZE)
distance = -distance
turtle.sety(turtle.ycor() - SQUARE_SIZE)
turtle.hideturtle()
turtle.done()