Make web game using HTML + JS (one file) where we should slice strawberries (draw them)
- User
Make web game using HTML + JS (one file) where we should slice strawberries (draw them)
- Assistant
Make web game using HTML + JS (one file) where we should slice strawberries (draw them)
Certainly! Below is the code for a simple web game where strawberries appear on the screen, and you can slice them by drawing over them with your mouse or touch input. The game is implemented in a single HTML file using HTML5 Canvas and JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Strawberry Slicing Game</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; background: #222; }
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script>
// Get the canvas and context
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Set canvas to full screen
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Strawberry image (Base64 encoded)
const strawberryImg = new Image();
strawberryImg.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAb1BMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAClpKTGxsbc3NyZmZnh4eHk5OTq6uq1tbXv7+/w8PDy8vLp6eni4uLg4ODiYmKdXV3a2trc3NywsLDFxcXg4ODm5ubq6urx8fH09PT19fXz8/P2tra7F28ZAAAAM3RSTlMAAwQLFxgaHCAnKDRHWV1eY26jo6+zt7jLz9Db5vL5+/v8/f6+vfD06+LU1xHYCgAAAJFJREFUGNNljVsSgCAMBZEgnBV4bM0CNvz/d6OSiU/GAWKpt+6K4AdkEbkZ9JGsHZwJ4CBr7K8kUAGgkLlAsISCnaqxG6XUvBFCdxnnEdVcUCFG0EoQSqb32NsE4sxHACBW2m7nFzc5EE+VmmY3zDE3dH992LpGo2ZMsFM3ZPJffzQ8Y+0AAAAASUVORK5CYII=';
// Variables
let strawberries = [];
let slicedStrawberries = [];
let isDrawing = false;
let lastPos = null;
// Strawberry class
class Strawberry {
constructor(x, y, dx, dy) {
this.x = x;
this.y = y;
this.dx = dx; // Velocity in x
this.dy = dy; // Velocity in y
this.radius = 20;
this.sliced = false;
}
draw() {
if (!this.sliced) {
ctx.drawImage(strawberryImg, this.x - this.radius, this.y - this.radius, 40, 40);
}
}
update() {
this.x += this.dx;
this.y += this.dy;
this.dy += 0.1; // Gravity
}
}
// Spawn strawberries periodically
function spawnStrawberry() {
let x = Math.random() * canvas.width;
let y = canvas.height + 20;
let dx = (Math.random() - 0.5) * 4;
let dy = - (6 + Math.random() * 4);
strawberries.push(new Strawberry(x, y, dx, dy));
}
setInterval(spawnStrawberry, 1000);
// Handle mouse/touch events
function startDrawing(e) {
isDrawing = true;
lastPos = getPos(e);
}
function stopDrawing() {
isDrawing = false;
lastPos = null;
}
function draw(e) {
if (!isDrawing) return;
let pos = getPos(e);
checkSlice(lastPos, pos);
lastPos = pos;
}
function getPos(e) {
let rect = canvas.getBoundingClientRect();
if (e.touches) {
return {
x: e.touches[0].clientX - rect.left,
y: e.touches[0].clientY - rect.top
};
} else {
return {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
}
}
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('touchstart', startDrawing);
canvas.addEventListener('touchmove', draw);
canvas.addEventListener('touchend', stopDrawing);
// Check for slicing
function checkSlice(p1, p2) {
strawberries.forEach(function(strawberry) {
if (!strawberry.sliced && lineIntersectsCircle(p1, p2, strawberry)) {
strawberry.sliced = true;
slicedStrawberries.push(strawberry);
}
});
}
function lineIntersectsCircle(p1, p2, circle) {
// Calculate the distance from the line segment to the center of the circle
let A = p2.x - p1.x;
let B = p2.y - p1.y;
let C = circle.x - p1.x;
let D = circle.y - p1.y;
let dot = A * C + B * D;
let len_sq = A * A + B * B;
let param = -1;
if (len_sq != 0) //in case of 0 length line
param = dot / len_sq;
let xx, yy;
if (param < 0) {
xx = p1.x;
yy = p1.y;
}
else if (param > 1) {
xx = p2.x;
yy = p2.y;
}
else {
xx = p1.x + param * A;
yy = p1.y + param * B;
}
let dx = circle.x - xx;
let dy = circle.y - yy;
return (dx * dx + dy * dy) < (circle.radius * circle.radius);
}
// Main game loop
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
strawberries.forEach(function(strawberry, index) {
strawberry.update();
strawberry.draw();
// Remove strawberries that are off-screen or sliced
if (strawberry.y > canvas.height + 50 || strawberry.sliced) {
strawberries.splice(index, 1);
}
});
// Draw slicing line (optional)
if (isDrawing && lastPos) {
ctx.beginPath();
ctx.strokeStyle = 'white';
ctx.lineWidth = 2;
ctx.moveTo(lastPos.x, lastPos.y);
ctx.lineTo(lastPos.x + 1, lastPos.y + 1);
ctx.stroke();
}
requestAnimationFrame(gameLoop);
}
// Start the game
gameLoop();
// Adjust canvas size on window resize
window.addEventListener('resize', function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
Explanation:
Canvas Setup:
<canvas> element fills the entire browser window for an immersive experience.#222) to make the strawberries stand out.Strawberry Implementation:
Strawberry class defines each strawberry's properties and methods.
x, y) and movement (dx, dy) simulate the strawberry's trajectory.draw() method renders the strawberry image if it hasn't been sliced.User Interaction:
checkSlice() function detects if the line intersects any strawberries using the lineIntersectsCircle() helper function.Collision Detection:
Game Loop:
gameLoop() function updates the game state and renders the scene.
requestAnimationFrame() for smooth animations.Strawberry Image:
strawberryImg.src = 'strawberry.png';
How to Run the Game:
Save the Code:
.html extension, e.g., strawberry_slicing_game.html.Open in a Browser:
Play:
Possible Enhancements:
Scoring System:
ctx.fillText() method.Sliced Animation:
Sound Effects:
Multiple Fruit Types:
Game Modes and Difficulty:
Responsive Design:
Notes:
Make sure your browser allows for running JavaScript from local files. If you encounter any issues, you can serve the file using a simple local web server (e.g., Live Server extension in VSCode or python -m http.server).
Remember that intensive graphics operations can be performance-heavy on low-end devices; optimizing the number of strawberries and their update frequency can help maintain smooth performance.
Feel free to modify and expand upon this basic game to make it more engaging and tailored to your preferences!
If you have any questions or need further assistance, please let me know.
Not yet included in a published release.