Make it so that when you hit the wall it goes through and comes back the opposite side
Assistant
User
Make it look cooler
Assistant
Certainly! Here's a simple implementation of the classic Snake game in HTML, CSS, and JavaScript that supports touchscreen controls with on-screen arrow buttons. You can run this code in any modern browser on desktop or mobile.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Snake Game - Touchscreen Friendly</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
background: #000;
color: #eee;
font-family: monospace, monospace;
margin: 0;
height: 100vh;
justify-content: center;
}
canvas {
background: #111;
border: 2px solid #eee;
touch-action: none; /* prevent scrolling while swiping */
}
#controls {
margin-top: 10px;
display: grid;
grid-template-columns: 60px 60px 60px;
grid-template-rows: 60px 60px 60px;
gap: 10px;
user-select: none;
}
button {
background: #222;
border: 2px solid #eee;
border-radius: 8px;
color: #eee;
font-size: 24px;
font-weight: bold;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
button:active {
background: #fff;
color: #000;
}
/* Position arrows in a directional pad layout */
#up {
grid-column: 2;
grid-row: 1;
}
#left {
grid-column: 1;
grid-row: 2;
}
#down {
grid-column: 2;
grid-row: 2;
}
#right {
grid-column: 3;
grid-row: 2;
}
</style>
</head>
<body>
<canvas id="game" width="400" height="400"></canvas>
<div id="controls">
<button id="up">↑</button>
<button id="left">←</button>
<button id="down">↓</button>
<button id="right">→</button>
</div>
<script>
(() => {
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const gridSize = 20; // number of grid cells each row/col
const cellSize = canvas.width / gridSize;
let snake = [{ x: 10, y: 10 }];
let direction = { x: 0, y: 0 };
let food = null;
let gameOver = false;
let score = 0;
// Place food in a free position
function placeFood() {
let x, y, collision;
do {
x = Math.floor(Math.random() * gridSize);
y = Math.floor(Math.random() * gridSize);
collision = snake.some(s => s.x === x && s.y === y);
} while (collision);
food = { x, y };
}
function drawCell(x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x * cellSize, y * cellSize, cellSize - 1, cellSize - 1);
}
function reset() {
snake = [{ x: 10, y: 10 }];
direction = { x: 0, y: 0 };
gameOver = false;
score = 0;
placeFood();
}
function update() {
if (gameOver) return;
if (direction.x === 0 && direction.y === 0) return; // not moving yet
// move snake by adding new head
const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
// check collisions
if (
head.x < 0 || head.x >= gridSize ||
head.y < 0 || head.y >= gridSize ||
snake.some(s => s.x === head.x && s.y === head.y)
) {
gameOver = true;
alert(`Game Over! Your score: ${score}`);
reset();
return;
}
snake.unshift(head);
// check if food eaten
if (head.x === food.x && head.y === food.y) {
score++;
placeFood();
} else {
snake.pop();
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw food
drawCell(food.x, food.y, 'red');
// draw snake
snake.forEach((segment, i) => {
drawCell(segment.x, segment.y, i === 0 ? '#0f0' : '#080');
});
// display score
ctx.fillStyle = '#eee';
ctx.font = '18px monospace';
ctx.fillText(`Score: ${score}`, 10, canvas.height - 10);
}
// Configure controls
function setDirection(x, y) {
// prevent reverse direction instantly
if (direction.x === -x && direction.y === -y) return;
direction = { x, y };
}
// Arrow button events
document.getElementById('up').addEventListener('touchstart', e => { e.preventDefault(); setDirection(0, -1); });
document.getElementById('down').addEventListener('touchstart', e => { e.preventDefault(); setDirection(0, 1); });
document.getElementById('left').addEventListener('touchstart', e => { e.preventDefault(); setDirection(-1, 0); });
document.getElementById('right').addEventListener('touchstart', e => { e.preventDefault(); setDirection(1, 0); });
// For mouse users too (desktop support)
document.getElementById('up').addEventListener('mousedown', e => { e.preventDefault(); setDirection(0, -1); });
document.getElementById('down').addEventListener('mousedown', e => { e.preventDefault(); setDirection(0, 1); });
document.getElementById('left').addEventListener('mousedown', e => { e.preventDefault(); setDirection(-1, 0); });
document.getElementById('right').addEventListener('mousedown', e => { e.preventDefault(); setDirection(1, 0); });
// Support swipe gestures on canvas for extra touch control
let touchStartX = 0;
let touchStartY = 0;
const swipeThreshold = 30;
canvas.addEventListener('touchstart', e => {
const touch = e.touches[0];
touchStartX = touch.clientX;
touchStartY = touch.clientY;
});
canvas.addEventListener('touchmove', e => {
if (e.touches.length > 1) return; // ignore multi-touch
const touch = e.touches[0];
const dx = touch.clientX - touchStartX;
const dy = touch.clientY - touchStartY;
if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > swipeThreshold) {
// horizontal swipe
if (dx > 0) setDirection(1, 0);
else setDirection(-1, 0);
touchStartX = touch.clientX;
touchStartY = touch.clientY;
} else if (Math.abs(dy) > swipeThreshold) {
// vertical swipe
if (dy > 0) setDirection(0, 1);
else setDirection(0, -1);
touchStartX = touch.clientX;
touchStartY = touch.clientY;
}
});
reset();
function gameLoop() {
update();
draw();
}
setInterval(gameLoop, 100); // 10 frames per second
})();
</script>
</body>
</html>
How this works:
The game draws a 20x20 grid.
The snake is represented by an array of {x,y} coordinate segments.
Food appears randomly in places not occupied by the snake.
You control the snake by pressing on-screen arrow buttons or swiping on the canvas.
The arrow buttons trigger snake direction changes when tapped.
The swipe gesture on the canvas also changes the direction, enhancing the touchscreen experience.
When the snake hits the wall or itself, the game ends and resets with an alert showing your score.
Open this page on a touchscreen device, and you can play with the big arrow buttons or swipe to control.
If you want any additions or further improvements, feel free to ask!
Sure! I've updated the code so that 3 apples spawn at once instead of one. The snake can eat any of the apples, and when it eats one, that apple is removed and a new one spawns in a free spot (always keeping 3 apples on the board).
Here is the updated version with multiple apples:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Snake Game with 3 Apples - Touchscreen Friendly</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
background: #000;
color: #eee;
font-family: monospace, monospace;
margin: 0;
height: 100vh;
justify-content: center;
}
canvas {
background: #111;
border: 2px solid #eee;
touch-action: none; /* prevent scrolling while swiping */
}
#controls {
margin-top: 10px;
display: grid;
grid-template-columns: 60px 60px 60px;
grid-template-rows: 60px 60px 60px;
gap: 10px;
user-select: none;
}
button {
background: #222;
border: 2px solid #eee;
border-radius: 8px;
color: #eee;
font-size: 24px;
font-weight: bold;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
button:active {
background: #fff;
color: #000;
}
/* Position arrows in a directional pad layout */
#up {
grid-column: 2;
grid-row: 1;
}
#left {
grid-column: 1;
grid-row: 2;
}
#down {
grid-column: 2;
grid-row: 2;
}
#right {
grid-column: 3;
grid-row: 2;
}
</style>
</head>
<body>
<canvas id="game" width="400" height="400"></canvas>
<div id="controls">
<button id="up">↑</button>
<button id="left">←</button>
<button id="down">↓</button>
<button id="right">→</button>
</div>
<script>
(() => {
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const gridSize = 20; // number of grid cells each row/col
const cellSize = canvas.width / gridSize;
let snake = [{ x: 10, y: 10 }];
let direction = { x: 0, y: 0 };
let foods = [];
const maxFoods = 3;
let gameOver = false;
let score = 0;
// Place one food in a free position (not inside the snake or existing food)
function placeFood() {
let x, y, collision;
do {
x = Math.floor(Math.random() * gridSize);
y = Math.floor(Math.random() * gridSize);
collision = snake.some(s => s.x === x && s.y === y) ||
foods.some(f => f.x === x && f.y === y);
} while (collision);
foods.push({ x, y });
}
function drawCell(x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x * cellSize, y * cellSize, cellSize - 1, cellSize - 1);
}
function reset() {
snake = [{ x: 10, y: 10 }];
direction = { x: 0, y: 0 };
gameOver = false;
score = 0;
foods = [];
for (let i = 0; i < maxFoods; i++) {
placeFood();
}
}
function update() {
if (gameOver) return;
if (direction.x === 0 && direction.y === 0) return; // not moving yet
// move snake by adding new head
const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
// check collisions
if (
head.x < 0 || head.x >= gridSize ||
head.y < 0 || head.y >= gridSize ||
snake.some(s => s.x === head.x && s.y === head.y)
) {
gameOver = true;
alert(`Game Over! Your score: ${score}`);
reset();
return;
}
snake.unshift(head);
// Check if eaten any food
const foodIndex = foods.findIndex(f => f.x === head.x && f.y === head.y);
if (foodIndex !== -1) {
score++;
// Remove eaten food
foods.splice(foodIndex, 1);
// Spawn a new food to maintain count
placeFood();
} else {
snake.pop();
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw foods (apples)
foods.forEach(food => {
drawCell(food.x, food.y, 'red');
});
// draw snake
snake.forEach((segment, i) => {
drawCell(segment.x, segment.y, i === 0 ? '#0f0' : '#080');
});
// display score
ctx.fillStyle = '#eee';
ctx.font = '18px monospace';
ctx.fillText(`Score: ${score}`, 10, canvas.height - 10);
}
// Configure controls
function setDirection(x, y) {
// prevent reverse direction instantly
if (direction.x === -x && direction.y === -y) return;
direction = { x, y };
}
// Arrow button events
document.getElementById('up').addEventListener('touchstart', e => { e.preventDefault(); setDirection(0, -1); });
document.getElementById('down').addEventListener('touchstart', e => { e.preventDefault(); setDirection(0, 1); });
document.getElementById('left').addEventListener('touchstart', e => { e.preventDefault(); setDirection(-1, 0); });
document.getElementById('right').addEventListener('touchstart', e => { e.preventDefault(); setDirection(1, 0); });
// For mouse users too (desktop support)
document.getElementById('up').addEventListener('mousedown', e => { e.preventDefault(); setDirection(0, -1); });
document.getElementById('down').addEventListener('mousedown', e => { e.preventDefault(); setDirection(0, 1); });
document.getElementById('left').addEventListener('mousedown', e => { e.preventDefault(); setDirection(-1, 0); });
document.getElementById('right').addEventListener('mousedown', e => { e.preventDefault(); setDirection(1, 0); });
// Support swipe gestures on canvas for extra touch control
let touchStartX = 0;
let touchStartY = 0;
const swipeThreshold = 30;
canvas.addEventListener('touchstart', e => {
const touch = e.touches[0];
touchStartX = touch.clientX;
touchStartY = touch.clientY;
});
canvas.addEventListener('touchmove', e => {
if (e.touches.length > 1) return; // ignore multi-touch
const touch = e.touches[0];
const dx = touch.clientX - touchStartX;
const dy = touch.clientY - touchStartY;
if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > swipeThreshold) {
// horizontal swipe
if (dx > 0) setDirection(1, 0);
else setDirection(-1, 0);
touchStartX = touch.clientX;
touchStartY = touch.clientY;
} else if (Math.abs(dy) > swipeThreshold) {
// vertical swipe
if (dy > 0) setDirection(0, 1);
else setDirection(0, -1);
touchStartX = touch.clientX;
touchStartY = touch.clientY;
}
});
reset();
function gameLoop() {
update();
draw();
}
setInterval(gameLoop, 100); // 10 frames per second
})();
</script>
</body>
</html>
What’s changed:
foods is an array holding the current apples (3 at all times).
The placeFood() function makes sure to avoid snake and existing foods.
When the snake eats one apple, it disappears and a new one appears elsewhere.
The draw code renders all apples.
The score increments by 1 for each apple eaten as normal.
Open this on a touchscreen device or desktop and enjoy Snake with 3 apples! If you want other features or tweaks, let me know!
Certainly! To make the snake wrap around the edges (i.e., going through one wall brings it back on the opposite side), we just need to modify the collision check with the walls and instead of ending the game, we "teleport" the snake head to the opposite edge.
Here is the updated code with wrap-around walls:
html
<!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-around Walls and 3 Apples</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
background: #000;
color: #eee;
font-family: monospace, monospace;
margin: 0;
height: 100vh;
justify-content: center;
}
canvas {
background: #111;
border: 2px solid #eee;
touch-action: none; /* prevent scrolling while swiping */
}
#controls {
margin-top: 10px;
display: grid;
grid-template-columns: 60px 60px 60px;
grid-template-rows: 60px 60px 60px;
gap: 10px;
user-select: none;
}
button {
background: #222;
border: 2px solid #eee;
border-radius: 8px;
color: #eee;
font-size: 24px;
font-weight: bold;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
button:active {
background: #fff;
color: #000;
}
/* Position arrows in a directional pad layout */
#up {
grid-column: 2;
grid-row: 1;
}
#left {
grid-column: 1;
grid-row: 2;
}
#down {
grid-column: 2;
grid-row: 2;
}
#right {
grid-column: 3;
grid-row: 2;
}
</style>
</head>
<body>
<canvas id="game" width="400" height="400"></canvas>
<div id="controls">
<button id="up">↑</button>
<button id="left">←</button>
<button id="down">↓</button>
<button id="right">→</button>
</div>
<script>
(() => {
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const gridSize = 20; // number of grid cells each row/col
const cellSize = canvas.width / gridSize;
let snake = [{ x: 10, y: 10 }];
let direction = { x: 0, y: 0 };
let foods = [];
const maxFoods = 3;
let gameOver = false;
let score = 0;
// Place one food in a free position (not inside the snake or existing food)
function placeFood() {
let x, y, collision;
do {
x = Math.floor(Math.random() * gridSize);
y = Math.floor(Math.random() * gridSize);
collision = snake.some(s => s.x === x && s.y === y) ||
foods.some(f => f.x === x && f.y === y);
} while (collision);
foods.push({ x, y });
}
function drawCell(x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x * cellSize, y * cellSize, cellSize - 1, cellSize - 1);
}
function reset() {
snake = [{ x: 10, y: 10 }];
direction = { x: 0, y: 0 };
gameOver = false;
score = 0;
foods = [];
for (let i = 0; i < maxFoods; i++) {
placeFood();
}
}
function update() {
if (gameOver) return;
if (direction.x === 0 && direction.y === 0) return; // not moving yet
// move snake by adding new head,
// apply wrap-around rules:
let newX = snake[0].x + direction.x;
let newY = snake[0].y + direction.y;
if (newX < 0) newX = gridSize - 1;
else if (newX >= gridSize) newX = 0;
if (newY < 0) newY = gridSize - 1;
else if (newY >= gridSize) newY = 0;
const head = { x: newX, y: newY };
// check collision with self only (walls are passed through)
if (snake.some(s => s.x === head.x && s.y === head.y)) {
gameOver = true;
alert(`Game Over! Your score: ${score}`);
reset();
return;
}
snake.unshift(head);
// Check if eaten any food
const foodIndex = foods.findIndex(f => f.x === head.x && f.y === head.y);
if (foodIndex !== -1) {
score++;
// Remove eaten food
foods.splice(foodIndex, 1);
// Spawn a new food to maintain count
placeFood();
} else {
snake.pop();
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw foods (apples)
foods.forEach(food => {
drawCell(food.x, food.y, 'red');
});
// draw snake
snake.forEach((segment, i) => {
drawCell(segment.x, segment.y, i === 0 ? '#0f0' : '#080');
});
// display score
ctx.fillStyle = '#eee';
ctx.font = '18px monospace';
ctx.fillText(`Score: ${score}`, 10, canvas.height - 10);
}
// Configure controls
function setDirection(x, y) {
// prevent reverse direction instantly
if (direction.x === -x && direction.y === -y) return;
direction = { x, y };
}
// Arrow button events
document.getElementById('up').addEventListener('touchstart', e => { e.preventDefault(); setDirection(0, -1); });
document.getElementById('down').addEventListener('touchstart', e => { e.preventDefault(); setDirection(0, 1); });
document.getElementById('left').addEventListener('touchstart', e => { e.preventDefault(); setDirection(-1, 0); });
document.getElementById('right').addEventListener('touchstart', e => { e.preventDefault(); setDirection(1, 0); });
// For mouse users too (desktop support)
document.getElementById('up').addEventListener('mousedown', e => { e.preventDefault(); setDirection(0, -1); });
document.getElementById('down').addEventListener('mousedown', e => { e.preventDefault(); setDirection(0, 1); });
document.getElementById('left').addEventListener('mousedown', e => { e.preventDefault(); setDirection(-1, 0); });
document.getElementById('right').addEventListener('mousedown', e => { e.preventDefault(); setDirection(1, 0); });
// Support swipe gestures on canvas for extra touch control
let touchStartX = 0;
let touchStartY = 0;
const swipeThreshold = 30;
canvas.addEventListener('touchstart', e => {
const touch = e.touches[0];
touchStartX = touch.clientX;
touchStartY = touch.clientY;
});
canvas.addEventListener('touchmove', e => {
if (e.touches.length > 1) return; // ignore multi-touch
const touch = e.touches[0];
const dx = touch.clientX - touchStartX;
const dy = touch.clientY - touchStartY;
if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > swipeThreshold) {
// horizontal swipe
if (dx > 0) setDirection(1, 0);
else setDirection(-1, 0);
touchStartX = touch.clientX;
touchStartY = touch.clientY;
} else if (Math.abs(dy) > swipeThreshold) {
// vertical swipe
if (dy > 0) setDirection(0, 1);
else setDirection(0, -1);
touchStartX = touch.clientX;
touchStartY = touch.clientY;
}
});
reset();
function gameLoop() {
update();
draw();
}
setInterval(gameLoop, 100); // 10 frames per second
})();
</script>
</body>
</html>
Summary of the key change:
When calculating the new head position, if it would go outside the grid, wrap it around to the opposite side.
We no longer treat hitting the wall as a game over condition.
The snake still dies if it hits itself.
Try this on your device, and the snake will wrap through walls seamlessly. Let me know if you want further adjustments!
Got it! To make the Snake game look cooler, I'll enhance it with:
Gradient colors on the snake (head and body segments) for a nicer effect.
Shiny, glossy apple-looking food with circle and highlight.
Subtle background grid pattern.
Smooth animations with a darker border around segments.
Better font and some shadows for score text.
Slightly rounded corners on the snake blocks.
A subtle glow effect on the snake head.
Here's the upgraded full code with these style and draw enhancements: