import pygame
import random
# 初始化 pygame
pygame.init()
# 设置屏幕尺寸和颜色
WIDTH, HEIGHT = 800, 600
BACKGROUND_COLOR = (135, 206, 250) # 天空蓝
CAR_COLOR = (255, 0, 0) # 滑冰车颜色
OBSTACLE_COLOR = (0, 0, 0) # 障碍物颜色
FPS = 30
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("滑冰车游戏")
# 创建游戏对象
car_width, car_height = 50, 30
obstacle_width, obstacle_height = 60, 20
# 初始滑冰车位置
car_pos = [WIDTH // 2, HEIGHT - car_height - 10]
car_speed = 5
obstacles = []
clock = pygame.time.Clock()
def move_car(keys):
if keys[pygame.K_LEFT]:
car_pos[0] -= car_speed
if keys[pygame.K_RIGHT]:
car_pos[0] += car_speed
# 防止滑冰车走出屏幕边界
car_pos[0] = max(0, min(car_pos[0], WIDTH - car_width))
def drop_obstacle():
x = random.randint(0, WIDTH - obstacle_width)
y = -obstacle_height
obstacles.append([x, y])
def move_obstacles():
for obstacle in obstacles:
obstacle[1] += 5
def check_collision():
global obstacles
for obstacle in obstacles[:]:
if (car_pos[0] < obstacle[0] + obstacle_width and
car_pos[0] + car_width > obstacle[0] and
car_pos[1] < obstacle[1] + obstacle_height and
car_pos[1] + car_height > obstacle[1]):
return True
return False
def draw_objects():
screen.fill(BACKGROUND_COLOR)
pygame.draw.rect(screen, CAR_COLOR, (*car_pos, car_width, car_height))
for obstacle in obstacles:
pygame.draw.rect(screen, OBSTACLE_COLOR, (*obstacle, obstacle_width, obstacle_height))
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
move_car(keys)
if random.randint(1, 30) == 1:
drop_obstacle()
move_obstacles()
if check_collision():
print("游戏结束!")
running = False
draw_objects()
clock.tick(FPS)
pygame.quit()