2016-11-15 251 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()