본문 바로가기
개발 프로젝트/JavaScript

자바스크립트로 게임 만들기(1)

by BuyAndPray 2020. 11. 6.
반응형

자바스크립트와 canvas를 활용해서 간단한 벽돌깨기 게임을 만들어 보겠습니다. 다 만들어진 게임의 모습은 아래와 같습니다.

 

벽돌깨기 플레이 모습

소스코드가 필요하신 분은 아래 주소에서 확인해주세요.

 

https://github.com/arclic/JS-breakout

 

기본 세팅

먼저 app.html 파일을 만들고 다음과 같이 입력해줍니다.

 

app.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"></meta>
        <title>BreakOut</title>
        <style>
            #gameCanvas{ border: 1px solid black; }
        </style>
    </head>
    <body>
        <canvas id="gameCanvas" width=300 height=500></canvas>
        <script type="module" src="app.js"></script>
    </body>
</html>

먼저 게임의 타이틀을 BreakOut이라고 설정한 뒤 벽돌깨기 게임이 동작할 canvas를 하나 생성합니다. 그리고 canvas 주변에 border을 생성해줍니다.

 

게임 구현의 대부분은 자바스크립트에서 할 것이기 때문에 html은 이렇게 간단하게만 입력해도 됩니다.

 

다음으로는 app.js 파일을 만들고 다음과 같이 입력해줍니다.

 

app.js

class App{
    constructor(){
        this.canvas = document.getElementById("gameCanvas");
        this.ctx = this.canvas.getContext("2d");

        window.requestAnimationFrame(this.animate.bind(this));
    }

    animate(){
        window.requestAnimationFrame(this.animate.bind(this));
    }
}

window.onload = () => {
    new App();
}

페이지가 로드되면 App 객체가 하나 생성됩니다. window.requestAnimationFrame(callback) 메서드는 브라우저에게 수행하기를 원하는 애니메이션을 알리고 애니메이션 리페인트 이전에 callback 함수를 호출하게 됩니다.

 

현재 callback 함수로 animate() 메서드가 들어갔고 계속해서 프레임을 업데이트하기 위해서 animate() 메서드 안에서 window.requestAnimationFrame()이 재귀적으로 animate() 메서드를 호출하고 있습니다.

 

 

벽돌 생성

app.js 까지 만들었으면 이제 벽돌을 생성해보겠습니다. 벽돌 생성을 위해서 block.js를 만들고 다음과 같이 입력해주세요.

 

block.js

export class Block {
    constructor(x, y){
        this.x = x;
        this.y = y;

        this.width = 50;
        this.height = 20;

        this.strokeColor = "#fff";
        this.fillColor = "#07baa0";
    }

    draw(ctx){
        ctx.strokeStyle = this.strokeColor;
        ctx.fillStyle = this.fillColor;
        ctx.beginPath();
        ctx.strokeRect(this.x, this.y, this.width, this.height);
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
}

strokeStyle과 fillStyle을 다르게 해서 각각의 block에 border가 있는 듯한 느낌을 줍니다. draw() 메서드는 ctx를 인자로 받아서 canvas에 block을 한 개씩 그리게 됩니다.

 

이제 canvas를 약간 꾸민 뒤 canvas에 block을 추가해보겠습니다. app.js를 다음과 같이 수정해주세요.

 

app.js

import { Block } from "./block.js";

class App{
    constructor(){
        this.canvas = document.getElementById("gameCanvas");
        this.ctx = this.canvas.getContext("2d");

        const blockWidth = 50;
        const blockHeight = 20;
        
        this.blocks = [];
        for(let i = 0; i <= this.canvas.width - blockWidth; i += blockWidth){
            for(let j = 50; j <= 200; j += blockHeight){
                this.blocks.push(new Block(i, j));
            }
        }

        window.requestAnimationFrame(this.animate.bind(this));
    }

    draw(){
        this.ctx.fillStyle = "#102330";
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        this.blocks.forEach((block) => {
            block.draw(this.ctx);
        });
    }

    animate(){
        this.draw();

        window.requestAnimationFrame(this.animate.bind(this));
    }
}

window.onload = () => {
    new App();
}

먼저 block.js에서 Block class를 import 해옵니다. 그리고 각각의 벽돌을 저장할 배열 blocks를 만든 뒤 (0, 50)부터 (250, 200)까지 벽돌을 생성하게 됩니다.

 

animate() 메서드에는 draw() 메서드가 추가되어 매 프레임마다 draw()가 실행됩니다. draw() 함수에서는 canvas 전체 배경과 각각의 벽돌을 그립니다. 

 

실행한 화면은 아래와 같습니다.

 

벽돌이 추가된 canvas

 

자바스크립트로 게임 만들기 시리즈

반응형

댓글