import sys
import pygame
import random
# 初始化pygame
pygame.init()
# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏的FPS
clock = pygame.time.Clock()
fps = 60
# 定义颜色
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
# 玩家的位置和大小
player_pos = [screen_width / 2, screen_height / 2]
player_size = 20
# 灯光列表
lights = []
# 创建灯光
def create_light(color, pos, radius):
light = {
'color': color,
'pos': pos,
'radius': radius,
}
lights.append(light)
# 更新灯光的位置
def update_lights():
for light in lights:
light['pos'][0] += random.randint(-5, 5)
light['pos'][1] += random.randint(-5, 5)
# 如果灯光离屏幕太远,就移除
if not 0 <= light['pos'][0] < screen_width or not 0 <= light['pos'][1] < screen_height:
lights.remove(light)
# 绘制灯光
def draw_lights(surface):
for light in lights:
pygame.draw.circle(surface, light['color'], light['pos'], light['radius'])
# 主游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
# 更新玩家位置
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_pos[0] -= 5
if keys[pygame.K_RIGHT]:
player_pos[0] += 5
if keys[pygame.K_UP]:
player_pos[1] -= 5
if keys[pygame.K_DOWN]:
player_pos[1] += 5
# 创建随机灯光
if random.randint(0, 100) < 10:
color = red if random.randint(0, 1) else green
create_light(color, [random.randint(0, screen_width), random.randint(0, screen_height)], random.randint(10, 50))
# 更新灯光位置
update_lights()
# 绘制背景
screen.fill(white)
# 绘制玩家
pygame.draw.rect(screen, red, (player_pos[0] - player_size / 2, player_pos[1] - player_size / 2, player_size, player_size))
# 绘制灯光
draw_lights(screen)
# 更新屏幕显示
pygame.display.flip()
# 控制游戏速度
clock.tick(fps)
# 退出游戏
pygame.quit()
sys.exit()
使用PythonPygame实现的基本像素风格灯光追逐游戏
4397

被折叠的 条评论
为什么被折叠?



