以下是我的入门级编程课程的作业
对于本作业,您将使用海龟图形创建自己的复杂马赛克瓷砖图案。您的马赛克必须满足以下要求:
我试图保持这个超级简单,因为我是一个初学者。到目前为止,这是我的代码,我一直坚持使用 for 循环让乌龟绘制图案,在屏幕上向右移动,然后使用 for 循环再次绘制该图案 4 次。我正在一只乌龟上进行测试,它第一次移动,但随后在同一位置绘制了另外 3 次图案。
# Creating a mosaic using greg the turlte from the Turtle Graphics module
import turtle
#setting up the screen environment
myscreen = turtle.Screen()
myscreen.bgcolor("black")
myscreen.screensize(400, 400)
# Initializing turtles, their writing speed, and pen color
greg = turtle.Turtle()
greg.speed(0.5)
greg.color('red')
# Set starting locations for each turtle
greg.up()
greg.goto(-250, 250)
greg.down()
#create loop function for each turtle
y = -250
angle = 91
for y in range(4):
for x in range(50):
greg.forward(x)
greg.left(angle)
greg.up()
greg.goto(y, 250)
greg.down()
y = y + 100
myscreen.exitonclick()
输出图像
我的输出在结构上应该是什么样子
我尝试过重新排列 for 循环,但我认为 for 语句的逻辑还没有完全融入我的大脑。
以能够解释变量用途的方式选择变量命名是个好主意。这有助于查看代码是否执行了应有的操作。 下面是如何做到这一点的示例:
# Creating a mosaic using greg the turlte from the Turtle Graphics module
import turtle
#setting up the screen environment
myscreen = turtle.Screen()
myscreen.bgcolor("black")
myscreen.screensize(400, 400)
colors = ['red', 'green', 'blue'] # list of three colors to loop over
# Initializing turtles, their writing speed
greg = turtle.Turtle()
greg.speed(0.5)
# Set reference location and heading of turtle drawing the first tile
x0, y0, direction = -250, 250, 0 # reference x, y position and the reference turtle heading angle
# Initialize values required to draw the tile:
turnAngle = 91
distanceXbetweenTiles, distanceYbetweenTiles = 40, 40
# create tiles in a loop over tile numbers:
for tileNo in range(4): # tileNo will start with zero 0 and run up to 3
# ^-- draw four tiles:
greg.up()
# move and turn the turtle so that it will draw the next tile
greg.goto(x0 + tileNo*distanceXbetweenTiles, y0 - tileNo*distanceYbetweenTiles)
greg.setheading(direction) # make sure the turtle has always same orientation (i.e. heading angle)
greg.color(colors[tileNo%3]) # loop over color indices: 0,1,2, 0,1,2, 0,1,2, ...
greg.down()
# draw one tile at the above chosen position:
for distance in range(50):
greg.forward(distance)
greg.left(turnAngle)
myscreen.exitonclick()
请参阅问题下方的评论,了解代码未按预期运行的原因。