1

我需要编写一个函数,根据这个人想要多少颗星星的问题来随机绘制星星。a=color,b=length 和 c,d 是起始坐标。我不确定我哪里出错了,任何提示、提示或帮助将不胜感激。

import turtle
from random import*
def star(a,b,c,d):
    x=5
    y=0
    turtle.color(a)
    turtle.begin_fill()
    turtle.penup()
    turtle.goto(c,d)
    turtle.pendown()
    while x>0:
        turtle.forward(b)
        turtle.right(144)
        turtle.forward(b)
        x-=1
    turtle.end_fill()

star('red',100,0,0)

def random_color():
    randvar=randrange(0,5)
    if randvar==0:
        return ('red')
    elif randvar==1:
        return ('blue')
    elif randvar==2:
        return ('green')
    elif randvar==3:
        return ('yellow')
    else:
        return ('black')

def length():
    randvar=randrange(5,71)

def x():
    randvar=randrange(-280,281)

def y():
    randvar=randrange(-200,201)

def night_sky():
   z=int(input('How many stars do you want?'))
   a=random_color
   b=length
   c=x
   d=y
   while z>0:
       star(a,b,c,d)
       z-=1
4

1 回答 1

3

要调用函数,请在函数名称后加上括号:

   a=random_color()
   b=length()
   c=x()
   d=y()

确保night_sky()在脚本末尾调用。目前,只有

star('red',100,0,0)

正在被调用。这就是为什么你只能看到一颗星星。


功能lengthx以及y需要使用return。否则,None默认返回。

def length():
    return randrange(5,71)

def x():
    return randrange(-280,281)

def y():
    return randrange(-200,201)

您需要将定义abc和的语句移动d到-while循环中,以免同一个星被绘制z次数。当我们这样做时,while-loop 可以更简单地写成for-loop:

   for i in range(z):
       a=random_color()
       b=length()
       c=x()
       d=y()
       star(a,b,c,d)

如果您使用更具描述性的变量名称,您的代码将变得更加自文档化:

def star(color, side_length, x, y):
    print(color, side_length, x, y)
    turtle.color(color)
    turtle.begin_fill()
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()
    for i in range(5):
        turtle.forward(side_length)
        turtle.right(144)
        turtle.forward(side_length)
    turtle.end_fill()

因此,通过这些更改,代码变为:

import turtle
import random

def star(color, side_length, x, y):
    print(color, side_length, x, y)
    turtle.color(color)
    turtle.begin_fill()
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()
    for i in range(5):
        turtle.forward(side_length)
        turtle.right(144)
        turtle.forward(side_length)
    turtle.end_fill()


def random_color():
    randvar = randrange(0, 5)
    if randvar == 0:
        return ('red')
    elif randvar == 1:
        return ('blue')
    elif randvar == 2:
        return ('green')
    elif randvar == 3:
        return ('yellow')
    else:
        return ('black')


def length():
    return random.randrange(5, 71)


def xcoord():
    return random.randrange(-280, 281)


def ycoord():
    return random.randrange(-200, 201)


def night_sky():
    z = int(input('How many stars do you want?'))
    for i in range(z):
        color = random_color()
        side_length = length()
        x = xcoord()
        y = ycoord()
        star(color, side_length, x, y)

night_sky()
于 2013-04-01T17:26:12.370 回答