You are on page 1of 4

<!

--
1. 아래의 코드를 그대로 사용하여 코드를 작성해줘
2. 코드가 변경된 부부은 모두 코드 변경 주석을 달아줘
1. 게임 시작 시 스네이크 포지션은 게임창 안에 있도록 해줘
-->

<!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>
canvas {
border: 1px solid #000;
display: block;
margin: 20px auto;
}

#info {
text-align: center;
}
</style>
</head>
<body>
<div id="info">
<p>Time: <span id="time">0</span> seconds</p>
<p>Score: <span id="score">0</span></p>
<p>Snake Position: <span id="snakePosition">0, 0</span></p>
</div>
<canvas id="gameCanvas" width="400" height="400"></canvas>

<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

const gridSize = 20;


const gridSizeX = canvas.width / gridSize;
const gridSizeY = canvas.height / gridSize;

let snake = [{ x: Math.floor(gridSizeX / 2), y: Math.floor(gridSizeY /


2) }];
let direction = 'right';
let food = generateFood();
let gameSpeed = 200; // Initial game speed in milliseconds
let intervalId;
let startTime = Date.now() / 1000; // Start time in seconds
let score = 0;

function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);

// Draw the snake


ctx.fillStyle = '#00F';
snake.forEach(segment => {
ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize,
gridSize);
});

// Draw the food


ctx.fillStyle = '#F00';
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
}

function update() {
let newHead = { ...snake[0] };
switch (direction) {
case 'up': newHead.y--; break;
case 'down': newHead.y++; break;
case 'left': newHead.x--; break;
case 'right': newHead.x++; break;
}

// Check for collisions with walls or itself


if (
newHead.x < 0 || newHead.x >= gridSizeX ||
newHead.y < 0 || newHead.y >= gridSizeY ||
snake.some(segment => segment.x === newHead.x && segment.y ===
newHead.y)
) {
// Game over
const playAgain = confirm('Game Over! Score: ' + score + '\nDo you
want to play again?');
if (playAgain) {
resetGame();
} else {
// Close the game window
window.close();
}
}

snake.unshift(newHead);

// Check for collision with food


if (newHead.x === food.x && newHead.y === food.y) {
// Generate new food
food = generateFood();

// Increase game speed (decrease the interval) when food is eaten


gameSpeed -= 10;
clearInterval(intervalId);
intervalId = setInterval(gameLoop, gameSpeed);

// Increase score by 10
score += 10;
document.getElementById('score').innerText = score;
} else {
// Remove the last segment of the snake if no food is eaten
snake.pop();
}

// Update snake position display


document.getElementById('snakePosition').innerText = `${newHead.x}, $
{newHead.y}`;
}

function generateFood() {
return {
x: Math.floor(Math.random() * gridSizeX),
y: Math.floor(Math.random() * gridSizeY)
};
}

function resetGame() {
snake = [{ x: 10, y: 10 }]; // Reset snake position to x: 10, y: 10
direction = 'right';
food = generateFood();
gameSpeed = 200; // Reset game speed
clearInterval(intervalId);
intervalId = setInterval(gameLoop, gameSpeed);

startTime = Date.now() / 1000;


score = 0;
document.getElementById('score').innerText = score;

// Focus on the game canvas


canvas.focus();
}

function gameLoop() {
update();
draw();
// Update time
const currentTime = Date.now() / 1000;
const elapsedTime = currentTime - startTime;
document.getElementById('time').innerText = elapsedTime.toFixed(2) +
's';
}

window.addEventListener('keydown', (event) => {


switch (event.key) {
case 'ArrowUp': direction = 'up'; break;
case 'ArrowDown': direction = 'down'; break;
case 'ArrowLeft': direction = 'left'; break;
case 'ArrowRight': direction = 'right'; break;
}
});

// Start the game loop


intervalId = setInterval(gameLoop, gameSpeed);

// Focus on the game canvas initially


canvas.focus();
</script>
</body>
</html>

You might also like