Your provided code is already in JavaScript within the HTML page. If you mean to extract just the JavaScript part (the <script> content) or convert this whole into a pure JavaScript-only version (e.g., generating DOM elements and styles dynamically), please clarify.
If you want the JavaScript only (i.e., the <script> block extracted and formatted):
javascript
(() => {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const scoreboard = document.getElementById('scoreboard');
const controls = document.querySelectorAll('.btn');
const gameOverOverlay = document.getElementById('gameOverOverlay');
const gameOverMessage = document.getElementById('gameOverMessage');
const restartBtn = document.getElementById('restartBtn');
const gameContainer = document.getElementById('game');
const tileCount = 24;
let gridSize;
// Game state
let snake, velocity, nextVelocity, apples, score, gameOver;
let hue = 0;
const maxApples = 3;
// Effects
const effects = { score: [], particles: [] };
// Resize canvas to container size
function resizeCanvas() {
const size = gameContainer.clientWidth;
canvas.width = size;
canvas.height = size;
gridSize = size / tileCount;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// Helpers
function colorGradient(isSnake) {
hue = (hue + 2) % 360;
if (isSnake) {
const c1 = `hsl(${hue},100%,50%)`;
const c2 = `hsl(${(hue + 40) % 360},100%,60%)`;
const g = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
g.addColorStop(0, c1);
g.addColorStop(1, c2);
return g;
} else {
const g = ctx.createRadialGradient(0, 0, 5, 0, 0, gridSize * 0.6);
g.addColorStop(0, `hsl(${hue},100%,70%)`);
g.addColorStop(1, `hsl(${(hue + 60) % 360},80%,40%)`);
return g;
}
}
function roundedRect(x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
ctx.fill();
}
function isEmpty(x, y) {
return !snake.some(s => s.x === x && s.y === y) &&
!apples.some(a => a.x === x && a.y === y);
}
// Spawn apples
function spawnApples() {
while (apples.length < maxApples) {
const p = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount)
};
if (isEmpty(p.x, p.y)) apples.push(p);
}
}
// Effects helpers
function addScoreFx(x, y, amt) {
effects.score.push({
x: x * gridSize + gridSize / 2,
y: y * gridSize + gridSize / 2,
alpha: 1,
text: '+' + amt,
size: 24
});
}
function addParticles(x, y) {
for (let i = 0; i < 12; i++) {
effects.particles.push({
x: x * gridSize + gridSize / 2,
y: y * gridSize + gridSize / 2,
dx: (Math.random() - 0.5) * 8,
dy: (Math.random() - 0.5) * 8,
alpha: 1,
size: Math.random() * 4 + 2
});
}
}
function updateEffects() {
effects.score.forEach((e, i) => {
e.y -= 1.5;
e.alpha -= 0.02;
e.size += 0.3;
if (e.alpha <= 0) effects.score.splice(i, 1);
});
effects.particles.forEach((p, i) => {
p.x += p.dx;
p.y += p.dy;
p.alpha -= 0.03;
p.color = `hsla(${(hue + i * 30) % 360},100%,60%,${p.alpha})`;
if (p.alpha <= 0) effects.particles.splice(i, 1);
});
}
function flashScore() {
scoreboard.classList.add('flash');
setTimeout(() => scoreboard.classList.remove('flash'), 200);
}
// Game update
function update() {
if (gameOver) return;
if ((nextVelocity.x !== -velocity.x || nextVelocity.y !== -velocity.y) &&
(nextVelocity.x !== velocity.x || nextVelocity.y !== velocity.y)) {
velocity = nextVelocity;
}
const head = {
x: (snake[0].x + velocity.x + tileCount) % tileCount,
y: (snake[0].y + velocity.y + tileCount) % tileCount
};
// Collision with self
if (snake.some(p => p.x === head.x && p.y === head.y)) {
endGame();
return;
}
snake.unshift(head);
// Check apple eat
let ateApple = false;
for (let i = 0; i < apples.length; i++) {
if (apples[i].x === head.x && apples[i].y === head.y) {
apples.splice(i, 1);
score++;
addScoreFx(head.x, head.y, 1);
addParticles(head.x, head.y);
flashScore();
spawnApples();
ateApple = true;
break;
}
}
if (!ateApple) {
snake.pop();
}
scoreboard.textContent = `Score: ${score}`;
}
// Draw frame
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw grid lines
ctx.strokeStyle = '#222';
ctx.lineWidth = 1;
for (let i = 0; i <= tileCount; i++) {
const pos = i * gridSize;
ctx.beginPath();
ctx.moveTo(pos, 0);
ctx.lineTo(pos, canvas.height);
ctx.moveTo(0, pos);
ctx.lineTo(canvas.width, pos);
ctx.stroke();
}
// Draw apples
apples.forEach(a => {
const cx = a.x * gridSize + gridSize / 2;
const cy = a.y * gridSize + gridSize / 2;
ctx.save();
ctx.translate(cx, cy);
ctx.shadowColor = '#f44';
ctx.shadowBlur = 18;
ctx.fillStyle = colorGradient(false);
ctx.beginPath();
ctx.ellipse(0, 0, gridSize * 0.4, gridSize * 0.55, Math.PI / 6, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = '#282';
ctx.beginPath();
ctx.ellipse(0, -gridSize * 0.3, gridSize * 0.15, gridSize * 0.3, Math.PI / 4, 0, 2 * Math.PI);
ctx.fill();
ctx.restore();
});
// Draw snake
snake.forEach((s, i) => {
const px = s.x * gridSize;
const py = s.y * gridSize;
ctx.save();
ctx.fillStyle = colorGradient(true);
ctx.shadowColor = '#0ff';
ctx.shadowBlur = i === 0 ? 25 : 18;
roundedRect(px + 2, py + 2, gridSize - 4, gridSize - 4, 8);
ctx.restore();
});
// Draw effects
effects.particles.forEach(p => {
ctx.fillStyle = p.color;
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, 2 * Math.PI);
ctx.fill();
});
effects.score.forEach(e => {
ctx.fillStyle = `rgba(0,255,150,${e.alpha})`;
ctx.font = `${e.size}px Arial`;
ctx.textAlign = 'center';
ctx.shadowColor = '#0f9';
ctx.shadowBlur = 10;
ctx.fillText(e.text, e.x, e.y);
});
}
// End game
function endGame() {
gameOver = true;
gameOverMessage.textContent = `Game Over! Your score was ${score}.`;
gameOverOverlay.classList.add('visible');
gameContainer.focus();
}
// Restart game
function restartGame() {
snake = [
{ x: 12, y: 12 },
{ x: 11, y: 12 },
{ x: 10, y: 12 }
];
velocity = { x: 1, y: 0 };
nextVelocity = { x: 1, y: 0 };
apples = [];
score = 0;
gameOver = false;
scoreboard.textContent = `Score: ${score}`;
gameOverOverlay.classList.remove('visible');
spawnApples();
draw();
}
// Touch controls: swipe detection
let touchStartX = null;
let touchStartY = null;
const minSwipeDistance = 30;
canvas.addEventListener('touchstart', e => {
if (e.touches.length === 1) {
const t = e.touches[0];
touchStartX = t.clientX;
touchStartY = t.clientY;
}
}, { passive: true });
canvas.addEventListener('touchmove', e => {
if (touchStartX === null || touchStartY === null) return;
const t = e.touches[0];
const dx = t.clientX - touchStartX;
const dy = t.clientY - touchStartY;
if (Math.abs(dx) > minSwipeDistance || Math.abs(dy) > minSwipeDistance) {
if (Math.abs(dx) > Math.abs(dy)) {
if (dx > 0) tryChangeDirection('right');
else tryChangeDirection('left');
} else {
if (dy > 0) tryChangeDirection('down');
else tryChangeDirection('up');
}
touchStartX = null;
touchStartY = null;
}
}, { passive: true });
// Button controls
controls.forEach(btn => {
btn.addEventListener('click', () => {
tryChangeDirection(btn.dataset.dir);
});
});
// Keyboard controls
gameContainer.addEventListener('keydown', e => {
if (gameOver) return;
switch (e.key) {
case 'ArrowUp':
case 'w':
case 'W':
tryChangeDirection('up');
e.preventDefault();
break;
case 'ArrowDown':
case 's':
case 'S':
tryChangeDirection('down');
e.preventDefault();
break;
case 'ArrowLeft':
case 'a':
case 'A':
tryChangeDirection('left');
e.preventDefault();
break;
case 'ArrowRight':
case 'd':
case 'D':
tryChangeDirection('right');
e.preventDefault();
break;
}
});
// Change direction helper
function tryChangeDirection(dir) {
const directions = {
up: { x: 0, y: -1 },
down: { x: 0, y: 1 },
left: { x: -1, y: 0 },
right: { x: 1, y: 0 }
};
const newVel = directions[dir];
if (!newVel) return;
if (newVel.x !== -velocity.x || newVel.y !== -velocity.y) {
nextVelocity = newVel;
}
}
// Game loop with separate update and draw rates
const updateFPS = 10; // snake moves 10 times per second
let lastUpdate = 0;
function gameLoop(time = 0) {
if (!gameOver) {
if (time - lastUpdate > 1000 / updateFPS) {
lastUpdate = time;
update();
updateEffects();
}
draw();
}
requestAnimationFrame(gameLoop);
}
// Restart button event
restartBtn.addEventListener('click', () => {
restartGame();
});
// Initialize game
function init() {
restartGame();
requestAnimationFrame(gameLoop);
}
init();
})();
If you want me to convert the whole HTML+CSS+JS into a single JavaScript file that programmatically creates DOM and styles — that is a bigger task and not usually how you'd do it for a game like this. But I can help with that if you want.
Please confirm what you want exactly or if you want me to convert this code into another framework or style.
Got it! You want the Snake game (the same logic and features) rewritten in C++.
Since the original is a touchscreen/browser-based game with graphics and animations, we can't directly map that to plain C++. To build an interactive Snake game with graphics in C++, common ways include using:
Console-based game (text-mode)
Using a graphics library like SDL2, SFML, or similar for graphics and input
What I can do:
Provide a console-based Snake game in C++ that supports keyboard controls.
Or a minimal graphical Snake game using SFML (requires a library install).
I recommend a simple console version first. It won't have shadows, colors, or neon style, but it will reproduce the core gameplay: moving snake, multiple apples, score, and restart.
Console-based Snake in C++ (with 3 apples and keyboard controls)
cpp
#include <iostream>
#include <vector>
#include <conio.h> // for _kbhit() and _getch() on Windows; for Linux, use other means
#include <windows.h> // for Sleep and system("cls"); remove these includes and functions if on non-Windows platform
#include <ctime>
#include <cstdlib>
using namespace std;
const int WIDTH = 24;
const int HEIGHT = 24;
const int MAX_APPLES = 3;
struct Point {
int x, y;
bool operator==(const Point& rhs) const {
return x == rhs.x && y == rhs.y;
}
};
enum Direction { UP, DOWN, LEFT, RIGHT };
class SnakeGame {
public:
SnakeGame() {
reset();
}
void run() {
while (!gameOver) {
input();
update();
draw();
Sleep(100); // control game speed, ~10 FPS
}
gameOverScreen();
}
private:
vector<Point> snake;
vector<Point> apples;
Direction dir;
int score;
bool gameOver;
void reset() {
snake.clear();
snake.push_back({ WIDTH / 2, HEIGHT / 2 });
snake.push_back({ WIDTH / 2 - 1, HEIGHT / 2 });
snake.push_back({ WIDTH / 2 - 2, HEIGHT / 2 });
dir = RIGHT;
score = 0;
gameOver = false;
apples.clear();
spawnApples();
}
void spawnApples() {
while ((int)apples.size() < MAX_APPLES) {
Point p = { rand() % WIDTH, rand() % HEIGHT };
if (!isOccupied(p)) {
apples.push_back(p);
}
}
}
bool isOccupied(const Point& p) {
for (auto& s : snake)
if (s == p) return true;
for (auto& a : apples)
if (a == p) return true;
return false;
}
void input() {
if (_kbhit()) {
char ch = _getch();
switch (ch) {
case 'w': case 'W':
case 72: // arrow up
if (dir != DOWN) dir = UP;
break;
case 's': case 'S':
case 80: // arrow down
if (dir != UP) dir = DOWN;
break;
case 'a': case 'A':
case 75: // arrow left
if (dir != RIGHT) dir = LEFT;
break;
case 'd': case 'D':
case 77: // arrow right
if (dir != LEFT) dir = RIGHT;
break;
case 'r': case 'R':
reset();
break;
case 27: // ESC key
gameOver = true;
break;
}
}
}
void update() {
if (gameOver) return;
// move head
Point newHead = snake.front();
switch (dir) {
case UP: newHead.y--; break;
case DOWN: newHead.y++; break;
case LEFT: newHead.x--; break;
case RIGHT: newHead.x++; break;
}
// wrap around
if (newHead.x < 0) newHead.x = WIDTH - 1;
if (newHead.x >= WIDTH) newHead.x = 0;
if (newHead.y < 0) newHead.y = HEIGHT - 1;
if (newHead.y >= HEIGHT) newHead.y = 0;
// check collision with self
for (auto& s : snake) {
if (newHead == s) {
gameOver = true;
return;
}
}
// add new head
snake.insert(snake.begin(), newHead);
// check apple eaten
bool ateApple = false;
for (int i = 0; i < (int)apples.size(); i++) {
if (apples[i] == newHead) {
ateApple = true;
apples.erase(apples.begin() + i);
score++;
spawnApples();
break;
}
}
// if did not eat apple, remove tail
if (!ateApple) {
snake.pop_back();
}
}
void draw() {
system("cls"); // clear the console
// top border
for (int i = 0; i < WIDTH + 2; i++) cout << "#";
cout << endl;
for (int y = 0; y < HEIGHT; y++) {
cout << "#";
for (int x = 0; x < WIDTH; x++) {
Point cur = { x, y };
if (cur == snake.front()) {
cout << "O"; // snake head
}
else if (contains(snake.begin() + 1, snake.end(), cur)) {
cout << "o"; // snake body
}
else if (contains(apples.begin(), apples.end(), cur)) {
cout << "@"; // apple
}
else {
cout << " ";
}
}
cout << "#" << endl;
}
// bottom border
for (int i = 0; i < WIDTH + 2; i++) cout << "#";
cout << endl;
cout << "Score: " << score << " (Use WASD or arrow keys to move, R to restart, ESC to quit)" << endl;
}
template<typename Iter>
bool contains(Iter begin, Iter end, const Point& p) {
for (; begin != end; ++begin) {
if (*begin == p) return true;
}
return false;
}
void gameOverScreen() {
cout << "\nGame Over! Final score: " << score << endl;
cout << "Press R to restart or ESC to quit." << endl;
while (true) {
if (_kbhit()) {
char ch = _getch();
if (ch == 'r' || ch == 'R') {
reset();
run();
break;
}
else if (ch == 27) {
break;
}
}
Sleep(100);
}
}
};
int main() {
srand((unsigned int)time(nullptr));
SnakeGame game;
game.run();
return 0;
}
Notes:
Controls: WASD or arrow keys to move, R to restart, ESC to quit.
Drawn in console with simple characters:
O = snake head
o = snake body
@ = apples
# = border
The snake wraps around the edges (like your JS version).
Spawns 3 apples simultaneously.
Collision with self ends the game.
Restart prompt after game over.
Compilation:
On Windows with Visual Studio or g++ on MinGW:
bash
g++ snake.cpp -o snake.exe
Run snake.exe.
On Linux / Mac, you need to replace _kbhit() and _getch() with equivalent code, e.g. using ncurses library or terminal settings to handle non-blocking input.
If you want a graphical version using SFML or SDL, just ask! But that requires installing libraries and more setup.
If you want help adapting this to your platform or linking libraries, happy to assist!
Yes! The C++ Snake game I provided above is already a complete single-file program — you can save the whole code as, for example, snake.cpp, compile it, and run it without needing any other files.
Summary:
Just copy the entire code below into a file snake.cpp.
Compile and run it.
Everything (game logic, drawing, input) is self-contained.
Here is the full single-file C++ Snake game again for convenience:
cpp
#include <iostream>
#include <vector>
#include <conio.h> // for _kbhit() and _getch() on Windows
#include <windows.h> // Sleep and system("cls") on Windows
#include <ctime>
#include <cstdlib>
using namespace std;
const int WIDTH = 24;
const int HEIGHT = 24;
const int MAX_APPLES = 3;
struct Point {
int x, y;
bool operator==(const Point& rhs) const {
return x == rhs.x && y == rhs.y;
}
};
enum Direction { UP, DOWN, LEFT, RIGHT };
class SnakeGame {
public:
SnakeGame() {
reset();
}
void run() {
while (!gameOver) {
input();
update();
draw();
Sleep(100); // delay for game speed (~10 FPS)
}
gameOverScreen();
}
private:
vector<Point> snake;
vector<Point> apples;
Direction dir;
int score;
bool gameOver;
void reset() {
snake.clear();
snake.push_back({ WIDTH / 2, HEIGHT / 2 });
snake.push_back({ WIDTH / 2 - 1, HEIGHT / 2 });
snake.push_back({ WIDTH / 2 - 2, HEIGHT / 2 });
dir = RIGHT;
score = 0;
gameOver = false;
apples.clear();
spawnApples();
}
void spawnApples() {
while ((int)apples.size() < MAX_APPLES) {
Point p = { rand() % WIDTH, rand() % HEIGHT };
if (!isOccupied(p)) {
apples.push_back(p);
}
}
}
bool isOccupied(const Point& p) {
for (auto& s : snake)
if (s == p) return true;
for (auto& a : apples)
if (a == p) return true;
return false;
}
void input() {
if (_kbhit()) {
char ch = _getch();
switch (ch) {
case 'w': case 'W':
case 72: // arrow up
if (dir != DOWN) dir = UP;
break;
case 's': case 'S':
case 80: // arrow down
if (dir != UP) dir = DOWN;
break;
case 'a': case 'A':
case 75: // arrow left
if (dir != RIGHT) dir = LEFT;
break;
case 'd': case 'D':
case 77: // arrow right
if (dir != LEFT) dir = RIGHT;
break;
case 'r': case 'R':
reset();
break;
case 27: // ESC
gameOver = true;
break;
}
}
}
void update() {
if (gameOver) return;
Point newHead = snake.front();
switch (dir) {
case UP: newHead.y--; break;
case DOWN: newHead.y++; break;
case LEFT: newHead.x--; break;
case RIGHT: newHead.x++; break;
}
// Wrap edges
if (newHead.x < 0) newHead.x = WIDTH - 1;
if (newHead.x >= WIDTH) newHead.x = 0;
if (newHead.y < 0) newHead.y = HEIGHT - 1;
if (newHead.y >= HEIGHT) newHead.y = 0;
// Collision with self
for (auto& s : snake) {
if (newHead == s) {
gameOver = true;
return;
}
}
snake.insert(snake.begin(), newHead);
bool ateApple = false;
for (int i = 0; i < (int)apples.size(); ++i) {
if (apples[i] == newHead) {
ateApple = true;
apples.erase(apples.begin() + i);
score++;
spawnApples();
break;
}
}
if (!ateApple) {
snake.pop_back();
}
}
void draw() {
system("cls");
// Top border
for (int i = 0; i < WIDTH + 2; ++i) cout << "#";
cout << "\n";
for (int y = 0; y < HEIGHT; ++y) {
cout << "#";
for (int x = 0; x < WIDTH; ++x) {
Point cur = {x, y};
if (cur == snake.front()) cout << "O"; // Head
else if (contains(snake.begin()+1, snake.end(), cur)) cout << "o"; // Body
else if (contains(apples.begin(), apples.end(), cur)) cout << "@"; // Apple
else cout << " ";
}
cout << "#\n";
}
// Bottom border
for (int i = 0; i < WIDTH + 2; ++i) cout << "#";
cout << "\n";
cout << "Score: " << score << " ";
cout << "(WASD or arrows to move, R to restart, ESC to quit)" << endl;
}
template<typename Iter>
bool contains(Iter begin, Iter end, const Point& p) {
for (; begin != end; ++begin) {
if (*begin == p) return true;
}
return false;
}
void gameOverScreen() {
cout << "\nGame Over! Final score: " << score << endl;
cout << "Press R to restart or ESC to quit." << endl;
while (true) {
if (_kbhit()) {
char ch = _getch();
if (ch == 'r' || ch == 'R') {
reset();
run();
break;
}
else if (ch == 27) {
break;
}
}
Sleep(100);
}
}
};
int main() {
srand((unsigned int)time(nullptr));
SnakeGame game;
game.run();
return 0;
}
How to compile (Windows):
Using g++ in Command Prompt or PowerShell:
bash
g++ snake.cpp -o snake.exe
snake.exe
Notes:
This code uses Windows-only functions like _kbhit(), _getch(), Sleep(), and system("cls").
For Linux/macOS, you'd need equivalents, e.g., ncurses for input and screen control.
The game logic and UI are all wrapped inside one file — no external dependencies.
If you want a platform-independent or GUI-based version, let me know! But this is the quickest self-contained example you can run on Windows.