要使用pygame實現類似滿天星游戲,你可以按照以下步驟進行操作:
在命令行中運行以下命令進行安裝:
pip install pygame
import pygame
import random
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
class Star:
def __init__(self):
self.x = random.randint(0, width)
self.y = random.randint(0, height)
self.speed = random.randint(1, 3)
def move(self):
self.y += self.speed
if self.y > height:
self.y = 0
self.x = random.randint(0, width)
def draw(self):
pygame.draw.circle(screen, (255, 255, 255), (self.x, self.y), 1)
num_stars = 100
stars = []
for _ in range(num_stars):
stars.append(Star())
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0))
for star in stars:
star.move()
star.draw()
pygame.display.flip()
pygame.quit()
這樣,你就可以使用pygame實現類似滿天星游戲了。每一幀中,星星都會向下移動,并在移動到窗口底部時重新回到窗口頂部。