냅다 개발부터 시작.
- 프로젝트 구조 설정:
먼저, 프로젝트 폴더를 만들고 필요한 파일들을 생성.
mkdir slither-clone
cd slither-clone
mkdir client server
touch client/index.html client/style.css client/game.js server/server.js
- HTML 구조 생성:
client/index.html 파일에 기본 HTML 구조를 작성.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Slither Clone</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script src="game.js"></script>
</body>
</html>
- 기본 CSS 스타일:
client/style.css 파일에 간단한 스타일을 추가.
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
#gameCanvas {
border: 1px solid #000;
}
- 기본 JavaScript 게임 로직:
client/game.js 파일에 기본적인 게임 로직을 구현.
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
const snake = {
x: canvas.width / 2,
y: canvas.height / 2,
size: 10,
dx: 2,
dy: 0
};
function drawSnake() {
ctx.fillStyle = 'green';
ctx.beginPath();
ctx.arc(snake.x, snake.y, snake.size, 0, Math.PI * 2);
ctx.fill();
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
snake.x += snake.dx;
snake.y += snake.dy;
if (snake.x < 0) snake.x = canvas.width;
if (snake.x > canvas.width) snake.x = 0;
if (snake.y < 0) snake.y = canvas.height;
if (snake.y > canvas.height) snake.y = 0;
drawSnake();
requestAnimationFrame(update);
}
function changeDirection(e) {
const LEFT_KEY = 37;
const RIGHT_KEY = 39;
const UP_KEY = 38;
const DOWN_KEY = 40;
const keyPressed = e.keyCode;
if (keyPressed === LEFT_KEY) {
snake.dx = -2;
snake.dy = 0;
}
if (keyPressed === UP_KEY) {
snake.dx = 0;
snake.dy = -2;
}
if (keyPressed === RIGHT_KEY) {
snake.dx = 2;
snake.dy = 0;
}
if (keyPressed === DOWN_KEY) {
snake.dx = 0;
snake.dy = 2;
}
}
document.addEventListener('keydown', changeDirection);
update();
- 기본 서버 설정:
server/server.js 파일에 간단한 Node.js 서버를 설정한다.
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
// 정적 파일 제공
app.use(express.static(path.join(__dirname, '../client')));
// 루트 경로 처리
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../client/index.html'));
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
이제 기본적인 구조가 만들었다. 서버를 실행하려면 먼저 필요한 패키지를 설치해야 함:
cd server
npm init -y
npm install express
node server.js
일단 게임 밑바닥부터 만들어두었다.