IT & CODE 이야기

Math 클래스 예제(물고기 잡기 게임) 본문

CODE/JQuery

Math 클래스 예제(물고기 잡기 게임)

Karoid 2016. 2. 19. 00:36

 

갤러리 배열

이번 예제는 jquery로 Math 클래스를 연습할수 있는 예제입니다. 예제의 조건은 다음과 같습니다.

  1. 게임의 목표는 10초 안에 물고기를 많이 클릭할수록 점수를 얻는 게임입니다.
  2. 게임 시작하기 버튼을 누르면 버튼이 사라지고 물고기가 박스 안에 나타나고 계속해서 움직입니다.
  3. 물고기를 클릭하면 하단의 점수란의 점수가 클릭한 수만큼 올라가고, 흘러간 시간이 표시됩니다.
  4. 물고기는 랜덤한 지점을 향해 계속 이동하고 그 지점에 도착하면 다른 랜덤한 지점을 설정해 움직입니다
  5. 제한된 시간이 끝나면 물고기가 사라지고 점수가 표시됩니다. 
  6. 물고기 src:https://t1.daumcdn.net/cfile/tistory/2637484856B21E3332
    물고기 width:200px; position:relative;
    박스 width:700px; height:442px; border:2px solid grey; margin:auto;
  7. 느낌이 오지 않는다면 아래 예제를 한번 실행시켜보세요

아래는 예제를 완성시킨 모습입니다.

fish
경과 시간: 0
점수:0

이 예제의 코드

<style media="screen"> #box{width:700px; height:442px; border:2px solid grey;margin:auto;} #pos_text{text-align: center;} #accept{ width:120px; height:60px; border:1px blue solid; background-color: grey; margin-left:auto; margin-top:10px; margin-right:auto; } #fish{width:200px; position:relative;} </style> <input type="button" value="게임 시작하기" id="startGame"> <div id="box"> <img id="fish" src="https://t1.daumcdn.net/cfile/tistory/2637484856B21E3332" alt="fish" /> </div> <div id="pos_text"> 경과 시간: <span id="time">0</span><br/> 점수:<span id="point">0</span><br /> </div> <SCRIPT src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></SCRIPT> <script type="text/javascript"> var x=250; var y=150; var point=0; var timer=0; var objectiveX = 100; var objectiveY = 100; $('#fish').css('display', 'none'); getPoint(); started(); function getPoint(){ $('#fish').click(function() { point++; $('#point').html(point) }); } function started(){ $('#startGame').click(function() { started_init(); a = setInterval(function(){ started_timer(); started_moving(); console.log(Math.atan2(objectiveY-y,objectiveX-x)); },20) setTimeout(function(){ end_init(); },10000) }); function started_init(){ $('#fish').css('display', ''); $('#startGame').css('display', 'none'); $('#point').html(point) } function started_timer(){ timer++; $("#time").html(Math.floor(timer/50)) } function started_moving(){ if((x-objectiveX)*(x-objectiveX)+(y-objectiveY)*(y-objectiveY)<30){ objectiveX = 500*Math.random(); objectiveY = 300*Math.random(); } var angle = Math.atan2(objectiveY-y,objectiveX-x) x+=10*Math.cos(angle); y+=10*Math.sin(angle); if (500<x) { x=500; }else if (0>x) { x=0; }else if (y>300) { y=300; }else if (y<0) { y=0; } $('#fish').css({ left:x, top:y, }); } } function end_init(){ $('#fish').css('display', 'none'); $('#startGame').css('display', ''); timer = 0; point = 0; x=250; y=150; clearInterval(a); } </script>

 

'CODE > JQuery' 카테고리의 다른 글

.charAt 예제  (0) 2016.02.20
SetInterval과 clearInterval 활용 예제  (4) 2016.02.17
갤러리를 배열하기  (0) 2016.02.11
animate() 예제 (물고기 움직이기)  (0) 2016.02.08
이미지를 x축 이동시키기  (0) 2016.02.07
Comments