본문 바로가기
javaScript/JS Examples

타이머를 함수 게임

by mooyou 2019. 8. 8.
728x90
300x250

1_ 타이머 함수를 활용해서 물고기 잡기 게임 만들기

 

요구사항

1. 5초 동안 물고기를 많이 클릭하기 게임

2. 쿨고기 클릭시 1점

3. 게임이 종료된 후 물고기 클릭 시 게임 점수가 올라가면 안된다.

4. 점수는 획득 시 바로 화면에 출력한다.

 

<script>
  $(document).ready(function() {
                // 점수 변수
                var count = 0;
                // 점수를 출력할 요소
                var $score = $("#score");

                // 게임 진행 유무 판단 변수
                var playing = true;
                // 물고기에 클릭 이벤트 등록
                $("#fish").click(function() {
                    if (playing == true) {
                        // 점수 증가
                        count++;
                        $score.html(count);
                    }
                });

                // 게임을 5초후에 종료시켜 줍니다.
                setTimeout(function() {
                    playing = false;
                    alert("게임이 종료 되었습니다.")
                }, 5000);
            });

        </script>
    </head>
    <body>
        <div>
            현재점수 <span id="score">0</span>
        </div>
        <div class="panel">
            <img src="fish1.png" id="fish">
        </div>
    </body>

 

점수를 출력하는 방법

$("#score").html(점수); 또는

$("#score").text(점수);

 

클릭이벤트 등록 방법

$(selector).click(function(){
 실행소스
});

 

구현은 점수처리와 게임종료 2단계로 나눠서 처리한다.

 

 

 

 

 


 

 

 

2_ 자동으로 물고기 움직이기

 

요구사항

1. 시작 버튼 누르면 물고기가 좌우로 자동으로움직인다.

2. 정지버튼을 누르면 멈춘다. 다시 시작 버튼을 누르면 물고기가 다시 움직인다.

 

물고기를 움직이는 방법 :  물고기.css("left", 위치값)

 

	<script>

		$(document).ready(function(){
			//물고기 노드 구하기.
			var $fish = $("#fish");

			// 물고기가 한번에 움직일 거리
			var step = 50;

			$("#btnStart").click(function(){
				// 다음 물고기 위치
				var x = $fish.position().left+step;

				// 물고기 위치가 430을 넘는 경우, 물고기 이동방향을 뒤쪽으로 변경 해줌
				if(x>=430){
				x=430;
				$fish.attr("src","fish2.png");
					step=-50;
				}

				// 물고기 위치가 50보다 작은 경우, 물고기 이동방향을 앞쪽으로 변경 해줌
				if(x<50){
					x=50;
					$fish.attr("src","fish1.png");
					step=50;
				}
			   // 물고기 위치 설정
				$fish.css("left", x);

			});

			$("#btnStop").click(function(){


			})
		});

	</script>



<div> 		
	<div id="panel">
		<img src="fish1.png" id="fish">
		<div id="bar"> </div>								
	</div>
	
	<div id="nav">
		<button id="btnStart">시작</button>
		<button id="btnStop">멈춤</button>
	</div>
</div>
       

 

 

- 구현하기

<script>

$(document).ready(function(){   

    //물고기 노드 구하기.
    var $fish = $("#fish");
    
    // 물고기가 한번에 움직일 거리  
    var step = 50;  
    var timerID = 0;
    
    
    // 물고기 움직이기
    $("#btnStart").click(function(){        
    
        if(timerID==0){
            timerID=setInterval(function(){
                
                // 다음 물고기 위치
                var x = $fish.position().left+step;
                
                // 물고기 위치가 430을 넘는 경우, 물고기 이동방향을 뒤쪽으로 변경 해줌             
                if(x>=430){                         
                    x=430;
                    $fish.attr("src","fish2.png");
                    step=-50;
                }
                
                // 물고기 위치가 50보다 작은 경우, 물고기 이동방향을 앞쪽으로 변경 해줌
                if(x<50){
                    x=50;
                    $fish.attr("src","fish1.png");
                    step=50;
                }
                // 물고기 위치 설정
                $fish.css("left", x);
                
            },100);
        }
    });
    
    
    // 물고기 멈추기
    $("#btnStop").click(function(){
        clearInterval(timerID);
        timerID=0;
    })
}); 


</script>
</head>

<body>	
	<div> 
		
		<div id="panel">
			<div id="bar"> </div>			
			<img src="fish1.png" id="fish">			
		</div>
		<div id="nav">
            <button id="btnStart">시작</button>
            <button id="btnStop">멈춤</button>
		</div>
	</div>       
