728x90
반응형
HTML, CSS, JavaScript로 간단한 게임 만들기
공 튕기기 게임으로 배우는 웹 개발
1. HTML로 기본 구조 만들기
게임을 시작하기 위해 HTML의 <canvas>
태그를 사용해 캔버스를 설정합니다. 아래는 기본 HTML 코드입니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<title>공 튕기기 게임</title>
</head>
<body>
<canvas id="gameCanvas" width="600" height="400"></canvas>
</body>
</html>
2. CSS로 스타일링
CSS를 사용해 캔버스를 중앙에 배치하고 테두리와 배경색을 추가합니다.
canvas {
display: block;
margin: 50px auto;
border: 2px solid #333;
background-color: #f4f4f4;
}
3. JavaScript로 게임 로직 추가
JavaScript를 사용해 공을 움직이고, 화면의 경계에서 튕기도록 설정합니다.
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
let x = canvas.width / 2;
let y = canvas.height / 2;
let dx = 2;
let dy = -2;
const ballRadius = 10;
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#007BFF";
ctx.fill();
ctx.closePath();
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
dy = -dy;
}
x += dx;
y += dy;
requestAnimationFrame(update);
}
update();
4. 전체 코드
아래는 위의 단계를 모두 통합한 전체 코드입니다. 복사해서 사용해 보세요!
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>공 튕기기 게임</title>
<style>
canvas {
display: block;
margin: 50px auto;
border: 2px solid #333;
background-color: #f4f4f4;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="600" height="400"></canvas>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
let x = canvas.width / 2;
let y = canvas.height / 2;
let dx = 2;
let dy = -2;
const ballRadius = 10;
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#007BFF";
ctx.fill();
ctx.closePath();
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
dy = -dy;
}
x += dx;
y += dy;
requestAnimationFrame(update);
}
update();
</script>
</body>
</html>
결론
이 튜토리얼을 통해 HTML, CSS, JavaScript를 사용해 간단한 공 튕기기 게임을 만드는 과정을 배웠습니다. 이제 이 코드를 기반으로 점수 시스템, 난이도 조절 등 다양한 기능을 추가해 더 재미있는 게임을 만들어 보세요!
728x90
반응형
'프로그래밍' 카테고리의 다른 글
Python 기초 강의 1-1: 파이썬 시작하기 (0) | 2025.01.08 |
---|---|
HTML, Css, JavaScript 를 이용한 클릭 게임 만들기 (1) | 2025.01.08 |
파이썬을 이용한 우주선 슈팅 게임 만들기 (0) | 2025.01.06 |
파이썬을 이용한 장애물 피하기 게임 만들기 (0) | 2025.01.06 |
파이썬을 이용한 캐릭터 수집 게임 만들기 (0) | 2025.01.06 |