2015-12-18 4 views
1

Когда я пытаюсь изменить табло с помощью переменной computerCount (как вы можете видеть в инструкции if в функции обновления для шаровой переменной), другие номера отображаются неправильно. Имейте в виду, что сначала 0 работает правильно.Как обновить текст, записанный на холсте

Screenshot of the Pong game

JSFiddle format - Вы можете изменить код, перейдя в правом верхнем углу, который говорит "Edit" в JSFiddle.

Код:

<!doctype html> 
<html lang="en"> 

<head> 
    <meta charset="UTF-8"> 
    <title>Pong</title> 

    <!-- Basic styling, centering the canvas --> 
    <style> 
    canvas{ 
     position: absolute; 
     margin: auto; 
     top:60px; 
     bottom:0; 
     right:0; 
     left:0; 
    } 

    #scoreBoard{ 
     position: absolute; 
     margin: auto; 
     top:0; 
     bottom:640px; 
     right:720px; 
     left:20px; 
    } 

    </style> 
</head> 

<body> 

    <canvas id = "scoreBoard" width="500" height = "100"></canvas> 
    <script> 
     var WIDTH = 700 
     var HEIGHT = 600 
     var pi = Math.PI 
      var canvas 
      var ctx 
      var keystate 
      var upArrow = 38; 
      var downArrow = 40; 
      var computerCount = 0; 
      var playerCount = 0; 

      var player = { 
       x: null, 
       y: null, 
       width: 20, 
       height: 100, 
       /** 
       * Update the position depending on pressed keys 
       */ 
       update: function() { 
       if(keystate[upArrow]){ 
        this.y-=7; 
       } 
       if(keystate[downArrow]){ 
        this.y+=7; 
       }}, 
       /** 
       * Draw the player paddle to the canvas 
       */ 

       draw: function() { 
        ctx.fillRect(this.x, this.y, this.width, this.height); 
       } 
      } 
      /** 
      * The ai paddle 
      * 
      * @type {Object} 
      */ 
      var ai = { 
       x: null, 
       y: null, 
       width: 20, 
       height: 100, 
       /** 
       * Update the position depending on the ball position 
       */ 
       update: function() { 
        var desty = ball.y-(this.height - ball.side)*0.5 
        this.y += (desty-this.y)*0.2; 

       }, 

       draw: function() { 
        ctx.fillRect(this.x, this.y, this.width, this.height); 
       } 
      } 
      /** 
      * The ball object 
      * 
      * @type {Object} 
      */ 
      var ball = { 
       x: null, 
       y: null, 
       vel:null, 
       side: 20, 
       speed:5, 



       update: function() { 

       this.x += this.vel.x; 
       this.y += this.vel.y; 

       if(0>this.y || this.y+this.side>HEIGHT){ 
       var offset = this.vel.y<0 ? 0-this.y : HEIGHT-(this.y+this.side); 
       this.y+=2*offset 
       this.vel.y*=-1;    
       } 

       var AABBIntersect = function(ax, ay, aw, ah, bx, by, bw, bh) { 
       return ax < bx+bw && ay < by+bh && bx < ax+aw && by < ay+ah; 
       }; 


       var pdle = this.vel.x<0 ? player : ai; 
       if(AABBIntersect(pdle.x,pdle.y,pdle.width,pdle.height, this.x, this.y, this.side, this.side)){ 

       this.x = pdle===player ? player.x + player.width : ai.x - this.side; 

       var n = (this.y+this.side-pdle.y)/(pdle.height+this.side) 
       var phi = 0.25*pi*(2*n - 1) // pi/4 = 45 

       this.x = pdle===player ? player.x+player.width : ai.x - this.side; 
       var n = (this.y+this.side - pdle.y)/(pdle.height+this.side); 
       var phi = 0.25*pi*(2*n - 1); // pi/4 = 45 
       this.vel.x = (pdle===player ? 1 : -1)*this.speed*Math.cos(phi); 
       this.vel.y = this.speed*Math.sin(phi); 

       } 


       if(ball.x<0){ 
        computerCount =+1; 
        ball.x = (WIDTH - ball.side)/2; 
      ball.y = (HEIGHT - ball.side)/2; 
       } 

       }, 
       // reset the ball when ball outside of the canvas in the 


       draw: function() { 
        ctx.fillRect(this.x, this.y, this.side, this.side); 
       } 
      } 

      function score(){ 


      } 
      /** 
      * Starts the game 
      */ 
     function main() { 
      // create, initiate and append game canvas 
      canvas = document.createElement("canvas"); 
      canvas.width = WIDTH; 
      canvas.height = HEIGHT; 
      ctx = canvas.getContext("2d"); 
      document.body.appendChild(canvas); 

      canvas2 = document.createElement("canvas"); 
      canvas2.setAttribute("id", "scoreBoard"); 
      canvas2.width = 200; 
      canvas2.height = 100; 
      ctx2 = canvas2.getContext("2d"); 
      document.body.appendChild(canvas2); 

      keystate = {}; 
      document.addEventListener("keydown" , function(event){ 
       keystate[event.keyCode] = true; 
      }) 

      document.addEventListener("keyup" , function(event){ 
       delete keystate[event.keyCode]; 
      }) 

      init(); 

      var loop = function() { 
       update(); 
       draw(); 
       window.requestAnimationFrame(loop, canvas); 
      }; 
      window.requestAnimationFrame(loop, canvas); 
     } 
     /** 
     * Initatite game objects and set start positions 
     */ 
     function init() { 
      player.x = player.width; 
      player.y = (HEIGHT - player.height)/2; 
      ai.x = WIDTH - (player.width + ai.width); 
      ai.y = (HEIGHT - ai.height)/2; 
      ball.x = (WIDTH - ball.side)/2; 
      ball.y = (HEIGHT - ball.side)/2; 
      ball.vel = { 
       x:ball.speed, 
       y: 0 

      } 


     } 
     /** 
     * Update all game objects 
     */ 
     function update() { 
      ball.update(); 
      player.update(); 
      ai.update(); 
     } 

     function draw(){ 







      ctx.fillStyle = "black" 
      ctx.fillRect(0,0,WIDTH,HEIGHT) 

      ctx.save(); 
      ctx2.fillStyle = "red" 
      ctx2.fillText(String(computerCount),100,100) 
      ctx2.fillText("VS",120,100) 
      ctx2.fillText(String(playerCount),175,100) 
      ctx2.font = "bold 40px monaco" 
      ctx.fillStyle = "white" 
      ball.draw(); 
      player.draw(); 
      ai.draw(); 

      var w=4; 
      var x= (WIDTH-w)*0.5; 
      var y=2; 
      var step = HEIGHT/20; 
      while(y<HEIGHT){ 
      ctx.fillRect(x,y+step*0.25,w,step*0.5) 
      y+=step; 
      } 

      ctx.restore(); 


     } 


     // start and run the game 
     main(); 
    </script> 
