python - 如何将一些对象分布到整个屏幕上

标签 python pygame

我正在学习在 pygame 中编码。并且有任务将星星散布到整个屏幕上。

我已经完成了我的代码,但它仅在屏幕的左上角传播星星,我真的不知道如何将星星放置在整个屏幕上。此代码用于传播答案:

def x_demension(custom_settings, star):
    available_x = custom_settings.width - 2*star.rect.width #available space along abscissa axis
    count_numbers = int(available_x / (2*star.rect.width)) #quantity of stars throught weight
    return count_numbers


def y_demension(custom_settings, star, spaceship):
    available_y = custom_settings.height - 2*star.rect.height - spaceship.rect.height #available space along ordinate axis
    number_rows = int(available_y / (2*star.rect.height)) #quantity of rows throught height
    return number_rows


def create_star(screen, custom_settings, number, row_number, stars):
    star = Star(screen, custom_settings) #create an instance of a star

    star.rect.x = star.rect.width + 2*star.rect.width * randint(0,number) #coordinate x of a star
    x = randint(0, star.rect.x)
    star.rect.x = x

    star.rect.y = star.rect.height + 2*star.rect.height * randint(0,row_number) #coordinate y of a star
    y = randint(0,star.rect.y)
    star.rect.y = y

    stars.add(star) #added stars
    if len(stars) > 50: #limiter of the star adding
        stars.remove(star)
    else:
        stars.add(star)


def starsky(custom_settings, screen, spaceship, stars):
    star = Star(custom_settings, screen) #created as an instance of a random star
    number_stars = x_demension(custom_settings, star)
    number_rows = y_demension(custom_settings, star, spaceship)
    for row_number in range(number_rows):
        for number in range(number_stars):
            create_star(screen, custom_settings, number, row_number, stars)

This is what I get

最佳答案

除非我遗漏了什么,否则不应该是:

def create_star(screen, custom_settings, number, row_number, stars):
    star = Star(screen, custom_settings)
    w, h = pygame.display.get_surface().get_size()
    x = randint(0, w)
    star.rect.x = x
    y = randint(0, h)
    star.rect.y = y

    stars.add(star) #added stars
    if len(stars) > 50: #limiter of the star adding
        stars.remove(star)
    else:
        stars.add(star)

关于python - 如何将一些对象分布到整个屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58462854/

相关文章:

python - 在 Python 3.5.2 中解压 Optional 类型注解

python - 带参数和不带参数的 super() 有什么区别?

python - python 的 'pygame.key.get_pressed()' 模块无法识别按键

python - 在不丢失键盘状态的情况下调整 pygame 窗口大小

python - 带有 Python 绑定(bind)的 C lib,两者都想要渲染

python - "Driver is not defined"Python/ Selenium

python - 从角度和线的长度获取点的位置

python - 在列表字典的每个索引处查找最小值和最大值

python - Pandas - 绘图系列

python - Pygame-transform.rotate 结果使用大量 RAM