我不明白为什么我的圈子被放在对角线上

I can't figure out why my circles are being placed in a diagonal line

我目前正在编写一段 python 乌龟代码,它要求我在正方形内随机放置圆圈。由于某种原因,它们总是放在对角线上,不会随机绘制。

import random
import turtle

for i in range(15):
    # draws 15 circles and then stops
    random_position = random.randint(-80,90)
    
    # allows the computer to pick any number between -80 and 90 as an x or y co-ordinate
    pit_x = random_position 
    pit_y = random_position 
    pit_radius = 7
      
    # radius of circle
    turtle.penup()
    turtle.setposition(pit_x, pit_y-pit_radius)
    turtle.pendown()
    turtle.begin_fill()
    turtle.circle(pit_radius)
    turtle.end_fill()
    turtle.hideturtle()
     
    # the circle is now a black hole

它是这样显示的:

我该如何解决这个问题?

pit_xpit_x 相等。改为这样做:

pit_x = random.randint(-80,90)
pit_y = random.randint(-80,90)

您只选择一个随机数,然后将其用于两个坐标。而x=y是对角线。

random_position 是随机生成的,但它本身不是生成器 - 只是一个数字。

我还建议将绘图代码放在它自己的函数中,所以:

import random
import turtle

def black_hole(pit_x, pit_y, pit_radius):
    turtle.penup()
    turtle.setposition(pit_x, pit_y-pit_radius)
    turtle.pendown()
    turtle.begin_fill()
    turtle.circle(pit_radius)
    turtle.end_fill()
    turtle.hideturtle()

for i in range(15):
    black_hole(random.randint(-80,90), random.randint(-80,90), 7)

也许使用

pit_x = random.randint(-80,90)
pit_y = random.randint(-80,90)

或者如果你想要一个函数(我想你想为每个函数做 random_pos) 刚刚

def randomPitNumber():
  return random.randint(-80, 90)

然后

    pit_x = randomPitNumber()
    pit_y = randomPitNumber()

并删除 random_position 变量。

提示:为了帮助纠正某些人回答的答案,请按下它旁边的复选标记,这样您就可以将它标记为其他人的正确答案。