Certainly! Let's build an AI battle of Rock, Paper, Scissors. We'll create a web-based simulation where rocks, papers, and scissors move around the screen, chasing their targets and fleeing from their predators. When they catch their target, they'll convert it into their own type.
Project Files:
index.html - The main HTML file that sets up the structure of the page.
styles.css - The CSS file that styles the elements on the page.
script.js - The JavaScript file that contains the logic for the simulation.
images/ - A directory containing the images for rock, paper, and scissors icons.
1. index.html
Create an index.html file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AI Battle: Rock Paper Scissors</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script src="script.js"></script>
</body>
</html>
Explanation:
- We include a
<canvas> element with the id gameCanvas where we'll draw our simulation.
- We link to
styles.css in the <head> section.
- We include
script.js at the end of the <body> to ensure the DOM is loaded before the script runs.
2. styles.css
Create a styles.css file with the following content:
body {
margin: 0;
overflow: hidden;
}
#gameCanvas {
display: block;
background-color: #f0f0f0;
}
Explanation:
- We remove the default margin and hide the overflow of the body to make the canvas fill the screen without scrollbars.
- We set the canvas to display as a block element and give it a light gray background.
3. script.js
Create a script.js file with the following content:
// script.js
// Canvas setup
const canvas = document.getElementById('gameCanvas');
const context = canvas.getContext('2d');
// Resize canvas to fill the window
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Event listener to handle window resizing
window.addEventListener('resize', function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
// Load images
const rockImage = new Image();
rockImage.src = 'images/rock.png';
const paperImage = new Image();
paperImage.src = 'images/paper.png';
const scissorsImage = new Image();
scissorsImage.src = 'images/scissors.png';
// Entity class
class Entity {
constructor(type, x, y) {
this.type = type; // 'rock', 'paper', or 'scissors'
this.x = x;
this.y = y;
this.speed = 1 + Math.random(); // Random speed between 1 and 2
this.target = null; // The entity this one is chasing
this.predator = null; // The entity this one is fleeing from
this.size = 32; // Size of the entity image
}
draw() {
let image;
if (this.type === 'rock') {
image = rockImage;
} else if (this.type === 'paper') {
image = paperImage;
} else if (this.type === 'scissors') {
image = scissorsImage;
}
context.drawImage(image, this.x - this.size / 2, this.y - this.size / 2, this.size, this.size);
}
update() {
// Determine the target and predator types
let targetType, predatorType;
if (this.type === 'rock') {
targetType = 'scissors';
predatorType = 'paper';
} else if (this.type === 'paper') {
targetType = 'rock';
predatorType = 'scissors';
} else if (this.type === 'scissors') {
targetType = 'paper';
predatorType = 'rock';
}
// Find the nearest target and predator
this.target = findNearestEntity(this, targetType);
this.predator = findNearestEntity(this, predatorType);
// Movement vector
let dx = 0;
let dy = 0;
// Chase target
if (this.target) {
const tx = this.target.x - this.x;
const ty = this.target.y - this.y;
const distTarget = Math.hypot(tx, ty);
// Normalize vector towards target
if (distTarget > 0) {
dx += (tx / distTarget) * this.speed;
dy += (ty / distTarget) * this.speed;
}
// Check for collision with target
if (distTarget < this.size) {
// Convert the target into this entity's type
this.target.type = this.type;
}
}
// Flee from predator
if (this.predator) {
const px = this.predator.x - this.x;
const py = this.predator.y - this.y;
const distPredator = Math.hypot(px, py);
// Normalize vector away from predator
if (distPredator > 0) {
dx -= (px / distPredator) * this.speed * 2; // Move faster away from predator
dy -= (py / distPredator) * this.speed * 2;
}
}
// Update position
this.x += dx;
this.y += dy;
// Keep within bounds
if (this.x < 0) this.x = 0;
if (this.x > canvas.width) this.x = canvas.width;
if (this.y < 0) this.y = 0;
if (this.y > canvas.height) this.y = canvas.height;
}
}
// Array to hold all entities
const entities = [];
// Function to find the nearest entity of a given type
function findNearestEntity(entity, type) {
let minDist = Infinity;
let nearest = null;
for (let other of entities) {
if (other.type === type && other !== entity) {
const dx = other.x - entity.x;
const dy = other.y - entity.y;
const dist = Math.hypot(dx, dy);
if (dist < minDist) {
minDist = dist;
nearest = other;
}
}
}
return nearest;
}
// Initialize entities
function initEntities() {
const numberOfEachType = 20;
for (let i = 0; i < numberOfEachType; i++) {
// Random positions
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
entities.push(new Entity('rock', x, y));
}
for (let i = 0; i < numberOfEachType; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
entities.push(new Entity('paper', x, y));
}
for (let i = 0; i < numberOfEachType; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
entities.push(new Entity('scissors', x, y));
}
}
// Animation loop
function animate() {
requestAnimationFrame(animate);
// Clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// Update and draw entities
for (let entity of entities) {
entity.update();
entity.draw();
}
}
// Start simulation after images are loaded
let imagesLoaded = 0;
function checkImagesLoaded() {
imagesLoaded++;
if (imagesLoaded === 3) {
initEntities();
animate();
}
}
rockImage.onload = checkImagesLoaded;
paperImage.onload = checkImagesLoaded;
scissorsImage.onload = checkImagesLoaded;
Explanation:
- Canvas Setup: We set up the canvas and ensure it fills the window. We handle window resizing to adjust the canvas size accordingly.
- Loading Images: We load images for rock, paper, and scissors. You'll need to provide these images in the
images/ directory.
- Entity Class:
- Each entity has a type (
rock, paper, or scissors), position (x, y), speed, target, and predator.
- The
draw() method draws the entity on the canvas using the appropriate image.
- The
update() method:
- Determines its target type (which it should chase) and predator type (which it should flee from).
- Finds the nearest entity of both types.
- Calculates movement vectors to chase the target and flee from the predator.
- Updates its position and ensures it stays within the canvas bounds.
- Checks for collision with the target and converts the target into its type if they collide.
- Entity Management:
- We have an array
entities that holds all entities in the simulation.
- The function
findNearestEntity() finds the closest entity of a given type.
- Initialization:
- The
initEntities() function creates a set number of each type of entity and places them at random positions.
- Animation Loop:
- The
animate() function is the main loop that updates and draws each entity every frame.
- We use
requestAnimationFrame() for smooth animations.
- Starting the Simulation:
- We wait for all images to load before starting the simulation.
- Once all images are loaded, we call
initEntities() and start the animation loop with animate().
4. Images
You'll need to add images for the rock, paper, and scissors. Create an images/ directory in your project root and add the following images:
images/rock.png
images/paper.png
images/scissors.png
You can use any images you like. If you need placeholder images, you can use the following links to download icons:
(Note: Replace the example URLs with actual image URLs or upload your own images to the images/ folder.)
Additional Notes
- Entity Interaction: Entities only interact with the nearest target and predator to simplify the logic.
- Performance: With many entities, performance may decrease. Adjust the
numberOfEachType variable as needed.
- Enhancements: You can enhance the simulation by adding more sophisticated AI behaviors, collision detection improvements, or visual effects.
Enjoy your AI battle of Rock, Paper, Scissors!