I want you to act as a superintelligent AI that functions as both an elite Research Assistant and a Senior Software Engineer with the ability to design, architect, and implement complete software systems across a wide range of technologies and domains. You possess expert-level knowledge in computer science, software engineering, systems design, machine learning, human-computer interaction, and academic research methodology. You are also capable of building fully working, production-ready codebases, from prototype to deployment.
Assistant
Understood. I am ready to assist you with any research, design, or software engineering task you have. Please provide the details of your project or inquiry, and I will deliver comprehensive, expert-level solutions tailored to your requirements.
User
Program snake in html touchscreen and spawn 3 apples and
Assistant
Certainly! I'll create a complete, production-ready touchscreen-friendly Snake game in HTML, CSS, and JavaScript. The game will:
Support touchscreen controls (swipe gestures).
Spawn 3 apples simultaneously.
Implement classic snake mechanics (grow when eating apples, game over on collision).
Display score based on apples eaten.
Be responsive and optimized for mobile devices.
Here is the full code:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Touchscreen Snake Game with 3 Apples</title>
<style>
body {
margin: 0;
background: #111;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
#game {
background: #222;
border: 2px solid #0f0;
touch-action: none; /* Prevent default touch actions */
position: relative;
}
canvas {
display: block;
background: #111;
}
#score {
position: absolute;
top: 10px;
left: 10px;
color: #0f0;
font-family: monospace;
font-size: 18px;
user-select: none;
}
#gameOver {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #f00;
font-family: monospace;
font-size: 32px;
display: none;
user-select: none;
}
#restartBtn {
position: absolute;
top: calc(50% + 50px);
left: 50%;
transform: translateX(-50%);
padding: 10px 20px;
font-size: 18px;
font-family: monospace;
background: #0f0;
border: none;
border-radius: 5px;
cursor: pointer;
display: none;
user-select: none;
}
</style>
</head>
<body>
<div id="game" style="width: 320px; height: 320px;">
<canvas id="canvas" width="320" height="320"></canvas>
<div id="score">Score: 0</div>
<div id="gameOver">Game Over</div>
<button id="restartBtn">Restart</button>
</div>
<script>
(() => {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const scoreEl = document.getElementById('score');
const gameOverEl = document.getElementById('gameOver');
const restartBtn = document.getElementById('restartBtn');
const gridSize = 20; // 20x20 grid (320/16)
const cellSize = canvas.width / gridSize; // 16 pixels per cell
// Directions
const DIR = {
LEFT: { x: -1, y: 0 },
UP: { x: 0, y: -1 },
RIGHT: { x: 1, y: 0 },
DOWN: { x: 0, y: 1 },
};
let snake;
let direction;
let nextDirection;
let apples;
let score;
let gameInterval;
let gameSpeed = 100; // ms per frame
// Touch controls variables
let touchStartX = null;
let touchStartY = null;
const swipeThreshold = 30; // minimum px to consider swipe
function init() {
snake = [
{ x: 10, y: 10 },
{ x: 9, y: 10 },
{ x: 8, y: 10 },
];
direction = DIR.RIGHT;
nextDirection = direction;
score = 0;
apples = [];
spawnApples(3);
scoreEl.textContent = 'Score: 0';
gameOverEl.style.display = 'none';
restartBtn.style.display = 'none';
if (gameInterval) clearInterval(gameInterval);
gameInterval = setInterval(gameLoop, gameSpeed);
}
function spawnApples(count) {
while (apples.length < count) {
const pos = {
x: Math.floor(Math.random() * gridSize),
y: Math.floor(Math.random() * gridSize),
};
// Make sure apple doesn't spawn on snake or another apple
if (
!snake.some(s => s.x === pos.x && s.y === pos.y) &&
!apples.some(a => a.x === pos.x && a.y === pos.y)
) {
apples.push(pos);
}
}
}
function gameLoop() {
// Update direction
direction = nextDirection;
// Calculate new head position
const head = snake[0];
const newHead = { x: head.x + direction.x, y: head.y + direction.y };
// Check collisions with walls
if (
newHead.x < 0 ||
newHead.x >= gridSize ||
newHead.y < 0 ||
newHead.y >= gridSize
) {
return gameOver();
}
// Check collision with self
if (snake.some(s => s.x === newHead.x && s.y === newHead.y)) {
return gameOver();
}
// Add new head
snake.unshift(newHead);
// Check if apple eaten
const appleIndex = apples.findIndex(a => a.x === newHead.x && a.y === newHead.y);
if (appleIndex !== -1) {
// Eat apple
apples.splice(appleIndex, 1);
score++;
scoreEl.textContent = 'Score: ' + score;
spawnApples(3); // Ensure always 3 apples
} else {
// Remove tail
snake.pop();
}
draw();
}
function draw() {
// Clear canvas
ctx.fillStyle = '#111';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw apples
apples.forEach(a => {
ctx.fillStyle = '#f00';
ctx.beginPath();
const centerX = a.x * cellSize + cellSize / 2;
const centerY = a.y * cellSize + cellSize / 2;
const radius = cellSize / 3;
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
ctx.fill();
});
// Draw snake
snake.forEach((segment, index) => {
ctx.fillStyle = index === 0 ? '#0f0' : '#0a0';
ctx.fillRect(
segment.x * cellSize,
segment.y * cellSize,
cellSize,
cellSize
);
});
}
function gameOver() {
clearInterval(gameInterval);
gameOverEl.style.display = 'block';
restartBtn.style.display = 'block';
}
// Touch controls - swipe detection
canvas.addEventListener('touchstart', e => {
if (e.touches.length === 1) {
touchStartX = e.touches[0].clientX;
touchStartY = e.touches[0].clientY;
}
}, { passive: true });
canvas.addEventListener('touchmove', e => {
if (!touchStartX || !touchStartY) return;
const touchX = e.touches[0].clientX;
const touchY = e.touches[0].clientY;
const diffX = touchX - touchStartX;
const diffY = touchY - touchStartY;
if (Math.abs(diffX) > Math.abs(diffY)) {
// Horizontal swipe
if (diffX > swipeThreshold && direction !== DIR.LEFT) {
nextDirection = DIR.RIGHT;
resetTouch();
} else if (diffX < -swipeThreshold && direction !== DIR.RIGHT) {
nextDirection = DIR.LEFT;
resetTouch();
}
} else {
// Vertical swipe
if (diffY > swipeThreshold && direction !== DIR.UP) {
nextDirection = DIR.DOWN;
resetTouch();
} else if (diffY < -swipeThreshold && direction !== DIR.DOWN) {
nextDirection = DIR.UP;
resetTouch();
}
}
}, { passive: true });
function resetTouch() {
touchStartX = null;
touchStartY = null;
}
// Keyboard controls for desktop testing
window.addEventListener('keydown', e => {
switch (e.key) {
case 'ArrowUp':
case 'w':
case 'W':
if (direction !== DIR.DOWN) nextDirection = DIR.UP;
break;
case 'ArrowDown':
case 's':
case 'S':
if (direction !== DIR.UP) nextDirection = DIR.DOWN;
break;
case 'ArrowLeft':
case 'a':
case 'A':
if (direction !== DIR.RIGHT) nextDirection = DIR.LEFT;
break;
case 'ArrowRight':
case 'd':
case 'D':
if (direction !== DIR.LEFT) nextDirection = DIR.RIGHT;
break;
}
});
restartBtn.addEventListener('click', () => {
init();
});
// Initialize game on load
init();
})();
</script>
</body>
</html>
Explanation:
Canvas size: 320x320 pixels, divided into a 20x20 grid (each cell 16x16 px).
Snake: Starts with length 3, moves every 100ms.
Apples: Always 3 apples on the board. When one is eaten, a new one spawns.
Controls: Swipe gestures on touchscreen to change direction; arrow keys/WASD for desktop.
Game Over: When snake hits wall or itself, game stops and shows "Game Over" with a restart button.
Score: Displays number of apples eaten.
You can save this as snake.html and open it on a mobile device or desktop browser. The swipe controls will work on touchscreens, and keyboard controls on desktop.
If you want me to add features like sound, animations, or a leaderboard, just ask!