포시코딩

javascript - 구글 공룡 게임 구현(1) 본문

개인프로젝트/구글 공룡 게임

javascript - 구글 공룡 게임 구현(1)

포시 2022. 6. 22. 12:43
728x90

인터넷이 끊긴 상태로 구글에 들어가면 플레이할 수 있는 게임이 있다. 

이렇게 생긴 스페이스로 장애물 피하는 간단한 게임이다. 

정식 명칭은 Dino T-Rex Game  인듯 

 

자바스크립트로만 위 게임을 구현해보려고 한다. 

새 프로젝트 폴더를 만든후에 index.html body 안에 아래 코드 입력

<canvas id="canvas"></canvas>
<script src="main.js"></script>

html 은 이게 끝이고 나머진 다 main.js 에서 코드작성할거임

let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d'); // context 란 뜻으로 ctx

canvas.width = window.innerWidth - 100;
canvas.height = window.innerHeight - 100;

// 바닥선
ctx.beginPath();
ctx.moveTo(0, 250);
ctx.lineTo(600, 250);
ctx.stroke();

// 임시캐릭터
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 50, 50);

2d 그림을 그리기위해 canvas 를 세팅해준 후 

주인공 캐릭터가 될 네모를 임시로 그려줬다.  canvas 기본 사용법은 아래 링크 참고

https://developer.mozilla.org/ko/docs/Web/API/Canvas_API/Tutorial/Basic_usage

 

캔버스(Canvas) 기본 사용법 - Web API | MDN

<canvas> HTML 엘리먼트를 살펴보는 것으로 이 튜토리얼을 시작해 보겠습니다. 이 페이지의 끝에서 캔버스 2D 컨텍스트를 설정하는 방법을 알게되고, 여러분의 브라우저에서 첫 번째 예제를 그리

developer.mozilla.org

 

임시캐릭터 자리에 주인공 캐릭터 dino 를 만들어보자 

여러 세팅값이 들어가야하니 dino 오브젝트를 생성

let dino = {
    x: 10, 
    y: 200, 
    width: 50, 
    height: 50, 
    draw(){
        ctx.fillStyle = 'green';
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
}
dino.draw();

위치값 x, y 와 너비, 높이를 지정 후 위에서 초록네모를 만들 때 쓴 코드를 

draw 함수 안에서 dino 의 세팅값을 가져와 실행되게 작성했다. 

dino.draw() 로 생성 여부 확인 -> 잘나옴 

 

다음은 장애물인 선인장 차례 

선인장은 여러개가 나와야할거고 -> 오브젝트 여러개 -> 클래스 생성

모두 똑같은 선인장이면 재미없으니

width, height 값에 랜덤값을 이용해 조정할거임 -> Math.random() 사용

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/random

 

Math.random() - JavaScript | MDN

Math.random() 함수는 0 이상 1 미만의 구간에서 근사적으로 균일한(approximately uniform) 부동소숫점 의사난수를 반환하며, 이 값은 사용자가 원하는 범위로 변형할 수 있다. 난수 생성 알고리즘에 사용

developer.mozilla.org

 

단순히 width, height 값 50에 랜덤으로 숫자 빼버리면 

x, y 좌표는 고정되있는데 높이가 들쭉날쭉이라 바닥선에서 삐져나가니

width, height 값을 랜덤으로 먼저 생성 후 y 값에 영향을 주게끔 했다. 

(변경된 y 값) = (기존 y 값 + 기존 height) - 변경된 height 

class Cactus {
    constructor() {
        // this.x = 500;
        // this.y = 200;
        // this.width = 50 + getRandomInt(-5, 6);
        // this.height = 50 + getRandomInt(-5, 6);
        this.width = 50 + getRandomInt(-5, 6);
        this.height = 50 + getRandomInt(-5, 6);
        this.x = 500;
        this.y = 250 - this.height;
    }
    draw() {
        ctx.fillStyle = 'red';
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
}
let cactus = new Cactus();
cactus.draw();

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min; //최댓값은 제외, 최솟값은 포함
}

여기까지 했으면 아래와 같은 화면이 나옴

 

728x90