Here's an HTML-based car driving game that implements a simple reinforcement learning approach. The car learns to navigate a track over time.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RL Car Driving Game</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0;
padding: 20px;
background-color: #f0f0f0;
}
#gameCanvas {
background-color: #333;
border: 2px solid #000;
margin: 0 auto;
display: block;
}
.controls {
margin: 20px 0;
}
button {
padding: 10px 15px;
margin: 0 5px;
font-size: 16px;
cursor: pointer;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
}
button:hover {
background-color: #45a049;
}
.stats {
margin: 20px auto;
width: 80%;
max-width: 600px;
padding: 15px;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<h1>Reinforcement Learning Car Game</h1>
<div class="controls">
<button id="startBtn">Start Learning</button>
<button id="resetBtn">Reset</button>
<button id="toggleModeBtn">Toggle Mode (AI/Manual)</button>
</div>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<div class="stats">
<h3>Learning Stats</h3>
<p>Episodes: <span id="episodes">0</span></p>
<p>Current Reward: <span id="currentReward">0</span></p>
<p>Best Reward: <span id="bestReward">0</span></p>
<p>Exploration Rate: <span id="explorationRate">1.00</span></p>
<p>Mode: <span id="mode">AI Learning</span></p>
</div>
<script>
// Game elements
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const startBtn = document.getElementById('startBtn');
const resetBtn = document.getElementById('resetBtn');
const toggleModeBtn = document.getElementById('toggleModeBtn');
// Stats elements
const episodesEl = document.getElementById('episodes');
const currentRewardEl = document.getElementById('currentReward');
const bestRewardEl = document.getElementById('bestReward');
const explorationRateEl = document.getElementById('explorationRate');
const modeEl = document.getElementById('mode');
// Game state
let isLearning = false;
let isManualMode = false;
let episodes = 0;
let currentReward = 0;
let bestReward = 0;
let explorationRate = 1.0;
const minExplorationRate = 0.01;
const explorationDecayRate = 0.001;
// Track definition
const trackWidth = 100;
const track = [
{x: 400, y: 100},
{x: 600, y: 150},
{x: 650, y: 300},
{x: 600, y: 450},
{x: 400, y: 500},
{x: 200, y: 450},
{x: 150, y: 300},
{x: 200, y: 150}
];
// Car properties
const car = {
x: 400,
y: 300,
width: 20,
height: 40,
angle: 0,
speed: 0,
maxSpeed: 5,
acceleration: 0.1,
turnSpeed: 0.05,
sensors: [],
sensorLength: 150,
sensorCount: 5,
checkpointsPassed: 0,
lastCheckpoint: -1
};
// Checkpoints for reward system
const checkpoints = [];
for (let i = 0; i < track.length; i++) {
const current = track[i];
const next = track[(i + 1) % track.length];
checkpoints.push({
x1: current.x,
y1: current.y,
x2: next.x,
y2: next.y
});
}
// Q-learning parameters
const qTable = {};
const learningRate = 0.1;
const discountFactor = 0.9;
const possibleActions = [
{accelerate: 1, turn: 0}, // Forward
{accelerate: 1, turn: -1}, // Forward + Left
{accelerate: 1, turn: 1}, // Forward + Right
{accelerate: 0, turn: -1}, // Left
{accelerate: 0, turn: 1}, // Right
{accelerate: -1, turn: 0}, // Brake
{accelerate: -1, turn: -1}, // Brake + Left
{accelerate: -1, turn: 1} // Brake + Right
];
// Key states for manual control
const keys = {
ArrowUp: false,
ArrowDown: false,
ArrowLeft: false,
ArrowRight: false
};
// Initialize the game
function init() {
resetCar();
drawTrack();
drawCar();
updateStats();
}
// Reset car to starting position
function resetCar() {
car.x = 400;
car.y = 300;
car.angle = 0;
car.speed = 0;
car.checkpointsPassed = 0;
car.lastCheckpoint = -1;
currentReward = 0;
updateSensors();
}
// Update car sensors
function updateSensors() {
car.sensors = [];
for (let i = 0; i < car.sensorCount; i++) {
const angle = car.angle - Math.PI/4 + (Math.PI/2 * i / (car.sensorCount - 1));
const sensor = {
x: car.x,
y: car.y,
angle: angle,
reading: car.sensorLength,
endX: car.x + Math.sin(angle) * car.sensorLength,
endY: car.y - Math.cos(angle) * car.sensorLength
};
// Check for track boundary intersections
for (let j = 0; j < track.length; j++) {
const p1 = track[j];
const p2 = track[(j + 1) % track.length];
// Inner track boundary
const innerP1 = getOffsetPoint(p1, p2, -trackWidth/2);
const innerP2 = getOffsetPoint(p2, p1, trackWidth/2);
// Outer track boundary
const outerP1 = getOffsetPoint(p1, p2, trackWidth/2);
const outerP2 = getOffsetPoint(p2, p1, -trackWidth/2);
// Check inner boundary
checkSensorIntersection(sensor, innerP1, innerP2);
// Check outer boundary
checkSensorIntersection(sensor, outerP1, outerP2);
}
car.sensors.push(sensor);
}
}
// Check if sensor intersects with a line segment
function checkSensorIntersection(sensor, p1, p2) {
const x1 = sensor.x;
const y1 = sensor.y;
const x2 = sensor.endX;
const y2 = sensor.endY;
const x3 = p1.x;
const y3 = p1.y;
const x4 = p2.x;
const y4 = p2.y;
const den = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
if (den === 0) return; // Lines are parallel
const t = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / den;
const u = -((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / den;
if (t > 0 && t < 1 && u > 0 && u < 1) {
const intersectX = x1 + t * (x2 - x1);
const intersectY = y1 + t * (y2 - y1);
const distance = Math.sqrt(
(intersectX - sensor.x) ** 2 +
(intersectY - sensor.y) ** 2
);
if (distance < sensor.reading) {
sensor.reading = distance;
sensor.endX = intersectX;
sensor.endY = intersectY;
}
}
}
// Get offset point for track boundaries
function getOffsetPoint(p1, p2, offset) {
const dx = p2.x - p1.x;
const dy = p2.y - p1.y;
const length = Math.sqrt(dx * dx + dy * dy);
return {
x: p1.x + offset * dy / length,
y: p1.y - offset * dx / length
};
}
// Draw the track
function drawTrack() {
// Draw outer track
ctx.beginPath();
ctx.strokeStyle = '#FFF';
ctx.lineWidth = trackWidth;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.moveTo(track[0].x, track[0].y);
for (let i = 1; i < track.length; i++) {
ctx.lineTo(track[i].x, track[i].y);
}
ctx.closePath();
ctx.stroke();
// Draw track center line
ctx.beginPath();
ctx.strokeStyle = '#AAA';
ctx.lineWidth = 2;
ctx.setLineDash([10, 10]);
ctx.moveTo(track[0].x, track[0].y);
for (let i = 1; i < track.length; i++) {
ctx.lineTo(track[i].x, track[i].y);
}
ctx.closePath();
ctx.stroke();
ctx.setLineDash([]);
// Draw checkpoints
for (let i = 0; i < checkpoints.length; i++) {
const cp = checkpoints[i];
ctx.beginPath();
ctx.strokeStyle = car.lastCheckpoint === i ? '#0F0' : '#F00';
ctx.lineWidth = 2;
ctx.moveTo(cp.x1, cp.y1);
ctx.lineTo(cp.x2, cp.y2);
ctx.stroke();
}
}
// Draw the car
function drawCar() {
ctx.save();
ctx.translate(car.x, car.y);
ctx.rotate(car.angle);
// Car body
ctx.fillStyle = '#0088FF';
ctx.fillRect(-car.width/2, -car.height/2, car.width, car.height);
// Car direction indicator
ctx.fillStyle = '#FF0000';
ctx.beginPath();
ctx.moveTo(0, -car.height/2);
ctx.lineTo(car.width/4, -car.height/2 - 5);
ctx.lineTo(-car.width/4, -car.height/2 - 5);
ctx.closePath();
ctx.fill();
ctx.restore();
// Draw sensors
for (const sensor of car.sensors) {
ctx.beginPath();
ctx.strokeStyle = sensor.reading < car.sensorLength ? '#FF0000' : '#00FF00';
ctx.lineWidth = 1;
ctx.moveTo(car.x, car.y);
ctx.lineTo(sensor.endX, sensor.endY);
ctx.stroke();
// Draw sensor reading
ctx.fillStyle = '#FFFFFF';
ctx.fillText(
Math.round(sensor.reading),
(car.x + sensor.endX) / 2,
(car.y + sensor.endY) / 2
);
}
}
// Update car position and check collisions
function updateCar(action) {
// Apply action
if (action) {
car.speed += action.accelerate * car.acceleration;
car.angle += action.turn * car.turnSpeed;
} else if (isManualMode) {
// Manual control
if (keys.ArrowUp) car.speed += car.acceleration;
if (keys.ArrowDown) car.speed -= car.acceleration;
if (keys.ArrowLeft) car.angle -= car.turnSpeed;
if (keys.ArrowRight) car.angle += car.turnSpeed;
}
// Limit speed
car.speed = Math.max(-car.maxSpeed/2, Math.min(car.maxSpeed, car.speed));
// Apply friction
car.speed *= 0.98;
// Update position
car.x += Math.sin(car.angle) * car.speed;
car.y -= Math.cos(car.angle) * car.speed;
// Update sensors
updateSensors();
// Check for checkpoint crossing
checkCheckpoints();
// Check for collision with track boundaries
return checkCollision();
}
// Check if car has crossed a checkpoint
function checkCheckpoints() {
for (let i = 0; i < checkpoints.length; i++) {
const nextCheckpoint = (car.lastCheckpoint + 1) % checkpoints.length;
if (i === nextCheckpoint) {
const cp = checkpoints[i];
if (lineIntersectsCircle(
cp.x1, cp.y1, cp.x2, cp.y2,
car.x, car.y, car.width/2
)) {
car.lastCheckpoint = i;
car.checkpointsPassed++;
currentReward += 100; // Reward for passing checkpoint
return true;
}
}
}
return false;
}
// Check if line intersects with circle
function lineIntersectsCircle(x1, y1, x2, y2, cx, cy, r) {
const dx = x2 - x1;
const dy = y2 - y1;
const a = dx * dx + dy * dy;
const b = 2 * (dx * (x1 - cx) + dy * (y