2016-11-15 286 views
-2

我想繪製3種隨機顏色的圓圈。但是在這個代碼,用於繪製圓,輸出無顏色:Python Turtle Draw隨機彩色圓圈

import turtle 

window=turtle.Screen() 
tess= turtle. Turtle() 

import random 

def getColor(): 

    color=random.randint(1,3) 
    if color==1: 
     color="red" 
    elif color==2: 
     color=="yellow" 
    elif color==3: 
     color=="blue" 
    return color 
print (random.randint(1,3)) 

def drawFace (x,y): 

    tess.penup() 
    tess.goto(x+5,y+10) 
    tess.circle(10) 
    tess.goto(x+15,y+10) 
    tess.circle(10) 
    tess.pendown() 
+1

您沒有使用'getColor()'。至少不在此代碼中。另外,您在兩次不同的randint()調用中生成兩個不同的數字。 – Lafexlos

回答

0

getColor()功能,你不分配給當它是黃色或藍色的color變量 - 你使用雙等於。下面是固定的版本:

def getColor(): 
    color=random.randint(1,3) 
    if color==1: 
     color="red" 
    elif color==2: 
     color="yellow" 
    elif color==3: 
     color="blue" 
    return color 

其次,你在drawFace()開始拿起筆起來,放得下完成之前!這裏的修復:

def drawFace (x,y): 
    tess.penup() 
    tess.goto(x+5,y+10) 
    tess.pendown() 
    tess.circle(10) 
    tess.penup() 
    tess.goto(x+15,y+10) 
    tess.pendown() 
    tess.circle(10) 
0

你並不需要選擇隨機數索引你的顏色,你可以隨機選擇一個直接與random.choice()。你需要呼叫GetColor()並通過tess.pencolor()應用你選擇的顏色我們也傾向於根據它們的中心來定位圓圈,但是Python龜沒有,所以我們需要(明確地)調整它,就像你一樣(隱式地)調整您的代碼:

from turtle import Turtle, Screen 
import random 

RADIUS = 10 

def getColor(turtle): 
    choice = turtle.pencolor() 

    while choice == turtle.pencolor(): 
     choice = random.choice(["red", "green", "blue"]) 

    return choice 

def drawFace(turtle, x, y): 
    turtle.pencolor(getColor(turtle)) 
    turtle.penup() 
    turtle.goto(x, y - RADIUS) 
    turtle.pendown() 
    turtle.circle(RADIUS) 

tess = Turtle() 

drawFace(tess, 5, 0) 

drawFace(tess, 15, 0) 

screen = Screen() 

screen.exitonclick()