Got it! I'll enhance your Snake game by adding a visible scoreboard and enabling control with a PS4 controller (DualShock 4) connected to an iPhone via Gamepad API.
What I will do:
- Add a simple scoreboard on top-left corner displaying Score (equal to apples eaten).
- Use the Gamepad API to detect PS4 controller inputs.
- Map PS4 D-pad and left stick to snake direction.
- Since iOS Safari supports Bluetooth gamepads (including PS4 controllers) via the Gamepad API (limited support but works on recent iOS versions).
Important notes:
- On iOS Safari, the Gamepad API is only available on HTTPS sites (or localhost).
- For the controller inputs to work, the user must touch the screen at least once to enable gamepad polling (due to iOS security).
- We'll poll
navigator.getGamepads() every update and change direction accordingly.
- To avoid reversing direction, we disallow immediate 180° turns.
- Score displayed is number of apples eaten:
score = snake.length - initialLength.
Below is your updated complete code with the scoreboard and PS4 controller support:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Snake Game with Touch, PS4 Controller & Score</title>
<style>
body {
margin: 0;
background: #111;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
user-select: none;
font-family: monospace, monospace;
color: limegreen;
}
canvas {
background-color: #000;
box-shadow: 0 0 15px 5px rgba(0, 255, 0, 0.7);
border-radius: 10px;
touch-action: none;
}
#scoreboard {
position: fixed;
top: 10px;
left: 10px;
font-size: 20px;
font-weight: bold;
user-select: none;
pointer-events: none;
text-shadow:
-1px -1px 0 #000,
1px -1px 0 #000,
-1px 1px 0 #000,
1px 1px 0 #000;
}
</style>
</head>
<body>
<div id="scoreboard">Score: 0</div>
<canvas id="game"></canvas>
<script>
(() => {
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const scoreboard = document.getElementById('scoreboard');
const gridSize = 20; // size of each cell in pixels
function resize() {
const size = Math.min(window.innerWidth, window.innerHeight) * 0.9;
canvas.width = Math.floor(size / gridSize) * gridSize;
canvas.height = canvas.width;
}
resize();
window.addEventListener('resize', resize);
function getCols() { return canvas.width / gridSize; }
function getRows() { return canvas.height / gridSize; }
// Directions
const DIR = {
LEFT: { x: -1, y: 0 },
UP: { x: 0, y: -1 },
RIGHT: { x: 1, y: 0 },
DOWN: { x: 0, y: 1 },
};
// Opposite pairs for direction checks
const opposites = new Map([
[DIR.LEFT, DIR.RIGHT],
[DIR.RIGHT, DIR.LEFT],
[DIR.UP, DIR.DOWN],
[DIR.DOWN, DIR.UP],
]);
// Because Map keys are objects, we'll use a helper function:
function isOpposite(dir1, dir2) {
return dir1.x + dir2.x === 0 && dir1.y + dir2.y === 0;
}
let direction = DIR.RIGHT;
let nextDirection = direction;
let snake = [
{ x: 8, y: 10 },
{ x: 7, y: 10 },
{ x: 6, y: 10 },
];
const initialLength = snake.length;
let apples = [];
function randomApplePosition() {
while (true) {
const x = Math.floor(Math.random() * getCols());
const y = Math.floor(Math.random() * getRows());
const collisionWithSnake = snake.some(s => s.x === x && s.y === y);
const collisionWithApple = apples.some(a => a.x === x && a.y === y);
if (!collisionWithSnake && !collisionWithApple) return { x, y };
}
}
function spawnApples() {
while (apples.length < 3) {
apples.push(randomApplePosition());
}
}
spawnApples();
let gameOver = false;
function drawCell(x, y, color, glow = false) {
const px = x * gridSize;
const py = y * gridSize;
if (glow) {
ctx.shadowColor = 'limegreen';
ctx.shadowBlur = 10;
} else {
ctx.shadowBlur = 0;
}
ctx.fillStyle = color;
ctx.fillRect(px, py, gridSize - 1, gridSize - 1);
ctx.shadowBlur = 0;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw apples
apples.forEach(({ x, y }) => {
ctx.shadowColor = 'rgba(255, 0, 0, 0.7)';
ctx.shadowBlur = 8;
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(x * gridSize + gridSize / 2, y * gridSize + gridSize / 2, gridSize / 2 - 2, 0, Math.PI * 2);
ctx.fill();
ctx.shadowBlur = 0;
});
// Draw snake
snake.forEach(({ x, y }, i) => {
let color = i === 0 ? '#b3ffb3' : '#00ff00';
drawCell(x, y, color, true);
});
if (gameOver) {
ctx.fillStyle = 'rgba(0,0,0,0.7)';
ctx.fillRect(0, canvas.height / 2 - 40, canvas.width, 80);
ctx.font = 'bold 36px monospace';
ctx.fillStyle = 'limegreen';
ctx.textAlign = 'center';
ctx.fillText('Game Over', canvas.width / 2, canvas.height / 2 + 12);
ctx.font = '16px monospace';
ctx.fillText('Tap or press any key to restart', canvas.width / 2, canvas.height / 2 + 40);
}
}
function updateScore() {
const score = snake.length - initialLength;
scoreboard.textContent = `Score: ${score}`;
}
function updateGamepad() {
if (!navigator.getGamepads) return;
const gamepads = navigator.getGamepads();
if (!gamepads) return;
for (let gp of gamepads) {
if (!gp) continue;
// Support PS4 DualShock 4 values:
// Buttons for D-pad:
// button[12] = Up, [13] = Down, [14] = Left, [15] = Right
// Left stick axes: axes[0] = horizontal (-1 left, 1 right), axes[1] = vertical (-1 up, 1 down)
// Priority to D-pad buttons if pressed
if (gp.buttons[12] && gp.buttons[12].pressed && direction !== DIR.DOWN) {
if (!isOpposite(direction, DIR.UP)) nextDirection = DIR.UP;
return;
}
if (gp.buttons[13] && gp.buttons[13].pressed && direction !== DIR.UP) {
if (!isOpposite(direction, DIR.DOWN)) nextDirection = DIR.DOWN;
return;
}
if (gp.buttons[14] && gp.buttons[14].pressed && direction !== DIR.RIGHT) {
if (!isOpposite(direction, DIR.LEFT)) nextDirection = DIR.LEFT;
return;
}
if (gp.buttons[15] && gp.buttons[15].pressed && direction !== DIR.LEFT) {
if (!isOpposite(direction, DIR.RIGHT)) nextDirection = DIR.RIGHT;
return;
}
// Otherwise, use left stick (with deadzone)
const deadzone = 0.35;
const hAxis = gp.axes[0];
const vAxis = gp.axes[1];
// horizontal movement
if (hAxis <= -deadzone && direction !== DIR.RIGHT) {
if (!isOpposite(direction, DIR.LEFT)) {
nextDirection = DIR.LEFT;
return;
}
} else if (hAxis >= deadzone && direction !== DIR.LEFT) {
if (!isOpposite(direction, DIR.RIGHT)) {
nextDirection = DIR.RIGHT;
return;
}
}
// vertical movement
if (vAxis <= -deadzone && direction !== DIR.DOWN) {
if (!isOpposite(direction, DIR.UP)) {
nextDirection = DIR.UP;
return;
}
} else if (vAxis >= deadzone && direction !== DIR.UP) {
if (!isOpposite(direction, DIR.DOWN)) {
nextDirection = DIR.DOWN;
return;
}
}
}
}
function update() {
if (gameOver) return;
updateGamepad();
direction = nextDirection;
let newHead = {
x: snake[0].x + direction.x,
y: snake[0].y + direction.y,
};
// Wrap around logic
if (newHead.x < 0) {
newHead.x = getCols() - 1;
} else if (newHead.x >= getCols()) {
newHead.x = 0;
}
if (newHead.y < 0) {
newHead.y = getRows() - 1;
} else if (newHead.y >= getRows()) {
newHead.y = 0;
}
// Check collision with self
if (snake.some(s => s.x === newHead.x && s.y === newHead.y)) {
gameOver = true;
draw();
return;
}
snake.unshift(newHead);
// Check apple collision - can eat multiple apples at once if overlapped
let ateApples = 0;
apples = apples.filter(apple => {
if (apple.x === newHead.x && apple.y === newHead.y) {
ateApples++;
return false; // remove this apple
}
return true;
});
if (ateApples > 0) {
spawnApples();
} else {
snake.pop();
}
updateScore();
}
// Keyboard controls for desktop
window.addEventListener('keydown', e => {
if (gameOver) {
reset();
return;
}
switch (e.key) {
case 'ArrowUp':
case 'w':
case 'W':
if (!isOpposite(direction, DIR.UP)) nextDirection = DIR.UP;
break;
case 'ArrowDown':
case 's':
case 'S':
if (!isOpposite(direction, DIR.DOWN)) nextDirection = DIR.DOWN;
break;
case 'ArrowLeft':
case 'a':
case 'A':
if (!isOpposite(direction, DIR.LEFT)) nextDirection = DIR.LEFT;
break;
case 'ArrowRight':
case 'd':
case 'D':
if (!isOpposite(direction, DIR.RIGHT)) nextDirection = DIR.RIGHT;
break;
}
});
// Touch swipe controls
let touchStartX = null;
let touchStartY = null;
const minSwipeDistance = 30;
canvas.addEventListener('touchstart', e => {
if (gameOver) {
reset();
e.preventDefault();
return;
}
const t = e.changedTouches[0];
touchStartX = t.clientX;
touchStartY = t.clientY;
}, { passive: false });
canvas.addEventListener('touchmove', e => {
e.preventDefault();
}, { passive: false });
canvas.addEventListener('touchend', e => {
if (touchStartX === null || touchStartY === null) return;
const t = e.changedTouches[0];
const dx = t.clientX - touchStartX;
const dy = t.clientY - touchStartY;
if (Math.abs(dx) < minSwipeDistance && Math.abs(dy) < minSwipeDistance) {
touchStartX = null;
touchStartY = null;
return;
}
if (Math.abs(dx) > Math.abs(dy)) {
if (dx > 0 && !isOpposite(direction, DIR.RIGHT)) {
nextDirection = DIR.RIGHT;
} else if (dx < 0 && !isOpposite(direction, DIR.LEFT)) {
nextDirection = DIR.LEFT;
}
} else {
if (dy > 0 && !isOpposite(direction, DIR.DOWN)) {
nextDirection = DIR.DOWN;
} else if (dy < 0 && !isOpposite(direction, DIR.UP)) {
nextDirection = DIR.UP;
}
}
touchStartX = null;
touchStartY = null;
}, { passive: false });
function reset() {
direction = DIR.RIGHT;
nextDirection = direction;
snake = [
{ x: 8, y: 10 },
{ x: 7, y: 10 },
{ x: 6, y: 10 },
];
apples = [];
spawnApples();
gameOver = false;
updateScore();
}
const fps = 10;
setInterval(() => {
update();
draw();
}, 1000 / fps);
// Show initial score
updateScore();
})();
</script>
</body>
</html>
How to test PS4 controller with iPhone
- Connect your PS4 controller to iPhone via Bluetooth:
- Hold PS and Share buttons together until light blinks.
- Go to iPhone Settings > Bluetooth > Pair device.
- Open this game on a secure HTTPS webpage or localhost.
- Tap the screen once to enable gamepad input on iOS Safari.
- Use D-pad or left stick on the controller to move the snake.
- Score updates as you eat apples.
- If game over, press any key, tap screen, or press any controller button to restart.
If you want me to make the scoreboard display more stylized, or add controller button press restart, or anything else — just ask!