繁体   English   中英

如何在 Turtle 中填充这些方块 - Python

[英]How Can I Fill These Squares in Turtle - Python

我正在尝试填充这些方块中的颜色:

http://i.imgur.com/kRGgR.png

现在海龟只填满这些方块的角落,而不是整个方块。

这是我的代码:

import turtle
import time
import random

print ("This program draws shapes based on the number you enter in a uniform pattern.")
num_str = input("Enter the side number of the shape you want to draw: ")
if num_str.isdigit():
    squares = int(num_str)

angle = 180 - 180*(squares-2)/squares

turtle.up

x = 0 
y = 0
turtle.setpos(x,y)


numshapes = 8
for x in range(numshapes):
    turtle.color(random.random(),random.random(), random.random())
    x += 5
    y += 5
    turtle.forward(x)
    turtle.left(y)
    for i in range(squares):
        turtle.begin_fill()
        turtle.down()
        turtle.forward(40)
        turtle.left(angle)
        turtle.forward(40)
        print (turtle.pos())
        turtle.up()
        turtle.end_fill()

time.sleep(11)
turtle.bye()

我试过在许多位置移动turtle.begin_fill()end_fill()都没有成功……使用Python 3.2.3,谢谢。

我还没有真正使用过乌龟,但看起来这可能是你想要做的。 如果我为这些调用假设了错误的功能,请纠正我:

turtle.begin_fill() # Begin the fill process.
turtle.down() # "Pen" down?
for i in range(squares):  # For each edge of the shape
    turtle.forward(40) # Move forward 40 units
    turtle.left(angle) # Turn ready for the next edge
turtle.up() # Pen up
turtle.end_fill() # End fill.

您正在绘制一系列三角形,对每个三角形使用begin_fill()end_fill() 您可能会做的是将您对begin_fill()end_fill()调用移到内部循环之外,这样您就可以绘制一个完整的正方形,然后要求填充它。

使用填充

t.begin_fill()
t.color("red")
for x in range(4):
    t.fd(100)
    t.rt(90)
t.end_fill()

太棒了,你解决了它! 如果你想让乌龟编程更容易,请使用turtle.seth而不是turtle.left或right。 turtle.left是相对于乌龟的最后位置,所以你不必担心乌龟在命令面前的位置

除了将begin_fill()end_fill()循环之外,正如一些人所提到的,您的代码还有其他问题。 例如,这是一个无操作:

turtle.up

即它不做任何事情。 (缺少括号。)这个测试:

if num_str.isdigit():

对您没有太大作用,因为没有else子句来处理错误。 (即当它不是数字时,下一个语句只是将字符串用作数字并失败。)这个计算似乎有点太复杂了:

angle = 180 - 180*(squares-2)/squares

最后应该有一种更干净的方式来退出程序。 让我们解决所有这些问题:

from turtle import Screen, Turtle
from random import random

NUMBER_SHAPES = 8

print("This program draws shapes based on the number you enter in a uniform pattern.")

num_str = ""

while not num_str.isdigit():
    num_str = input("Enter the side number of the shape you want to draw: ")

sides = int(num_str)
angle = 360 / sides

delta_distance = 0
delta_angle = 0

screen = Screen()
turtle = Turtle()

for x in range(NUMBER_SHAPES):
    turtle.color(random(), random(), random())

    turtle.penup()
    delta_distance += 5
    turtle.forward(delta_distance)
    delta_angle += 5
    turtle.left(delta_angle)
    turtle.pendown()

    turtle.begin_fill()

    for _ in range(sides):
        turtle.forward(40)
        turtle.left(angle)
        turtle.forward(40)

    turtle.end_fill()

screen.exitonclick()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM