简体   繁体   中英

Make turtle go to a random place on the screen with randint

How to make the cursor go to a random place on the screen with randint() using Python turtle graphics:

stars = Turtle()

drawings = [Trees, Moon, BlueSky, NightSky, Sun, Sunset, stars]


def penup():
    for x in drawings:
        x.penup()
penup()

def Stars():
    for x in range(5):
        penup()
        stars.goto((randint(-100,0), randint(0,100)))
        pendown()
        stars.left(36)
        stars.forward(10)
        stars.left(36)
        penup()
Stars()

I'm trying to make a program that draws stars at the top of the screen, with random spots to where it goes in the night sky. Could someone help with this randint() function? It's not going to a random position and it's acting weird.

Your code is a bit of a mess. Having both stars and Stars is risky coding. You use your penup() function as if it's turtle's penup() function, which it isn't. Your code doesn't even draw one star, let alone many. And the star you're attempting to draw looks more like a pentagon than a star.

Here's a rework of your code that does what you describe:

from turtle import Turtle, Screen
from random import randint

def stars():
    for _ in range(20):
        star.penup()
        star.goto(randint(-200, 200), randint(100, 200))
        star.pendown()

        for _ in range(5):
            star.left(144)
            star.forward(10)

screen = Screen()

star = Turtle()
star.speed('fastest')  # because I have no patience

stars()

star.hideturtle()
screen.exitonclick()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM