Creating a complex racing game with AI-controlled players in a single HTML file involves several steps, including drawing the track, handling the AI navigation, managing game state (like laps and timer), and rendering everything on the screen. Below is a complete HTML file that fulfills your requirements:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AI Racing Game</title>
<style>
body {
text-align: center;
background-color: #222;
color: #fff;
font-family: Arial, sans-serif;
}
#gameCanvas {
background-color: #555;
display: block;
margin: 20px auto;
position: relative;
}
#scoreboard {
margin-top: 10px;
}
.player-score {
display: inline-block;
margin: 0 20px;
}
</style>
</head>
<body>
<h1>AI Racing Game</h1>
<canvas id="gameCanvas" width="800" height="800"></canvas>
<div id="scoreboard">
<div class="player-score" id="player1Score">Player 1 Laps: 0</div>
<div class="player-score" id="player2Score">Player 2 Laps: 0</div>
<div id="timer">Time: 0.00s</div>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const TRACK_WIDTH = 35;
const TRACK_OUTER_RADIUS = 300;
const TRACK_INNER_RADIUS = TRACK_OUTER_RADIUS - TRACK_WIDTH;
// Define waypoints around the track for AI navigation
const waypoints = [];
const numWaypoints = 24; // 12 curves, each curve having 2 waypoints
for(let i = 0; i < numWaypoints; i++) {
const angle = (i / numWaypoints) * 2 * Math.PI;
const radius = (i % 2 === 0) ? TRACK_OUTER_RADIUS : TRACK_INNER_RADIUS;
waypoints.push({
x: canvas.width / 2 + radius * Math.cos(angle),
y: canvas.height / 2 + radius * Math.sin(angle)
});
}
// Player class
class Player {
constructor(color, startWaypoint) {
this.color = color;
this.x = startWaypoint.x;
this.y = startWaypoint.y;
this.radius = 10;
this.angle = 0; // Direction the car is facing
this.speed = 2; // Constant speed
this.currentWaypoint = 1;
this.laps = 0;
this.lastCheckpoint = 0;
}
update() {
const target = waypoints[this.currentWaypoint];
const dx = target.x - this.x;
const dy = target.y - this.y;
const distance = Math.hypot(dx, dy);
// Calculate desired angle
const desiredAngle = Math.atan2(dy, dx);
// Smoothly rotate towards desired angle
const angleDiff = desiredAngle - this.angle;
this.angle += angleDiff * 0.05;
// Update position
this.x += Math.cos(this.angle) * this.speed;
this.y += Math.sin(this.angle) * this.speed;
// Check if reached the waypoint
if(distance < 20) {
this.currentWaypoint = (this.currentWaypoint + 1) % waypoints.length;
if(this.currentWaypoint === 0) {
this.laps += 1;
}
}
}
draw() {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.moveTo(this.radius, 0);
ctx.lineTo(-this.radius, this.radius / 2);
ctx.lineTo(-this.radius, -this.radius / 2);
ctx.closePath();
ctx.fill();
ctx.restore();
}
}
// Initialize players
const player1 = new Player('red', waypoints[0]);
const player2 = new Player('blue', waypoints[0]);
// Timer
let startTime = null;
let elapsedTime = 0;
function drawTrack() {
// Draw outer circle
ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, TRACK_OUTER_RADIUS, 0, 2 * Math.PI);
ctx.fillStyle = '#888';
ctx.fill();
// Draw inner circle
ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, TRACK_INNER_RADIUS, 0, 2 * Math.PI);
ctx.fillStyle = '#555';
ctx.fill();
// Draw start/finish line
ctx.beginPath();
ctx.moveTo(canvas.width / 2, canvas.height / 2 - TRACK_OUTER_RADIUS);
ctx.lineTo(canvas.width / 2, canvas.height / 2 - TRACK_INNER_RADIUS);
ctx.strokeStyle = 'white';
ctx.lineWidth = 2;
ctx.stroke();
// Optionally, draw waypoints for visualization
/*
ctx.fillStyle = 'yellow';
waypoints.forEach(wp => {
ctx.beginPath();
ctx.arc(wp.x, wp.y, 3, 0, 2 * Math.PI);
ctx.fill();
});
*/
}
function updateScoreboard() {
document.getElementById('player1Score').textContent = `Player 1 Laps: ${player1.laps}`;
document.getElementById('player2Score').textContent = `Player 2 Laps: ${player2.laps}`;
document.getElementById('timer').textContent = `Time: ${elapsedTime.toFixed(2)}s`;
}
function gameLoop(timestamp) {
if(!startTime) startTime = timestamp;
elapsedTime = (timestamp - startTime) / 1000;
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw track
drawTrack();
// Update and draw players
player1.update();
player2.update();
player1.draw();
player2.draw();
// Update scoreboard
updateScoreboard();
requestAnimationFrame(gameLoop);
}
// Start the game loop
requestAnimationFrame(gameLoop);
</script>
</body>
</html>
Explanation of the Code
-
HTML Structure:
- A
<canvas> element with an id of gameCanvas is used to render the track and the players.
- The
scoreboard div displays the lap counts for both players and the race timer.
-
CSS Styling:
- The body has a dark background, and text is centered and styled for better visibility.
- The canvas is centrally placed with a fixed size of 800x800 pixels.
-
JavaScript Logic:
-
Track Drawing:
- A circular track is drawn using two concentric circles to represent the road (
TRACK_WIDTH of 35px).
- The
drawTrack function handles rendering the track on the canvas.
- Optionally, waypoints can be visualized by uncommenting the related section.
-
Waypoints:
- The
waypoints array contains 24 points (for 12 curves; each curve has 2 waypoints).
- These waypoints are placed alternately on the outer and inner radii to create curves.
-
Player Class:
- Each AI-controlled player has properties like position (
x, y), angle (direction), speed, currentWaypoint, and laps.
- The
update method moves the player towards the current waypoint. If the player is close enough to a waypoint, it updates to the next waypoint and increments the lap count if a full lap is completed.
- The
draw method visually represents the player as a colored triangle pointing in the direction of movement.
-
Game Loop:
- The
gameLoop function uses requestAnimationFrame to continuously update the game state and render the visuals.
- It calculates the elapsed time since the race started.
- It clears the canvas, redraws the track, updates and draws both players, and updates the scoreboard.
-
Scoring and Timer:
- The
updateScoreboard function updates the lap counts for both players and displays the elapsed time in seconds.
-
AI Behavior:
Potential Enhancements
- Collision Detection: Currently, players do not interact with each other or handle collisions. Implementing collision avoidance can make the AI more sophisticated.
- Laps Limit and Race Completion: Adding a race completion condition (e.g., first to 3 laps) can make the game more engaging.
- Improved AI Navigation: Incorporate more advanced pathfinding or physics-based movement for more realistic racing behavior.
- Graphics and Visuals: Enhance the track and player graphics for a more polished appearance.
- User Interaction: Allow users to start/restart the race or adjust AI difficulty.
This implementation provides a foundation for a simple AI racing game. Depending on your needs, you can expand and refine various aspects to create a more comprehensive experience.