Certainly! I can help you create an HTML page with JavaScript that simulates 1000 red and 1000 yellow balls bouncing around, rotating, and shooting bullets every 5 seconds. The balls will shoot bullets in random directions, and we'll see which color remains at the end.
Here's how you can proceed:
Overview:
- Canvas Setup: Use HTML5 Canvas to render the animation.
- Ball Mechanics: Each ball moves, rotates, and bounces within the canvas boundaries.
- Bullet Mechanics: Every 5 seconds, each ball shoots a bullet in a random direction.
- Collision Detection: Bullets can eliminate balls of the opposite color upon collision.
- End Condition: The simulation ends when only one color remains.
Step-by-Step Guide:
1. Create the HTML Structure
Start by creating an HTML file with a canvas element that fills the entire screen.
<!DOCTYPE html>
<html>
<head>
<title>Ball Battle Simulation</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="simulation.js"></script>
</body>
</html>
2. Set Up the Canvas
In your simulation.js file, get the canvas context and set the canvas size to fill the window.
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
3. Define the Ball Class
Each ball will have properties for position, velocity, color, and methods to update and draw itself.
class Ball {
constructor(x, y, vx, vy, color) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.color = color;
this.radius = 5;
this.angle = Math.random() * Math.PI * 2;
}
update() {
this.x += this.vx;
this.y += this.vy;
this.angle += 0.05;
// Bounce off walls
if (this.x - this.radius < 0 || this.x + this.radius > canvas.width) {
this.vx *= -1;
}
if (this.y - this.radius < 0 || this.y + this.radius > canvas.height) {
this.vy *= -1;
}
}
draw() {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(0, 0, this.radius, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
}
4. Define the Bullet Class
Bullets move in a straight line and can eliminate balls of the opposite color upon collision.
class Bullet {
constructor(x, y, vx, vy, shooterColor) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.radius = 2;
this.shooterColor = shooterColor;
}
update() {
this.x += this.vx;
this.y += this.vy;
}
draw() {
ctx.fillStyle = 'black';
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fill();
}
}
5. Initialize Balls
Create arrays to hold the balls and bullets, and initialize the balls with random positions and velocities.
let balls = [];
let bullets = [];
// Function to create balls of a specific color
function createBalls(count, color) {
for (let i = 0; i < count; i++) {
let x = Math.random() * canvas.width;
let y = Math.random() * canvas.height;
let vx = (Math.random() - 0.5) * 2;
let vy = (Math.random() - 0.5) * 2;
balls.push(new Ball(x, y, vx, vy, color));
}
}
createBalls(1000, 'red');
createBalls(1000, 'yellow');
6. Shooting Mechanism
Every 5 seconds, each ball shoots a bullet in a random direction.
function shootBullets() {
balls.forEach(ball => {
let angle = Math.random() * Math.PI * 2;
let speed = 3;
let vx = Math.cos(angle) * speed;
let vy = Math.sin(angle) * speed;
bullets.push(new Bullet(ball.x, ball.y, vx, vy, ball.color));
});
}
setInterval(shootBullets, 5000);
7. Collision Detection
Check if bullets hit balls of the opposite color and remove both upon collision.
function detectCollisions() {
bullets.forEach((bullet, bulletIndex) => {
balls.forEach((ball, ballIndex) => {
if (bullet.shooterColor === ball.color) return;
let dx = bullet.x - ball.x;
let dy = bullet.y - ball.y;
let distance = Math.hypot(dx, dy);
if (distance < bullet.radius + ball.radius) {
// Remove the ball and the bullet
balls.splice(ballIndex, 1);
bullets.splice(bulletIndex, 1);
}
});
});
}
8. Animation Loop
Render the balls and bullets, update their positions, and check for collisions.
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
balls.forEach(ball => {
ball.update();
ball.draw();
});
bullets.forEach((bullet, index) => {
bullet.update();
bullet.draw();
// Remove bullets that are out of bounds
if (
bullet.x < 0 || bullet.x > canvas.width ||
bullet.y < 0 || bullet.y > canvas.height
) {
bullets.splice(index, 1);
}
});
detectCollisions();
// Check for end condition
const redBallsLeft = balls.some(ball => ball.color === 'red');
const yellowBallsLeft = balls.some(ball => ball.color === 'yellow');
if (!redBallsLeft || !yellowBallsLeft) {
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'white';
ctx.font = '48px Arial';
let winner = redBallsLeft ? 'Red' : 'Yellow';
ctx.fillText(`${winner} wins!`, canvas.width / 2 - 100, canvas.height / 2);
return;
}
requestAnimationFrame(animate);
}
animate();
9. Final Touches
Save your simulation.js file and open the HTML file in a web browser to see the simulation in action.
Additional Notes
- Performance Optimization: With a large number of balls and bullets, performance may slow down. Consider optimizing collision detection using spatial partitioning (like quad-trees) if necessary.
- Visual Enhancements: You can add more visual flair by adjusting ball sizes, colors, and adding effects.
- Interactivity: Implement controls to start, pause, or reset the simulation as desired.
Full simulation.js Code
For your convenience, here's the entire simulation.js file combined:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
class Ball {
constructor(x, y, vx, vy, color) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.color = color;
this.radius = 5;
this.angle = Math.random() * Math.PI * 2;
}
update() {
this.x += this.vx;
this.y += this.vy;
this.angle += 0.05;
// Bounce off walls
if (this.x - this.radius < 0 || this.x + this.radius > canvas.width) {
this.vx *= -1;
}
if (this.y - this.radius < 0 || this.y + this.radius > canvas.height) {
this.vy *= -1;
}
}
draw() {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(0, 0, this.radius, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
}
class Bullet {
constructor(x, y, vx, vy, shooterColor) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.radius = 2;
this.shooterColor = shooterColor;
}
update() {
this.x += this.vx;
this.y += this.vy;
}
draw() {
ctx.fillStyle = 'black';
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fill();
}
}
let balls = [];
let bullets = [];
function createBalls(count, color) {
for (let i = 0; i < count; i++) {
let x = Math.random() * canvas.width;
let y = Math.random() * canvas.height;
let vx = (Math.random() - 0.5) * 2;
let vy = (Math.random() - 0.5) * 2;
balls.push(new Ball(x, y, vx, vy, color));
}
}
createBalls(1000, 'red');
createBalls(1000, 'yellow');
function shootBullets() {
balls.forEach(ball => {
let angle = Math.random() * Math.PI * 2;
let speed = 3;
let vx = Math.cos(angle) * speed;
let vy = Math.sin(angle) * speed;
bullets.push(new Bullet(ball.x, ball.y, vx, vy, ball.color));
});
}
setInterval(shootBullets, 5000);
function detectCollisions() {
bullets.forEach((bullet, bulletIndex) => {
balls.forEach((ball, ballIndex) => {
if (bullet.shooterColor === ball.color) return;
let dx = bullet.x - ball.x;
let dy = bullet.y - ball.y;
let distance = Math.hypot(dx, dy);
if (distance < bullet.radius + ball.radius) {
// Remove the ball and the bullet
balls.splice(ballIndex, 1);
bullets.splice(bulletIndex, 1);
}
});
});
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
balls.forEach(ball => {
ball.update();
ball.draw();
});
bullets.forEach((bullet, index) => {
bullet.update();
bullet.draw();
// Remove bullets that are out of bounds
if (
bullet.x < 0 || bullet.x > canvas.width ||
bullet.y < 0 || bullet.y > canvas.height
) {
bullets.splice(index, 1);
}
});
detectCollisions();
// Check for end condition
const redBallsLeft = balls.some(ball => ball.color === 'red');
const yellowBallsLeft = balls.some(ball => ball.color === 'yellow');
if (!redBallsLeft || !yellowBallsLeft) {
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'white';
ctx.font = '48px Arial';
let winner = redBallsLeft ? 'Red' : 'Yellow';
ctx.fillText(`${winner} wins!`, canvas.width / 2 - 100, canvas.height / 2);
return;
}
requestAnimationFrame(animate);
}
animate();
Enjoy your simulation! If you have any questions or need further customization, feel free to ask.