</body>

 

물고기를 자동으로 움직이게 하기위해서 익명함수로 묶어서 타이머 함수랑 연결시킨다.

timerID=setInterval(function(){ 이렇게 묶어준 후에 1초에 한번씩 실행되도록한다.

 

var timerID = 0; 변수를 만든다 타이머를 멈추기 위해서 반드시 필요하다.

 

정지버튼을 클릭하면 타이머 함수를 정지시킨다.

 $("#btnStop").click(function(){
        clearInterval(timerID);
        timerID=0;
    })

 

 

 

- 리팩토링1

리펙토링이란 쉽게 말해 코드를 다듬는 작업이다. 빠트린 주석을 추가하는 작업부터 중복된 코드 없애주는 작업 그리고 커다란 함수 덩어리를 보기 좋게 여러개의 함수로 나눠 작업하는 등을 리팩토링이라고 한다.

 

        <script>

            var $fish = null;
            // 물고기가 한번에 움직일 거리
            var step = 50;
            var timerID = 0;

            $(document).ready(function() {
                init();
                initEvent();
            });

            // 요소 초기화
            function init() {
                //물고기 노드 구하기.
                $fish = $("#fish");
            }

            // 이벤트 초기화
            function initEvent() {

                // 물고기 움직이기
                $("#btnStart").click(function() {

                });

                // 물고기 멈추기
                $("#btnStop").click(function() {

                })
            }

        </script>
    </head>

    <body>
        <div>

            <div id="panel">
                <div id="bar"></div>
                <img src="fish1.png" id="fish">
            </div>
            <div id="nav">
                <button id="btnStart">
                    시작
                </button>
                <button id="btnStop">
                    멈춤
                </button>
            </div>
        </div>
    </body>

1.먼저 ready()에 만든 지역변수를 전역변수로 만들어준다
2.init()함수를 신규로 만든 후 계속해서 사용할 물고기 요소를 변수에 담아 준다.
3. initEvent()를 만든 후 이벤트 등록 코드를 넣어 준다. 
4. 시작부분은 ready()에 init()함수와 initEvent()를 호출해 준다. 

 

 

 

리팩토링2

 

        <script>

            var $fish = null;
            // 물고기가 한번에 움직일 거리
            var step = 50;
            var timerID = 0;

            $(document).ready(function() {
                init();
                initEvent();
            });

            // 요소 초기화
            function init() {
                //물고기 노드 구하기.
                $fish = $("#fish");
            }

            // 이벤트 초기화
            function initEvent() {

                // 물고기 움직이기
                $("#btnStart").click(function() {
                    start();
                });

                // 물고기 멈추기
                $("#btnStop").click(function() {
                    stop();
                })
            }

            // 물고기 움직이기 타이머 실행
            function start() {

                if (timerID == 0) {
                    timerID = setInterval(function() {

                        // 물고기 움직이기
                        moveFish();

                    }, 100);
                }
            }

            // 물고기 멈추기
            function stop() {
                clearInterval(timerID);
                timerID = 0;
            }

            // 물고기 움직이기
            function moveFish() {
                // 다음 물고기 위치
                var x = $fish.position().left + step;

                // 물고기 위치가 430을 넘는 경우, 물고기 이동방향을 뒤쪽으로 변경 해줌
                if (x >= 430) {
                    x = 430;
                    $fish.attr("src", "fish2.png");
                    step = -50;
                }

                // 물고기 위치가 50보다 작은 경우, 물고기 이동방향을 앞쪽으로 변경 해줌
                if (x < 50) {
                    x = 50;
                    $fish.attr("src", "fish1.png");
                    step = 50;
                }
                // 물고기 위치 설정
                $fish.css("left", x);
            }

        </script>

 

 

1. 물고기를 움직이게 하는 코드가 구현된 익명함수를 moveFish라는  이름의 전역함수로 만들어 준다.
2. start()라는 함수를 신규로 만든 후 타이머를 생성하는 로직을  넣어준다.타이머 함수에는 moveFish()함수를 연결해 준다.
3. stop()함수를 신규로 만든 후 타이머를 정지시키는 로직을 넣어 준다.
4, 5 마지막으로 시작 버튼과 정지버튼을 클릭 이벤트 리스너에서  start() 함수와 stop() 함수를 각각 호출해 준다.

728x90
반응형

댓글