有没有办法检查多边形是否完全封闭?

时间:2019-03-23 23:26:31

标签: python turtle-graphics

我正在尝试绘制一个白色的红色停止标志。但是,我似乎无法弄清楚为什么红色八边形没有填充。

如果八边形仍处于打开状态,那为什么它没有填充?如果是的话,如何检查它是否已打开?

import turtle
turtle.bgcolor("black")
turtle.penup()
turtle.goto(-104,-229)
# Draws white octagon outline
for i in range(8):
    turtle.pensize(10)
    turtle.color("white")    
    turtle.pendown()
    turtle.forward(193)
    turtle.right(5)
    turtle.left(50)

# Draws red octagon
turtle.penup()
turtle.goto(-100,-220)
for i in range(8):
    turtle.pensize(10)
    turtle.color("red")
    turtle.fillcolor("red")
    turtle.begin_fill()    
    turtle.pendown()
    turtle.forward(185)
    turtle.right(5)
    turtle.left(50)
    turtle.end_fill()

# Writes "STOP"
turtle.penup()   
turtle.goto(5,-50)
turtle.setheading(360 / 8 / 2)
turtle.pendown()
turtle.stamp()  
turtle.pencolor("white")
turtle.shapesize(0.9)
turtle.stamp()
turtle.shapesize(1.0)
turtle.write("STOP", align="center", font=("Arial",110,"normal"))   
turtle.done()

2 个答案:

答案 0 :(得分:1)

您需要将开始和结束填充物放在循环之外,因为它一次只能填充一行

# Draws red octagon
turtle.penup()
turtle.goto(-100,-220)
turtle.pensize(10)
turtle.color("red")
turtle.fillcolor("red")
turtle.begin_fill()
for i in range(8):
    turtle.pendown()
    turtle.forward(185)
    turtle.right(5)
    turtle.left(50)
turtle.end_fill()

答案 1 :(得分:0)

我发现您的代码有两个问题。首先,将begin_fill()end_fill()放置在八角形环内-它们应该环绕环的外部,而不是环的一部分。其次,通常使事情变得比必要的更为复杂,包括抛出与结果无关的代码(例如stamp()shapesize()setheading()等)。在固定填充的情况下,代码简化了:

from turtle import Screen, Turtle

SIDE = 200
PEN_SIZE = 10
FONT_SIZE = 150
FONT = ("Arial", FONT_SIZE, "bold")

screen = Screen()
screen.bgcolor("black")

turtle = Turtle()
turtle.hideturtle()
turtle.pensize(PEN_SIZE)
turtle.penup()

# Draw white octagon with red fill
turtle.goto(-SIDE/2, -SIDE/2 + -SIDE/(2 ** 0.5))  # octogon geometry
turtle.color("white", "red")  # color() sets both pen and fill colors
turtle.pendown()

turtle.begin_fill()
for _ in range(8):
    turtle.forward(SIDE)
    turtle.left(45)
turtle.end_fill()

turtle.penup()

# Write "STOP"
turtle.goto(0, -FONT_SIZE/2)  # roughly font baseline
turtle.pencolor("white")

turtle.write("STOP", align="center", font=FONT)  # write() doesn't need pendown()

screen.exitonclick()