2014-12-07 3 views
-2

나는 대화 형 게임을 만들고 있으며 프로그래밍에 익숙하지 않습니다. 변수를 증가시키고 경고 상자에 넣는 방법에 대해 궁금합니다. 나는 음식의 계산을 찾고 싶다. 잡은 음식과 음식은 내 게임이 끝날 때 경고 상자에 표시한다. 또한 타이머를 켜고 타이머를 끝내면 어떻게 음식을 넣을 수있는 경고 상자가 나타납니다. 먹기와 음식 낭비가 나타 납니까?알림에 계산을 만드는 방법은 무엇입니까?

$(document).ready(function(){ 
    var cnv = $("#myCanvas")[0]; 
    var ctx = cnv.getContext("2d"); 
    var catcherX = ctx.canvas.width/2; 
    var catcherY = ctx.canvas.height - 100; // set the initial location of the catcher's y position 
    var numFoods = 5; 
    var catcherSpeed = 30; 
    var foodCaught = 0; 
    var foodWasted = 0; 

    function Food(){ // the name of the constructor usually begins with a captial letter 
     this.radius = 30; 

     this.x = Math.floor(Math.random()*ctx.canvas.width); 
     this.y = 0 - this.radius; 
     this.speed = 1+ Math.floor(Math.random()*5); 
     var imageToUse = new Image(); 
     this.width = 50; // default values 
     this.height = 50; // default values 

     var randomNum = Math.floor(Math.random()*2); // create a random number to choose the image 
     if(randomNum == 0){ 

      imageToUse.src = "corn.png"; 
      this.width = 27; // width of corn.png 
      this.height = 100; // height of corn.png 

     } else if(randomNum == 1){ 
      imageToUse.src = "straw.png" 
      this.width = 83; // width of straw.png 
      this.height = 100; // height of straw.png 
     } 

     this.moveFood = function(){ 

      if(this.y > ctx.canvas.height){ 
       this.x = Math.floor(Math.random()*ctx.canvas.width); 
       this.y = 0; 
       footWasted += 1; 
      } 

      this.y += this.speed; // add speed to location 
     } 

     this.drawFood = function() { 
      ctx.drawImage(imageToUse, this.x, this.y); 
     } 

     this.intersectFood = function(targetX, targetY, targetR) { 

      if(this.x + this.width > targetX && this.x < targetX + targetR && this.y + this.height > targetY && this.y < targetY + targetR){ 
       foodCaught += 1; 
       return true; 
      } 

      /* 
      var distanceX = this.x - targetX; 
      var distanceY = this.y - targetY; 
      var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY); 

      if(distance < targetR + this.radius){ 
       return true; 
      } 
      */ 
     } 
    } 
    // create an Array of Foods 
    var FoodArray = new Array(); 
    for(var i=0; i<numFoods; i++) { 
     FoodArray[i] = new Food(); 
    } 

    // get mouse Postion 

    $(document).keydown(function(e){ // attach the event to the entire document 

     switch(e.keyCode){ 
      case 37: // left 
       catcherX-= catcherSpeed; 
       break; 
      case 39: // right 
       catcherX+= catcherSpeed; 
       break; 
     } 

    }); 

    var interval = setInterval(gameLoop,10); // call draw every 10 milliseconds 
    var counter = 0; 

    function gameLoop(){ 
     ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height); //clears previous circles 
     for(var i=0; i < FoodArray.length; i++) { 
      FoodArray[i].moveFood(); 
      FoodArray[i].drawFood(); 
      if(FoodArray[i].intersectFood(catcherX, catcherY, 15)){ 
       FoodArray.splice(i,1); 
       console.log(i); 
      } 
     } 

     // draw catcher 
     ctx.beginPath(); 
     ctx.fillStyle="#119933"; 
     ctx.arc(catcherX,catcherY,15,0,Math.PI*2,true); 
     ctx.closePath(); 
     ctx.fill(); 
+1

기본 변수 저장 및 경고에 대한 지식없이 자바 스크립트 객체 지향을 사용하는 초보자. 아이러니합니다. –

+0

* "나는 만들고있다"* - 나는 위의 코드를 작성했지만 변수를 늘리는 데 도움이 필요하다고 믿을 수 없다. 표시된 코드에는 이미 변수를 증가시키는 많은 예제가 있습니다. 경고를 위해서 당신은 setInterval보다는 setTimeout을 원하지만 타이머도 있습니다. – nnnnnn

+0

아래에서 내 대답을 찾아 질문을 해결하는 경우 허용으로 표시하십시오. –

답변

1

게임이 종료

후 업데이트 답변, 수행

alert("foodCaught = " + foodCaught + "<br>foodWasted = " + foodWasted); 

그냥이 alertfoodCaughtfoodWasted 변수의 범위를 withing에 있는지 확인하십시오.

편집 : 게임이 실제로 끝없는됩니다

. 끝까지! gameLoop() 10 밀리 초마다 전화를 계속 setInterval! 이와

function gameLoop(){ 
    ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height); //clears previous circles 
    for(var i=0; i < FoodArray.length; i++) { 
     FoodArray[i].moveFood(); 
     FoodArray[i].drawFood(); 
     if(FoodArray[i].intersectFood(catcherX, catcherY, 15)){ 
      FoodArray.splice(i,1); 
      //console.log(i); 
     } 
    } 

    // draw catcher 
    ctx.beginPath(); 
    ctx.fillStyle="#119933"; 
    ctx.arc(catcherX,catcherY,15,0,Math.PI*2,true); 
    ctx.closePath(); 
    ctx.fill(); 

    console.log("foodCaught = " + foodCaught + "\nfoodWasted = " + foodWasted); 

} 

foodCaughtfoodWasted의 값을 얻을 것이다 : 아래의 코드와 같이

gameLoop() 함수의 끝 부분에 console.log() 문을 추가, foodCaughtfoodWasted 변수의 트랙을 유지하려면 변수는 gameLoop 함수가 호출 될 때마다 반환됩니다.

콘솔 사용 방법을 모르는 경우 this post을 확인하십시오.

EDIT2 :

내가이 게임을 종료하는 것에 대한 아이디어를 가지고있다. 아래의 업데이트 된 코드에서 나는 setTimeout()을 사용하여 게임을 10 초 동안 실행하도록 설정했습니다 (예제를 사용하면 빠르게 변경할 수 있습니다). 원하는 기간으로 변경할 수 있습니다. setTimeout()에서 필요한 값을 경고합니다. 여기

업데이트 된 자바 스크립트/jQuery 코드입니다 :

$(document).ready(function(){ 
    var cnv = $("#myCanvas")[0]; 
    var ctx = cnv.getContext("2d"); 
    var catcherX = ctx.canvas.width/2; 
    var catcherY = ctx.canvas.height - 100; // set the initial location of the catcher's y position 
    var numFoods = 5; 
    var catcherSpeed = 30; 
    var foodCaught = 0; 
    var foodWasted = 0; 



    function Food(){ // the name of the constructor usually begins with a captial letter 
     this.radius = 30; 

     this.x = Math.floor(Math.random()*ctx.canvas.width); 
     this.y = 0 - this.radius; 
     this.speed = 1+ Math.floor(Math.random()*5); 
     var imageToUse = new Image(); 
     this.width = 50; // default values 
     this.height = 50; // default values 

     var randomNum = Math.floor(Math.random()*2); // create a random number to choose the image 
     if(randomNum == 0){ 

      imageToUse.src = "corn.png"; 
      this.width = 27; // width of corn.png 
      this.height = 100; // height of corn.png 

     } else if(randomNum == 1){ 
      imageToUse.src = "straw.png" 
      this.width = 83; // width of straw.png 
      this.height = 100; // height of straw.png 
     } 




     this.moveFood = function(){ 

      if(this.y > ctx.canvas.height){ 
       this.x = Math.floor(Math.random()*ctx.canvas.width); 
       this.y = 0; 
       foodWasted += 1; 
      } 

      this.y += this.speed; // add speed to location 

     } 

     this.drawFood = function() { 
      ctx.drawImage(imageToUse, this.x, this.y); 
     } 

     this.intersectFood = function(targetX, targetY, targetR) { 

      if(this.x + this.width > targetX && this.x < targetX + targetR && this.y + this.height > targetY && this.y < targetY + targetR){ 
       foodCaught += 1; 
       return true; 
      } 
      /* 

      var distanceX = this.x - targetX; 
      var distanceY = this.y - targetY; 
      var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY); 

      if(distance < targetR + this.radius){ 
       return true; 
      } 
      */ 

     } 


    } 

    function gameLoop(){ 
     ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height); //clears previous circles 
     for(var i=0; i < FoodArray.length; i++) { 
      FoodArray[i].moveFood(); 
      FoodArray[i].drawFood(); 
      if(FoodArray[i].intersectFood(catcherX, catcherY, 15)){ 
       FoodArray.splice(i,1); 
      } 
     } 

     // draw catcher 
     ctx.beginPath(); 
     ctx.fillStyle="#119933"; 
     ctx.arc(catcherX,catcherY,15,0,Math.PI*2,true); 
     ctx.closePath(); 
     ctx.fill(); 

    } 

    $(document).keydown(function(e){ // attach the event to the entire document 

     switch(e.keyCode){ 
      case 37: // left 
       catcherX-= catcherSpeed; 
       break; 
      case 39: // right 
       catcherX+= catcherSpeed; 
       break; 
     } 

    }); 


    // create an Array of Foods 
    var FoodArray = new Array(); 
    for(var i=0; i<numFoods; i++) { 
     FoodArray[i] = new Food(); 
    }  

    var interval = setInterval(gameLoop,10); // call draw every 10 milliseconds 

    setTimeout(function(){ 
     clearInterval(interval);   
     alert("Time UP!\n\nfoodCaught = " + foodCaught + "\nfoodWasted = " + foodWasted); 
    }, 10000); 

}); 
+0

문서 준비 상태로 두지 마십시오. 경고는 게임이 끝날 때 표시되며 페이지가로드 된 후 5 초가 지나면 표시되지 않습니다. – nnnnnn

+0

@nnnnnn 감사합니다. 그러나 'foodCaught' 및'foodWasted '변수는'$ (document) .ready()'에 있습니다. –

+0

@Helen 답변이 업데이트되었습니다. 이상적으로는이 변수의 범위 안에이'alert '를 넣으면 코드가 깨지지 않아야한다. 게임이 끝나는 곳을 정확히 알지 못하므로 '경고'를 적절한 곳에 추가하십시오. 또는 youi가 원하는 경우 jsFiddle 데모에서 문제를 재현 할 수 있으므로 귀하를 더 도울 수 있습니다. –

관련 문제