Certainly! Below is your HTML/JavaScript code with an added pause button functionality. The pause button will allow the player to pause and resume the game when clicked.
Paused Variable: I've included a gamePaused variable to indicate whether the game is currently paused.
Pause Button: A new button labeled "Pause" is added, which allows the user to pause the game and change the button text to "Resume".
Toggle Pause Functionality: The togglePause() function toggles the state of the gamePaused variable and updates the button's text accordingly.
Game Logic: The update() function checks the value of gamePaused and returns early if the game is paused.
You can copy the above code directly into your HTML file, and it will work with the added pause functionality.
can you add a highscore section to this code
code
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gridSize = 20;
let snake = [{ x: 200, y: 200 }];
let direction = { x: 0, y: 0 };
let food = randomFoodPosition();
let score = 0;
let gameSpeed = 100;
function drawRect(x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x + 2, y + 2, gridSize - 4, gridSize - 4);
}
function gameLoop() {
moveSnake();
if (checkCollision()) return gameOver();
if (hasEatenFood()) {
growSnake();
score++;
document.getElementById('score').textContent = score;
food = randomFoodPosition();
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
snake.forEach(segment => drawRect(segment.x, segment.y, '#32CD32'));
drawRect(food.x, food.y, '#FF4500');
}
function moveSnake() {
const head = { x: (snake[0].x + direction.x), y: (snake[0].y + direction.y) };
snake.unshift(head);
snake.pop();
}
function hasEatenFood() {
return snake[0].x === food.x && snake[0].y === food.y;
}
function growSnake() {
snake.push({});
}
function checkCollision() {
const [head, ...body] = snake;
// Check if snake hits the walls
if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
return true;
}
// Check if snake hits its own body
return body.some(segment => segment.x === head.x && segment.y === head.y);
}
function randomFoodPosition() {
const maxPosition = canvas.width / gridSize;
return {
x: Math.floor(Math.random() * maxPosition) * gridSize,
y: Math.floor(Math.random() * maxPosition) * gridSize
};
}
function gameOver() {
alert(`Game Over! Your score: ${score}`);
resetGame();
}
function resetGame() {
snake = [{ x: 200, y: 200 }];
direction = { x: 0, y: 0 };
score = 0;
document.getElementById('score').textContent = score;
food = randomFoodPosition();
}
window.addEventListener('keydown', event => {
switch (event.key) {
case 'ArrowUp':
if (direction.y === 0) direction = { x: 0, y: -gridSize };
break;
case 'ArrowDown':
if (direction.y === 0) direction = { x: 0, y: gridSize };
break;
case 'ArrowLeft':
if (direction.x === 0) direction = { x: -gridSize, y: 0 };
break;
case 'ArrowRight':
if (direction.x === 0) direction = { x: gridSize, y: 0 };
break;
}
});
setInterval(gameLoop, gameSpeed);
</script>
Sure! Below is the modified version of your Snake game code with an added High Score section. The High Score will be updated when a player's score exceeds the previous high score, and it will persist across page reloads using localStorage.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Snake Game</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
min-height: 100vh;
background-color: #121212;
color: white;
font-family: 'Courier New', Courier, monospace;
}
canvas {
background-color: #1e1e1e;
border: 2px solid #555;
}
.game-info {
text-align: center;
margin-top: 20px;
}
a {
color: #32cd32;
text-decoration: none;
font-size: 16px;
}
</style>
</head>
<body>
<div>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<div class="game-info">
<h2>Score: <span id="score">0</span></h2>
<h2>High Score: <span id="highScore">0</span></h2>
<p>Use Arrow Keys to Play</p>
<a href="index.html">← Back to Home</a>
</div>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gridSize = 20;
let snake = [{ x: 200, y: 200 }];
let direction = { x: 0, y: 0 };
let food = randomFoodPosition();
let score = 0;
const gameSpeed = 100;
let highScore = localStorage.getItem('highScore') ? parseInt(localStorage.getItem('highScore')) : 0;
// Update High Score on the screen
document.getElementById('highScore').textContent = highScore;
function drawRect(x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x + 2, y + 2, gridSize - 4, gridSize - 4);
}
function gameLoop() {
moveSnake();
if (checkCollision()) return gameOver();
if (hasEatenFood()) {
growSnake();
score++;
document.getElementById('score').textContent = score;
food = randomFoodPosition();
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
snake.forEach(segment => drawRect(segment.x, segment.y, '#32CD32'));
drawRect(food.x, food.y, '#FF4500');
}
function moveSnake() {
const head = { x: (snake[0].x + direction.x), y: (snake[0].y + direction.y) };
snake.unshift(head);
snake.pop();
}
function hasEatenFood() {
return snake[0].x === food.x && snake[0].y === food.y;
}
function growSnake() {
snake.push({});
}
function checkCollision() {
const [head, ...body] = snake;
// Check if snake hits the walls
if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
return true;
}
// Check if snake hits its own body
return body.some(segment => segment.x === head.x && segment.y === head.y);
}
function randomFoodPosition() {
const maxPosition = canvas.width / gridSize;
return {
x: Math.floor(Math.random() * maxPosition) * gridSize,
y: Math.floor(Math.random() * maxPosition) * gridSize
};
}
function gameOver() {
alert(`Game Over! Your score: ${score}`);
if (score > highScore) {
highScore = score;
localStorage.setItem('highScore', highScore);
document.getElementById('highScore').textContent = highScore;
}
resetGame();
}
function resetGame() {
snake = [{ x: 200, y: 200 }];
direction = { x: 0, y: 0 };
score = 0;
document.getElementById('score').textContent = score;
food = randomFoodPosition();
}
window.addEventListener('keydown', event => {
switch (event.key) {
case 'ArrowUp':
if (direction.y === 0) direction = { x: 0, y: -gridSize };
break;
case 'ArrowDown':
if (direction.y === 0) direction = { x: 0, y: gridSize };
break;
case 'ArrowLeft':
if (direction.x === 0) direction = { x: -gridSize, y: 0 };
break;
case 'ArrowRight':
if (direction.x === 0) direction = { x: gridSize, y: 0 };
break;
}
});
setInterval(gameLoop, gameSpeed);
</script>
</body>
</html>
Key Changes:
High Score Display: Added an <h2> element under the score display in the HTML to show the High Score.
High Score Persistence: Added logic to read the high score from localStorage when the game starts and update it when appropriate:
The high score is initialized from localStorage.
If the player achieves a score greater than the high score when the game ends, it updates the high score, saves it to localStorage, and updates the displayed high score.
You can copy and use this code directly in your HTML file, and it will now keep track of the high score as you play!
Certainly! If you want the Snake game to maintain its own high score separate from other games or parts of your application, you can modify the key used in localStorage when storing the high score. This way, each game can have its own unique identifier.
Here’s how to modify the Snake game code to store and retrieve the high score using a unique key (like "snakeHighScore") in localStorage:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Snake Game</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
min-height: 100vh;
background-color: #121212;
color: white;
font-family: 'Courier New', Courier, monospace;
}
canvas {
background-color: #1e1e1e;
border: 2px solid #555;
}
.game-info {
text-align: center;
margin-top: 20px;
}
a {
color: #32cd32;
text-decoration: none;
font-size: 16px;
}
</style>
</head>
<body>
<div>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<div class="game-info">
<h2>Score: <span id="score">0</span></h2>
<h2>High Score: <span id="highScore">0</span></h2>
<p>Use Arrow Keys to Play</p>
<a href="index.html">← Back to Home</a>
</div>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gridSize = 20;
let snake = [{ x: 200, y: 200 }];
let direction = { x: 0, y: 0 };
let food = randomFoodPosition();
let score = 0;
const gameSpeed = 100;
const highScoreKey = 'snakeHighScore'; // Unique key for snake high score
let highScore = localStorage.getItem(highScoreKey) ? parseInt(localStorage.getItem(highScoreKey)) : 0;
// Update High Score on the screen
document.getElementById('highScore').textContent = highScore;
function drawRect(x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x + 2, y + 2, gridSize - 4, gridSize - 4);
}
function gameLoop() {
moveSnake();
if (checkCollision()) return gameOver();
if (hasEatenFood()) {
growSnake();
score++;
document.getElementById('score').textContent = score;
food = randomFoodPosition();
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
snake.forEach(segment => drawRect(segment.x, segment.y, '#32CD32'));
drawRect(food.x, food.y, '#FF4500');
}
function moveSnake() {
const head = { x: (snake[0].x + direction.x), y: (snake[0].y + direction.y) };
snake.unshift(head);
snake.pop();
}
function hasEatenFood() {
return snake[0].x === food.x && snake[0].y === food.y;
}
function growSnake() {
snake.push({});
}
function checkCollision() {
const [head, ...body] = snake;
// Check if snake hits the walls
if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
return true;
}
// Check if snake hits its own body
return body.some(segment => segment.x === head.x && segment.y === head.y);
}
function randomFoodPosition() {
const maxPosition = canvas.width / gridSize;
return {
x: Math.floor(Math.random() * maxPosition) * gridSize,
y: Math.floor(Math.random() * maxPosition) * gridSize
};
}
function gameOver() {
alert(`Game Over! Your score: ${score}`);
if (score > highScore) {
highScore = score;
localStorage.setItem(highScoreKey, highScore); // Store using unique key
document.getElementById('highScore').textContent = highScore;
}
resetGame();
}
function resetGame() {
snake = [{ x: 200, y: 200 }];
direction = { x: 0, y: 0 };
score = 0;
document.getElementById('score').textContent = score;
food = randomFoodPosition();
}
window.addEventListener('keydown', event => {
switch (event.key) {
case 'ArrowUp':
if (direction.y === 0) direction = { x: 0, y: -gridSize };
break;
case 'ArrowDown':
if (direction.y === 0) direction = { x: 0, y: gridSize };
break;
case 'ArrowLeft':
if (direction.x === 0) direction = { x: -gridSize, y: 0 };
break;
case 'ArrowRight':
if (direction.x === 0) direction = { x: gridSize, y: 0 };
break;
}
});
setInterval(gameLoop, gameSpeed);
</script>
</body>
</html>
Key Changes:
Unique Key for High Score: The key used for storing the high score in localStorage is now defined as const highScoreKey = 'snakeHighScore';. This prevents conflict with any other high scores you have saved for other games.
Code Adjustments: Wherever the high score is accessed in localStorage, it's now using highScoreKey to ensure the correct high score is retrieved and updated.
This way, the Snake game's high score will be maintained separately, allowing you to have different high scores for different games or applications on your site. You can copy and use this code directly in your HTML file, and it will work with its own high score functionality!