</body> 

</html> 

ответ

0

Упомянуто @Ishamael, количество компьютеров в строке 139 необходимо заменить на computerCount += 1; //After this if statement add if the player scores.

В строке 221,

function draw(){ 
    ctx.fillStyle = "black"; 
    ctx.fillRect(0,0,WIDTH,HEIGHT); 
    ctx.save(); 
    ctx2.fillStyle = "black"; 
    ctx2.fillRect(0,0,WIDTH, 100); 
    ctx2.save(); 
    ctx2.fillStyle = "red"; 
    ctx2.font = "bold 40px monaco"; 
    ctx2.fillText(String(computerCount),100,100); 
    ctx2.fillText("VS",120,100); 
    ctx2.fillText(String(playerCount),175,100); 
    ctx2.save(); 
    ctx.fillStyle = "white"; 
    . . . 
} 

запомнить вашу запятую и установить стиль текста, прежде чем писать. Я также добавил перерисовку, чтобы стереть предыдущий табло.

+0

Как обычно Клейтон! Огромное спасибо! Теперь я постараюсь сделать игру Doodle Jump! –

2

У вас есть две проблемы:

  1. Когда вы рисуете номер, вы не стирают предыдущий номер, который уже напечатаны. То есть, когда счет становится равным 1, вы оказываете 1 сверху из уже вынесенного 0. Самый простой способ обратиться к нему - сделать fillRect и нарисовать черный прямоугольник поверх ранее написанного балла, прежде чем нарисовать новый балл.

  2. Когда вы исправить это, вы заметите, что ваш счет никогда не идет выше 1. Причина опечатка в коде, который увеличивает его заменить

computerCount =+1; 

с

computerCount += 1; 
+0

Хм. так что если я нарисую пустой прямоугольник поверх него, не повлияет ли он на текущий счет? Смутно, как я это делаю? –

+0

Я отредактировал его. Тем не менее, есть еще черный ящик. –

+0

Можете ли вы показать мне свое редактирование? –

Смежные вопросы