2013-04-15 40 views
0

我已經設置了一種etchi素描風格的程序,它在按鍵上移動一定距離並使用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() 

回答

0

有在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()並用此代碼替換一個以獲得結果。

+0

工作完美,非常感謝您的幫助。 – user2281912