html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Snake Game with Wrap & 3 Apples + Touch Buttons</title>
<style>
* {
box-sizing: border-box;
}
html, body {
height: 100%;
margin: 0;
background: linear-gradient(135deg, #0f2027, #203a43, #2c5364);
display: flex;
flex-direction: column;
align-items: center;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
}
#game-container {
position: relative;
width: 90vmin;
height: 90vmin;
max-width: 600px;
max-height: 600px;
background: #111;
border-radius: 20px;
box-shadow:
0 0 20px #00ff90,
inset 0 0 30px #00ff90;
touch-action: none; /* prevent default gestures */
}
canvas {
display: block;
width: 100%;
height: 100%;
border-radius: 20px;
background-color: #000;
}
#score {
position: absolute;
top: 10px;
left: 20px;
color: #00ff90;
font-weight: 700;
font-size: 1.4rem;
text-shadow: 0 0 8px #00ff90;
user-select: none;
z-index: 2;
}
#message {
position: absolute;
top: 50%;
left: 50%;
color: #00ff90;
font-size: 2rem;
font-weight: 700;
text-align: center;
transform: translate(-50%, -50%);
user-select: none;
display: none;
text-shadow: 0 0 10px #00ff90;
z-index: 3;
}
#btn-restart {
position: absolute;
top: 60%;
left: 50%;
transform: translate(-50%, -50%);
background: #00ff90;
border: none;
border-radius: 12px;
padding: 10px 20px;
font-weight: 700;
font-size: 1.1rem;
color: #002211;
cursor: pointer;
box-shadow: 0 0 15px #00ff90;
user-select: none;
display: none;
transition: background-color 0.3s ease;
z-index: 3;
}
#btn-restart:hover {
background-color: #00cc72;
}
/* Tiny sparkle effect for the food */
@keyframes sparkle {
0%, 100% {
opacity: 1;
transform: scale(1);
filter: brightness(1.4);
}
50% {
opacity: 0.7;
transform: scale(1.2);
filter: brightness(1);
}
}
.sparkle {
animation: sparkle 1.2s infinite ease-in-out;
}
/* Touch buttons container */
#controls {
margin-top: 15px;
display: grid;
grid-template-columns: repeat(3, 60px);
grid-template-rows: 60px 60px 60px;
gap: 12px;
user-select: none;
}
button.control-btn {
background: #00ff90;
border: none;
border-radius: 12px;
box-shadow: 0 0 10px #00ff90;
font-size: 1.4rem;
font-weight: 700;
color: #002211;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
transition: background-color 0.25s ease;
touch-action: manipulation;
}
button.control-btn:active {
background-color: #00cc72;
box-shadow: 0 0 20px #00cc72 inset;
}
/* Layout for arrow buttons nicely placed */
#btn-up {
grid-column: 2;
grid-row: 1;
}
#btn-left {
grid-column: 1;
grid-row: 2;
}
#btn-down {
grid-column: 2;
grid-row: 2;
}
#btn-right {
grid-column: 3;
grid-row: 2;
}
/* Hide the middle bottom cell */
#controls > div.empty {
grid-column: 2;
grid-row: 3;
}
</style>
</head>
<body>
<div id="game-container" role="main" aria-label="Snake game">
<canvas id="game" width="600" height="600" aria-live="polite" tabindex="0"></canvas>
<div id="score" aria-live="polite" aria-atomic="true">Score: 0</div>
<div id="message" role="alert"></div>
<button id="btn-restart" aria-label="Restart game">Restart</button>
</div>
<div id="controls" aria-label="Game controls">
<button id="btn-up" class="control-btn" aria-label="Move up" title="Up ▲">▲</button>
<button id="btn-left" class="control-btn" aria-label="Move left" title="Left ◄">◄</button>
<button id="btn-down" class="control-btn" aria-label="Move down" title="Down ▼">▼</button>
<button id="btn-right" class="control-btn" aria-label="Move right" title="Right ►">►</button>
</div>
<script>
(() => {
'use strict';
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const scoreElem = document.getElementById('score');
const messageElem = document.getElementById('message');
const btnRestart = document.getElementById('btn-restart');
const container = document.getElementById('game-container');
// Touch buttons
const btnUp = document.getElementById('btn-up');
const btnDown = document.getElementById('btn-down');
const btnLeft = document.getElementById('btn-left');
const btnRight = document.getElementById('btn-right');
// Game constants
const COLS = 30;
const ROWS = 30;
const CELL_SIZE = canvas.width / COLS; // 20px per cell
const SNAKE_COLOR = '#00ff90';
const SNAKE_BORDER = '#006644';
const FOOD_COLOR = '#ff0066';
const MAX_FOOD = 3;
// Directions
const DIRS = {
'ArrowUp': {x: 0, y: -1},
'ArrowDown': {x: 0, y: 1},
'ArrowLeft': {x: -1, y: 0},
'ArrowRight': {x:1, y: 0}
};
// Game state
let snake = [];
let direction = {x: 0, y: 0};
let nextDirection = {x: 0, y: 0};
let foods = [];
let score = 0;
let isRunning = false;
let gameLoopId = null;
// For touch controls
let touchStartX = null;
let touchStartY = null;
const SWIPE_THRESHOLD = 30; // minimum px to be considered swipe
// Initialization
function init() {
snake = [
{x: Math.floor(COLS / 2), y: Math.floor(ROWS / 2)},
{x: Math.floor(COLS / 2) - 1, y: Math.floor(ROWS / 2)},
{x: Math.floor(COLS / 2) - 2, y: Math.floor(ROWS / 2)},
];
direction = {x: 1, y: 0}; // initially moving right
nextDirection = {x: 1, y: 0};
score = 0;
scoreElem.textContent = 'Score: 0';
messageElem.style.display = 'none';
btnRestart.style.display = 'none';
isRunning = true;
foods = [];
for(let i = 0; i < MAX_FOOD; i++) {
placeFood();
}
draw();
if(gameLoopId) cancelAnimationFrame(gameLoopId);
gameLoopId = requestAnimationFrame(gameLoop);
}
// Place one food somewhere not occupied by the snake or existing foods
function placeFood() {
let tries = 0;
while(tries < 1000) {
let fx = Math.floor(Math.random() * COLS);
let fy = Math.floor(Math.random() * ROWS);
let collisionWithSnake = snake.some(s => s.x === fx && s.y === fy);
let collisionWithFood = foods.some(f => f.x === fx && f.y === fy);
if(!collisionWithSnake && !collisionWithFood) {
foods.push({x: fx, y: fy});
break;
}
tries++;
}
}
// Check collision with self only (walls wrap)
function checkCollision(head) {
// Only check if head collides with any snake segment except the last (since snake moves forward)
for(let i = 0; i < snake.length; i++) {
if(snake[i].x === head.x && snake[i].y === head.y) return true;
}
return false;
}
// Game loop variables
const speed = 8; // moves per second
let lastTime = 0;
const interval = 1000 / speed;
function gameLoop(timestamp) {
if(!lastTime) lastTime = timestamp;
const delta = timestamp - lastTime;
if(delta > interval) {
lastTime = timestamp - (delta % interval);
update();
draw();
}
if(isRunning) {
gameLoopId = requestAnimationFrame(gameLoop);
}
}
function update() {
// Update direction only if it's not opposite to current direction
if(!(nextDirection.x === -direction.x && nextDirection.y === -direction.y)) {
direction = nextDirection;
}
let head = {
x: (snake[0].x + direction.x + COLS) % COLS,
y: (snake[0].y + direction.y + ROWS) % ROWS
};
// Check collision with self
if(checkCollision(head)) {
gameOver();
return;
}
snake.unshift(head);
// Check if ate any food(s)
let ateFoodIndex = foods.findIndex(f => f.x === head.x && f.y === head.y);
if(ateFoodIndex !== -1) {
// Increase score
score++;
scoreElem.textContent = `Score: ${score}`;
// Remove eaten food and add a new one
foods.splice(ateFoodIndex, 1);
placeFood();
} else {
snake.pop();
}
}
function drawCell(x, y, color, borderColor, isFood = false) {
// Draw the main cell
ctx.fillStyle = color;
ctx.strokeStyle = borderColor;
ctx.lineWidth = 1.75;
ctx.lineJoin = 'round';
ctx.beginPath();
const padding = 1.5;
let cx = x * CELL_SIZE + padding;
let cy = y * CELL_SIZE + padding;
let size = CELL_SIZE - padding * 2;
// Rounded rect for smooth edges
let radius = size / 6;
ctx.moveTo(cx + radius, cy);
ctx.lineTo(cx + size - radius, cy);
ctx.quadraticCurveTo(cx + size, cy, cx + size, cy + radius);
ctx.lineTo(cx + size, cy + size - radius);
ctx.quadraticCurveTo(cx + size, cy + size, cx + size - radius, cy + size);
ctx.lineTo(cx + radius, cy + size);
ctx.quadraticCurveTo(cx, cy + size, cx, cy + size - radius);
ctx.lineTo(cx, cy + radius);
ctx.quadraticCurveTo(cx, cy, cx + radius, cy);
ctx.closePath();
ctx.fill();
ctx.stroke();
if(isFood) {
// Sparkle effect for food using little white dots around the food
ctx.fillStyle = 'rgba(255, 255, 255, 0.7)';
let sparkleCount = 6;
for(let i = 0; i < sparkleCount; i++) {
let angle = (Math.PI * 2 / sparkleCount) * i + Date.now() * 0.004;
let sparkleX = cx + size/2 + Math.cos(angle) * size/3;
let sparkleY = cy + size/2 + Math.sin(angle) * size/3;
ctx.beginPath();
ctx.arc(sparkleX, sparkleY, 1.7, 0, Math.PI * 2);
ctx.fill();
}
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw foods
foods.forEach(food => {
drawCell(food.x, food.y, FOOD_COLOR, '#b30047', true);
});
// Draw snake
snake.forEach((segment, i) => {
// head brighter
let color = i === 0 ? '#00ff90' : '#006644';
let borderColor = '#003322';
drawCell(segment.x, segment.y, color, borderColor);
});
}
function gameOver() {
isRunning = false;
messageElem.textContent = `Game over! Your score is ${score}.`;
messageElem.style.display = 'block';
btnRestart.style.display = 'block';
canvas.focus();
}
btnRestart.addEventListener('click', () => {
init();
canvas.focus();
});
// Keyboard controls
window.addEventListener('keydown', e => {
if (!isRunning) return;
if (DIRS[e.key]) {
e.preventDefault();
let newDir = DIRS[e.key];
// Prevent reversing
if(!(newDir.x === -direction.x && newDir.y === -direction.y))
nextDirection = newDir;
}
});
// Touch controls for swipe detection
container.addEventListener('touchstart', e => {
if(e.touches.length === 1) {
touchStartX = e.touches[0].clientX;
touchStartY = e.touches[0].clientY;
}
}, {passive: true});
container.addEventListener('touchmove', e => {
if(!touchStartX || !touchStartY) return;
let dx = e.touches[0].clientX - touchStartX;
let dy = e.touches[0].clientY - touchStartY;
if(Math.abs(dx) > SWIPE_THRESHOLD || Math.abs(dy) > SWIPE_THRESHOLD) {
// Determine swipe direction
if(Math.abs(dx) > Math.abs(dy)) {
// Horizontal swipe
if(dx > 0 && !(direction.x === -1 && direction.y === 0)) {
nextDirection = {x: 1, y: 0};
} else if(dx < 0 && !(direction.x === 1 && direction.y === 0)) {
nextDirection = {x: -1, y: 0};
}
} else {
// Vertical swipe
if(dy > 0 && !(direction.x === 0 && direction.y === -1)) {
nextDirection = {x:0, y:1};
} else if(dy < 0 && !(direction.x === 0 && direction.y === 1)) {
nextDirection = {x: 0, y: -1};
}
}
touchStartX = null;
touchStartY = null;
}
}, {passive: true});
container.addEventListener('touchend', e => {
touchStartX = null;
touchStartY = null;
});
// Touch buttons controls
function setDirection(dx, dy) {
// Prevent reversing direction
if(!(dx === -direction.x && dy === -direction.y)) {
nextDirection = {x: dx, y: dy};
}
}
btnUp.addEventListener('touchstart', e => {
e.preventDefault();
setDirection(0, -1);
}, {passive: false});
btnDown.addEventListener('touchstart', e => {
e.preventDefault();
setDirection(0, 1);
}, {passive: false});
btnLeft.addEventListener('touchstart', e => {
e.preventDefault();
setDirection(-1, 0);
}, {passive: false});
btnRight.addEventListener('touchstart', e => {
e.preventDefault();
setDirection(1, 0);
}, {passive: false});
// Also support mouse click on buttons for desktop/touch hybrid
btnUp.addEventListener('mousedown', e => {
e.preventDefault();
setDirection(0, -1);
});
btnDown.addEventListener('mousedown', e => {
e.preventDefault();
setDirection(0, 1);
});
btnLeft.addEventListener('mousedown', e => {
e.preventDefault();
setDirection(-1, 0);
});
btnRight.addEventListener('mousedown', e => {
e.preventDefault();
setDirection(1, 0);
});
// Focus canvas to enable keyboard arrow keys on desktop
canvas.setAttribute('tabindex', '0');
canvas.focus();
// Start the game
init();
})();
</script>
</body>
</html>