Lesson 3 of 7 · 2 min
Record your driving
Arrow keys steer, accelerate and brake. Aim for 20 minutes, including recoveries from the grass, or the model never learns how to come back.
# run locally: record.py
import gymnasium as gym, numpy as np, pygame
ACTIONS = {0: [0, 0, 0], 1: [-1, 0, 0], 2: [1, 0, 0], 3: [0, 1, 0], 4: [0, 0, 0.8]}
env = gym.make("CarRacing-v3", render_mode="human")
obs, _ = env.reset(seed=0)
frames, labels = [], []
try:
while True:
pygame.event.pump()
k = pygame.key.get_pressed()
a = 1 if k[pygame.K_LEFT] else 2 if k[pygame.K_RIGHT] else 3 if k[pygame.K_UP] else 4 if k[pygame.K_DOWN] else 0
if k[pygame.K_q]:
break
frames.append(obs[:84].mean(axis=2).astype(np.uint8))
labels.append(a)
obs, _, done, cut, _ = env.step(np.array(ACTIONS[a], dtype=np.float32))
if done or cut:
obs, _ = env.reset()
finally:
np.savez_compressed("drive.npz", x=np.array(frames), y=np.array(labels))
print(len(frames), "frames saved")