[JS] 웹 게임 제작하기 1

PersesTitan·2022년 11월 24일
0

JS

목록 보기
1/3

그냥 갑자기 웹 게임을 만들고 싶어서 제작하게 되었습니다.

구상

간단하게 버블이 올라가면서 누르면 점수가 올라가는 방식으로 구현해볼까 합니다.

우선 우리의 시각을 책임지는 html으로 화면을 구현해줍니다.
우선 생성 테스트를 할 예정이라 버튼 2개를 추가했는데요. 추후 제거할 예정입니다.
html은 거둘 뿐...!
index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Game</title>
    <script src="create.js"></script>
</head>
<body>
    <div id="main"></div>
    <button onclick="loop()">생성</button>
    <button onclick="stop()">삭제</button>
</body>
</html>

다음은 js... 게임로직을 구현하는 중요한 역할이죠...!

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"

    const height = window.innerHeight;
    div.style.top = height - itemWidth + "px";
    div.style.right = position(width - itemWidth);
	// 아이디 추가
    div.setAttribute('id_value', (count++).toString());
    setInterval(() => {
        const value = div.style.top;
        div.style.top = value.substring(0, value.length - 2) - 1 + "px"
    }, 100);

    main.appendChild(div);
}

function stop() {
    document.getElementById("main").innerHTML = '';
}

// min ~ max
function random(min, max) {
    return Math.random() * (max - min) + min;
}
  • 전역 변수
    count는 버블아이디로 버블 각각 서로 다른 아이디를 가지게 할 예정입니다.
    score은 점수이고, hp는 생명력으로 놓칠때마다 1씩 깍아내릴 예정입니다.

  • loop()
    div를 생성하는 로직으로 브라우저 창 비율에 맞추어 크기와 위치를 구한뒤 생성을 합니다.
    생성한 객체를 html에 추가해줍니다.
    그리고 특정 시간 마다 위로 올라가도록 top 비율을 변경하였습니다.
    세로 위치는 가장 아래에 생성되게하고, 가로는 브라우저 크기에 맞추어 램던으로 생성하게 만들어주었습니다.

  • stop()
    그냥 테스트로 만든것으로 생성된 객체를 모두 지우게 구현하였습니다.

동작

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

0개의 댓글