user5613751
user5613751

Reputation:

How to update text written on canvas

When I try to change the scoreboard using the computerCount variable (as you can see in my if statement in the update function for the ball variable) the other numbers aren't shown properly. Keep in mind that at first 0 works properly.

Screenshot of the Pong game

JSFiddle format - You can change code by going at top right corner that says "Edit" in JSFiddle.

Code:

<!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>

Upvotes: 1

Views: 746

Answers (2)

cwahls
cwahls

Reputation: 753

Mentioned by @Ishamael, line 139's computer count needs to be changed to computerCount += 1; //After this if statement add if the player scores.

In line 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";
    . . .
}

remember your semicolons and set text style before writing. I also added the repaint to erase the previous scoreboard.

Upvotes: 0

Ishamael
Ishamael

Reputation: 12795

You have two problems:

  1. When you draw a number, you do not erase the previous number that is already printed. That is, when the score becomes 1, you render 1 on top of already rendered 0. The easiest way to address it is to do fillRect and draw a black rectangle on top of the previously written score before you draw a new score.

  2. When you fix that, you will notice that your score never goes above 1. The reason is a typo in the code that increments it, replace

computerCount =+1;

with

computerCount += 1;

Upvotes: 2

Related Questions