0% found this document useful (0 votes)
42 views

Webpage Coding in Prograss 13

The code initializes a snake game with a canvas. It sets the initial snake position to a random location within the canvas bounds. It draws the snake and food, updates the snake's position each interval, and resets the game if the snake collides with itself or the edges. The speed increases when food is eaten by decreasing the interval.

Uploaded by

mongggo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Webpage Coding in Prograss 13

The code initializes a snake game with a canvas. It sets the initial snake position to a random location within the canvas bounds. It draws the snake and food, updates the snake's position each interval, and resets the game if the snake collides with itself or the edges. The speed increases when food is eaten by decreasing the interval.

Uploaded by

mongggo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 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;

// Code changed: Set initial snake position to a random position within


the game window
let snake = [{ x: Math.floor(Math.random() * gridSizeX), y:
Math.floor(Math.random() * gridSizeY) }];
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() {
// Code changed: Reset snake position to a random position within the
game window
snake = [{ x: Math.floor(Math.random() * gridSizeX), y:
Math.floor(Math.random() * gridSizeY) }];
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