如何在整个屏幕上传播一些对象

2024-10-06 09:36:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习用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


Tags: ofrectnumbersettingsdefcustomwidthscreen
1条回答
网友
1楼 · 发布于 2024-10-06 09:36:45

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

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)

相关问题 更多 >