[JS] 웹 게임 제작하기 2

PersesTitan·2022년 11월 24일
0

JS

목록 보기
2/3

다음은 천장에 충돌하면 HP를 내리고 삭제를하는 로직과 버블 터치하였을때 점수를 올리고 버블이 사라지는 로직을 구현하였습니다.

임시로 구현했던 삭제 버튼은 없애고, 스코어와 HP를 추가하였습니다.
길어지면 헷깔리기 때문에 저는 item.js파일 1개를 더 만들었는데 파일 1개에 다 구현해도 무방합니다.

코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Game</title>
    <script src="create.js"></script>
    <script src="item.js"></script>
</head>
<body>
    <table style="border: 1px solid black">
        <tr>
            <td>스코어</td>
            <td id="score">0</td>
        </tr>
        <tr>
            <td>HP&nbsp;</td>
            <td id="hp">100</td>
        </tr>
    </table>
    <div id="main"></div>
    <button onclick="loop()">생성</button>
</body>
</html>

우선 삭제되는 부분을 구현하고, 천장에 부딧치면 downHp()를 호출하고, 클릭을하면 upScore()를 호출 하면 됩니다.

스피드는 다 똑같으면 재미 없으니 점수에 비례한 램던값으로 생성하였습니다.
값 차이를 많이 안줘서 그런지 솔직히 속도차이는 크게 못느꼈습니다.

item.js

function remove(value, interval) {
    const id_value = typeof value === 'string'
        ? document.querySelector(`[id_value="${value}"]`)
        : value;
    document.getElementById("main").removeChild(id_value);
    clearInterval(interval);
}

function downHp() {
    hp--;
    document.getElementById('hp').innerText = hp;
}

function upScore() {
    score++;
    document.getElementById('score').innerText = score;
}

function speed() {
    return Math.max(2, random(490 - score, 510 - score));
}

moveInterval에 item.js에서 생성한 downHp를 넣어주고 onClick를 하였을때 upScore를 적용해주었습니다.

create.js

count = 0;
score = 0;
hp = 100;

function loop() {
    const main = document.getElementById("main");

    const div = document.createElement("div");
    const width = window.innerWidth;
    const itemWidth = Math.floor(width / 100 * 7);

    div.style.width = itemWidth + "px"
    div.style.height = itemWidth + "px"

    div.style.borderRadius = "50%";
    div.style.backgroundColor = "black";
    // 절대 위치 지정
    div.style.position = "absolute"
    // 초기 위치 지정
    div.style.top = window.innerHeight - itemWidth + "px";
    div.style.right = position(width - itemWidth);
    // 아이디 추가
    div.setAttribute('id_value', (count++).toString());

    const moveInterval = setInterval(() => {
        const value = div.style.top;
        const pos = value.substring(0, value.length - 2);
        if (pos < 0) {
            downHp();
            remove(div.getAttribute('id_value'), moveInterval);
        }
        div.style.top = pos - 1 + "px"
    }, speed());

    // 클릭하면 점수올라가고 제거
    div.onclick = function () {
        upScore();
        remove(div, moveInterval);
    }
    main.appendChild(div);
}

function position(width) {
    return Math.floor(random(0, width)) + "px";
}

// min ~ max
function random(min, max) {
    return Math.random() * (max - min) + min;
}

동작

트릭페드로 해서 그런지 중간에 에임 이슈가 있습니다.

profile
안녕하세요 페르세스 티탄입니다! 부족한 부분이 많이 있겠지만 잘부탁드립니다.

0개의 댓글