【问题标题】:Filling in a turtle drawing after assigning to a key分配给键后填充海龟图
【发布时间】:2013-04-15 09:30:55
【问题描述】:

到目前为止,我已经设置了一种蚀刻草图样式的程序,它在按键时移动一定距离并使用 onkey 函数改变颜色。但是,我想通过将程序分配给另一个键(例如“空格”)来填充您使用程序绘制的内容。因此,当执行“空格”时,它将填充我绘制的内容,例如我当前使用的颜色的正方形。空格键已被定义为停止绘图,但我也希望它执行填充命令。

提前致谢。

screen_size = 600
setup(screen_size, screen_size)
maximum_coord = (screen_size/2) - 20
bgcolor("white")
goto(0,0)
speed = 5
pensize(3)
color("red")
pendown()


# Listen for the key presses
listen()

# Define all the functions that will control forward, back, left and right
    def up():
        if ycor() < maximum_coord:
    setheading(90)
    forward(speed)
def down():
    if ycor() > -maximum_coord:
        setheading(270)
        forward(speed)
def left():
    if xcor() > -maximum_coord:
        setheading(180)
        forward(speed)
def right():
    if xcor() < maximum_coord:
        setheading(0)
        forward(speed)
def undo_move():
    undo()


#Define space bar to make the pen go up and therefore stop drawing
current_state = penup
next_state = pendown
def space_bar():
    global current_state, next_state
    next_state()
    current_state, next_state = next_state, current_state


#Define colours when keys are pressed
def red():
        color("red")

def green():
    c    olor("green")

def blue():
        color("blue")


#Define space bar to make the pen go up and therefore stop drawing

current_state = penup
next_state = pendown
def space_bar():
     global current_state, next_state
     next_state()
     current_state, next_state = next_state, current_state

# Define the function to clear all the currently drawn lines on the page,
# but keep the turtle in the same position
def clear_drawing():
    clear()


# Define all the functions that will control forward, back, left and right
s= getscreen()
s.onkey(up,"Up")
s.onkey(down,"Down")
s.onkey(left,"Left")
s.onkey(right,"Right")
s.onkey(space_bar,"space")
s.onkey(red,"r")
s.onkey(green,"g")
s.onkey(blue,"b")
s.onkey(undo_move,"z")
s.onkey(clear_drawing, "c")

    done()

【问题讨论】:

    标签: python function fill turtle-graphics


    【解决方案1】:

    Turtle 中有两个函数称为begin_fill()end_fill(),它们填充TurtleTurtle 的颜色绘制的任何形状。棘手的是区分何时使用begin_fill() 或何时使用end_fill()

    有很多方法可以做到这一点(例如,在按下键时更改变量布尔值),但为了简单起见,我将向您展示如何使用计数器来做到这一点。

    首先将pendown()更改为penup()

    global counter
    counter = 0
    
    def space_bar():
        global counter
        counter =  counter + 1
        if counter % 2 != 0:
            pendown()
            begin_fill()
        else:
            penup()
            end_fill()
    

    此功能将能够在按下时切换进出功能,并且还将填充您在Turtle中跟踪的任何形状。

    编辑:删除其他space_bar() 之一并用此代码替换一个以获得结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 2012-05-17
      相关资源
      最近更新 更多