[JS] JumpGame

2022. 6. 17. 16:01·Stack/JavaScript

mgame.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            display: flex;
            justify-content: center;
        }
        canvas {
            background: url('img/헤네풀숲.png') center center/90% no-repeat;
        }
    </style>
</head>
<body>
    <canvas></canvas>
    <img style="display: none;" src="img/버섯.png" alt="">
    <img style="display: none;" src="img/슬라임.png" alt="">
    <img style="display: none;" src="img/돼지.png" alt="">
    <script>
        // 점프게임
        // 사각형을 그림
        // 점프기능
        // 충돌체크
        let canvas = document.querySelector('canvas');
        let ctx = canvas.getContext('2d');

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

        // 변수정의
        let animation;
        let timer = 0;
        let jump = false;
        let jumptimer = 0;
        let catIme = new Image();
        catIme.src = "img/character.png";
        // 장애물 이미지 노드리스트
        let obsImgs = document.querySelectorAll('img');
        // 주인공객체 만들기
        let gameU = {
            x: 350,
            y: 400,
            width: 135,
            height: 125,
            draw() {
                // ctx.fillStyle = "green";
                // ctx.fillRect(this.x, this.y, this.width, this.height);
                ctx.drawImage(catIme, this.x, this.y, this.width, this.height);
            }
        }
        gameU.draw();

        // 장애물 배열
        let obstacleArr = [];

        // 장애물 만들기
        class Obstacle {
            constructor() {
                this.x = 1400;
                this.y = 400;
                this.width = 135,
                this.height = 125,
                // num은 0, 1, 2 랜덤값이 지정
                this.num = Math.floor(Math.random()*3);
            }
            draw() {
                ctx.drawImage(obsImgs[this.num], this.x, this.y, this.width, this.height);
                // ctx.fillStyle = "red";
                // ctx.fillRect(this.x, this.y, this.width, this.height);
            }
        }

        // 화면을 계속해서 진행하는 함수
        // 애니메이션 만들기
        // 1초에 60번 실행함
        // 장애물은 2~3초 하나씩 생성
        function startFrame() {
            animation = requestAnimationFrame(startFrame);
            timer ++;
            // 캔버스 지우기
            ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
            // timer가 180증가 될 때마다 장애물을 생성
            // 장애물 배열에 넣기
            if(timer % 180 === 0 ) {
                let obs = new Obstacle;
                obstacleArr.push(obs);
            }
            obstacleArr.forEach((item, index, arr) => {
                // 왼쪽으로 이동된 장애물 제거하기
                // x좌표가 0보다 작으면 배열에서 제거
                if(item.x < 180) {
                    arr.splice(index, 1);
                }
                item.x -= 5;
                item.draw();
                // 충돌하는지 확인
                crashCheck(gameU, item);
            })
            // 스페이스 눌렀을 때 올라갔다가 내려오기
            if(jump) {
                gameU.y -=3 ;
                jumptimer += 1;
            } else {
                if(gameU.y < 400) gameU.y +=3 ;

            }
            if(jumptimer > 50) {
                jump = false;
                jumptimer = 0;
            }
            gameU.draw();
        }
        startFrame();
        // 키 이벤트
        window.addEventListener("keydown", function(e) {
            if(e.code == "Space") {
                jump = true;
                console.log(jump);
            }
        })
        // 충돌 확인하기
        function crashCheck(user, item) {
            let x차이 = item.x - (user.x + user.width);
            let y차이 = item.y - (user.y);
            console.log(`y차이::::::::: ${y차이}`)
            if(x차이<= 0 && y차이 <= 0) {
                cancelAnimationFrame(animation);
                console.log(`xx${x차이}`);
                console.log(`yy${y차이}`);
                console.log("충돌");
            }
        }
    </script>
</body>
</html>

 

 

 

game.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas></canvas>
    <script>
        // 점프게임
        // 사각형을 그림
        // 점프기능
        // 충돌체크
        let canvas = document.querySelector('canvas');
        let ctx = canvas.getContext('2d');

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

        // 변수정의
        let animation;
        let timer = 0;
        let jump = false;
        let jumptimer = 0;

        // 주인공객체 만들기
        let gameU = {
            x: 30,
            y: 300,
            width: 50,
            height: 50,
            draw() {
                ctx.fillStyle = "green";
                ctx.fillRect(this.x, this.y, this.width, this.height);
            }
        }
        gameU.draw();

        // 장애물 배열
        let obstacleArr = [];

        // 장애물 만들기
        class Obstacle {
            constructor() {
                this.x = 900;
                this.y = 300;
                this.width = 50;
                this.height = 50;
            }
            draw() {
                ctx.fillStyle = "red";
                ctx.fillRect(this.x, this.y, this.width, this.height);
            }
        }

        // 화면을 계속해서 진행하는 함수
        // 애니메이션 만들기
        // 1초에 60번 실행함
        // 장애물은 2~3초 하나씩 생성
        function startFrame() {
            animation = requestAnimationFrame(startFrame);
            timer ++;
            // 캔버스 지우기
            ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
            // timer가 180증가 될 때마다 장애물을 생성
            // 장애물 배열에 넣기
            if(timer % 180 === 0 ) {
                let obs = new Obstacle;
                obstacleArr.push(obs);
            }
            obstacleArr.forEach((item, index, arr) => {
                // 왼쪽으로 이동된 장애물 제거하기
                // x좌표가 0보다 작으면 배열에서 제거
                if(item.x < 0) {
                    arr.splice(index, 1);
                }
                item.x--;
                item.draw();
                // 충돌하는지 확인
                crashCheck(gameU, item);
            })
            // 스페이스 눌렀을 때 올라갔다가 내려오기
            if(jump) {
                gameU.y--;
                jumptimer++;
            } else {
                if(gameU.y < 300) gameU.y++;

            }
            if(jumptimer > 100) {
                jump = false;
                jumptimer = 0;
            }
            gameU.draw();
        }
        startFrame();
        // 키 이벤트
        window.addEventListener("keydown", function(e) {
            if(e.code == "Space") {
                jump = true;
                console.log(jump);
            }
        })
        // 충돌 확인하기
        function crashCheck(user, item) {
            let x차이 = item.x- (user.x+user.width);
            let y차이 = item.y- (user.y+user.height/2);
            if(x차이 <= 0 && y차이 <= 0) {
                cancelAnimationFrame(animation);
                console.log("충돌");
            }
        }
    </script>
</body>
</html>

'Stack > JavaScript' 카테고리의 다른 글

[JS] Promise / Async / 에러 핸들링 복습  (0) 2022.06.30
[JS] Wave  (0) 2022.06.20
[JS] Network  (0) 2022.06.17
[JS] 모듈  (0) 2022.06.17
[JS] canvas  (0) 2022.06.16
'Stack/JavaScript' 카테고리의 다른 글
  • [JS] Promise / Async / 에러 핸들링 복습
  • [JS] Wave
  • [JS] Network
  • [JS] 모듈
7ingout
7ingout
  • 7ingout
    Hello, 7ingout world!
    7ingout
  • 전체
    오늘
    어제
    • 분류 전체보기 (205)
      • Project (5)
      • Stack (173)
        • React (40)
        • JavaScript (50)
        • TypeScript (14)
        • HTML (11)
        • CSS (31)
        • Spring (9)
        • PHP (15)
        • SQL (3)
        • Python (0)
      • ETC (9)
      • Design (13)
        • Illustrator (6)
        • Photoshop (7)
      • Articloid (4)
        • 7ingout (4)
  • 공지사항

    • ☻
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
7ingout
[JS] JumpGame
상단으로

티스토리툴바