使用了 Pygame 库来创建一个简单的游戏环境,模拟了一辆自动驾驶汽车在道路上行驶。汽车的位置和速度通过键盘控制,可以左右移动和加速减速。道路的宽度和颜色可以根据需要进行调整。
import pygame
import random
游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
汽车的初始位置和速度
CAR_POSITION = [WINDOW_WIDTH / 2, WINDOW_HEIGHT - 50]
CAR_SPEED = [0, 0]
道路的宽度和颜色
ROAD_WIDTH = 100
ROAD_COLOR = (255, 255, 255)
其他车辆的初始位置和速度
OTHER_CARS = []
for i in range(5):
x = random.randint(0, WINDOW_WIDTH - ROAD_WIDTH)
y = random.randint(0, WINDOW_HEIGHT - 50)
speed = [random.randint(-5, 5), random.randint(-5, 5)]
OTHER_CARS.append({'position': [x, y], 'speed': speed})
游戏循环
running = True
clock = pygame.time.Clock()
while running:
处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
更新汽车位置
CAR_POSITION[0] += CAR_SPEED[0]
CAR_POSITION[1] += CAR_SPEED[1]
检查汽车是否超出边界
if CAR_POSITION[0] < 0 or CAR_POSITION[0] > WINDOW_WIDTH - ROAD_WIDTH:
CAR_SPEED[0] = -CAR_SPEED[0]
if CAR_POSITION[1] < 0 or CAR_POSITION[1] > WINDOW_HEIGHT - 50:
CAR_SPEED[1] = -CAR_SPEED[1]
绘制背景
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
screen.fill(ROAD_COLOR)
绘制汽车
pygame.draw.rect(screen, (0, 0, 255), (CAR_POSITION[0] - 25, CAR_POSITION[1] - 25, 50, 50))
绘制其他车辆
for car in OTHER_CARS:
pygame.draw.rect(screen, (0, 255, 0), (car['position'][0] - 25, car['position'][1] - 25, 50, 50))
刷新屏幕
pygame.display.flip()
控制游戏帧率
clock.tick(60)
退出游戏
pygame.quit()