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

如何在Python中高效存储随机屏幕x、y坐标至列表(Pygame星星开发)

星星绘制与坐标存储问题

我希望用代码在屏幕上绘制指定数量的星星,并实现星星偶尔闪烁的效果。在解决星星闪烁问题前,我想先明确如何存储随机生成的x、y坐标——应使用列表还是列表的列表?

初始可运行代码

包含两种不同尺寸星星的可运行代码如下:

import pygame
from random import randint
pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("My God, it's full of stars!")

black = (0,0,0)
white = (255,255,255)
gray = (50,50,50)

x = randint(1,800)
y = randint(1,600)
p = randint(1,800)
q = randint(1,600)
r = randint(1,800)
s = randint(1,600)

clock = pygame.time.Clock()
crashed = False
med_star_img = pygame.image.load('images/medium_star.png')
tiny_star_img = pygame.image.load('images/tiny_star.png')

def make_star(x,y):
        gameDisplay.blit(med_star_img, (x,y))
        gameDisplay.blit(tiny_star_img, (p,q))
        gameDisplay.blit(tiny_star_img, (r,s))
        
while not crashed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True

    gameDisplay.fill(gray)
    make_star(x,y)
    pygame.display.flip()
    # pygame.display.update()
    clock.tick(60)

pygame.quit()
quit()

编辑补充:修订后的代码

由于不确定make_star函数的正确写法,我修改了代码,内容如下:

import pygame
from random import randint
pygame.init()

display_width = 800
display_height = 600

# screen color choices
black = (0,0,0)
white = (255,255,255)
gray = (50,50,50)

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("My God, it's full of stars!")

clock = pygame.time.Clock()
crashed = False
med_star_img = pygame.image.load('images/medium_star.png')
tiny_star_img = pygame.image.load('images/tiny_star.png')

stars_location = []
stars_width = 0
stars_height = 0

#what this for loop does is that it runs the amount of times the range is
#for example if the range is 3
#and i print('hi') inside this loop
#it will print hi 3 times

for i in range(5):
    #what append does is it adds whatever you put in the brackets to the list      
    stars_location.append(pygame.Rect(randint(1,800),randint(1,600),stars_width,stars_height))

print(stars_location)


# Draw star
def make_star(x,y):
        gameDisplay.blit(med_star_img,(x,y))

        
while not crashed:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        crashed = True
        for star in stars_location:
                make_star(star.x,star.y)

        gameDisplay.fill(gray)
        pygame.display.flip()
        # pygame.display.update()
        clock.tick(60)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:01:10