You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中让随机生成的星点保持指定半径间距?

实现星点指定半径间距控制的方案

要让星点之间保持指定的最小间距,核心思路是新生成的星点与所有已存在的星点之间的欧几里得距离必须大于等于设定的最小半径,而非仅检查坐标是否完全重复。以下是具体实现步骤和修改后的代码:

关键修改点

  • 定义最小间距常量(可按需调整)
  • 替换原有的重复检查逻辑,改为计算新点与所有已存点的距离
  • 补充原代码中缺失的starLocationX()和starLocationY()坐标生成函数

修改后的完整代码

import turtle as t, random as r
import math

screen = t.Screen()
screen.bgcolor("#3A3B3C")
t.speed(0)  # 加快绘图速度,可选

# 星点之间的最小间距,可根据需求调整
MIN_DISTANCE = 40

def starLocationX():
    # 生成屏幕可见范围内的X坐标
    return r.randint(-screen.window_width()//2 + 10, screen.window_width()//2 - 10)

def starLocationY(y):
    # 生成指定高度以上的Y坐标,模拟天空区域
    return r.randint(y, screen.window_height()//2 - 10)

def randomStars(y, num):
    t.penup()
    t.pensize(2)
    t.color("white")
    locations = []
    
    for _ in range(num):
        valid = False
        # 限制尝试次数,避免因空间不足导致无限循环
        max_attempts = 100
        attempts = 0
        
        while not valid and attempts < max_attempts:
            attempts += 1
            x_pos = starLocationX()
            y_pos = starLocationY(y)
            # 检查新点是否与已存点过近
            too_close = False
            for (x, y) in locations:
                distance = math.hypot(x_pos - x, y_pos - y)
                if distance < MIN_DISTANCE:
                    too_close = True
                    break
            if not too_close:
                locations.append((x_pos, y_pos))
                valid = True
        
        if not valid:
            print(f"无法生成第{_+1}个星点:尝试次数耗尽")
            continue
        
        # 绘制星点
        t.goto(x_pos, y_pos)
        t.pendown()
        t.seth(60)
        t.fd(2)
        t.fd(-2)
        t.seth(-60)
        t.fd(2)
        t.fd(-2)
        t.seth(240)
        t.fd(2)
        t.fd(-2)
        t.seth(120)
        t.fd(2)
        t.fd(-2)
        t.penup()

randomStars(85, 30)
t.done()

代码说明

  1. 距离计算:用math.hypot()快速计算两点间的欧几里得距离,比手动计算平方根更简洁高效。
  2. 有效性校验:每次生成新坐标后,遍历所有已存星点,只要有一个点距离小于MIN_DISTANCE,就重新生成坐标。
  3. 防无限循环:添加max_attempts限制尝试次数,避免因屏幕空间不足导致程序卡住。
  4. 坐标范围控制:补充的坐标生成函数确保星点在屏幕可见区域内,避免超出画布。

你可以通过调整MIN_DISTANCE的值来控制星点之间的疏密程度,数值越大,星点间距越宽。

内容的提问来源于stack exchange,提问作者HotSanta1234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:45:37