JavaScript game example: simple keyboard practice

Time:2020-9-25

Keyboard is a kind of common input equipment. It is a basic skill for computer users to input flexibly and skillfully. Let’s write a simple keyboard practice game.

1. Small interactive animation of puncturing bubbles

Before writing a simple keyboard practice game, first design a simple bubble piercing interactive animation.

At the bottom of the panel, rise some bubbles one by one, click on a bubble with the mouse, the bubble is punctured, and the small bubble after puncturing gradually dissipates in the panel. The interactive effect is shown in Figure 1.

 

Interactive bubble 1 animation

A bubble can be divided into two states: (1) the bubble rises from the bottom of the panel; (2) the bubble is punctured into small bubbles by mouse click, or the bubble rises over the top of the panel and dissipates.

Two object classes are abstracted: bubbles and minibubbles. Among them, bubbles are used to represent a bubble that has not been punctured, and minibubbles is used to represent a small bubble that gradually dissipates after a bubble is punctured.

The bubbles object class defines six attributes: the coordinates (x, y) of the bubble center, radius of the bubble, yspeed of the vertical displacement change, gravity of the bubble rising acceleration and color of the bubble.

The initial value of coordinate attribute value y is the height of the canvas, which indicates that the bubble rises from the bottom of the game panel. The initial values of other attributes are determined by random numbers or specified directly. The specific definitions are as follows:

   function Bubbles()

   {

      this.x = rand(30,canvas.width – 30);

      this.y = canvas.height;

      this.radius = rand(15, 30);

      this.color =’rgba(255, 255, 255, 0.75)’;

      this.ySpeed= Math.random() * 2;

      this.gravity = 0.01;

   }

The bubbles object class defines two methods: draw () to draw bubbles and update () to change coordinates when bubbles rise.

The minibubbles object class defines eight attributes: coordinates (x, y) representing the center of small bubbles, radius of small bubbles, horizontal and vertical displacement variables XSPEED and yspeed when dispersing, filling color of small bubbles, deceleration gravity of small bubbles, and time to live of small bubbles. The specific definitions are as follows:

   function miniBubbles(x,y,radius)

   {

      this.x = x;

      this.y = y;

      this.radius = radius;

      this.color = ‘rgba(255, 255, 255, 0.5)’;

      this.xSpeed=(Math.random() – 0.5) * 0.6;

      this.ySpeed=(Math.random() – 1) * 0.5;

      this.gravity = -0.03;

      this.timeToLive = 100;

   }

The minibubbles object class defines two methods: draw () for drawing small bubbles and update () for changing the position of small bubbles. When the timetolive value is equal to 0, the small bubble is deleted from the small bubble array, indicating that the small bubble has died.

Two arrays, VAR bubbles = []; and VaR minibubbles = []; are defined to store the non punctured large bubble objects and the small bubbles scattered after the big bubbles are punctured.

Add mouse down event monitoring to canvas canvas.addEventListener (‘mousedown ‘, function() {});, find the bubble that the mouse clicks in the event handler function, and then delete the bubble from the bubbles array, and add several scattered small bubbles to the minibubbles array.

The complete HTML code is as follows.

Puncture bubble games




   var canvas = document.getElementById('myCanvas');
   var ctx = canvas.getContext('2d');
   canvas.height = innerHeight;
   canvas.width = innerWidth;
   function rand(min, max)
   {
      return Math.floor(Math.random() * (max - min + 1) + min);
   }
   function Bubbles() 
   {
      this.x = rand(30,canvas.width - 30);
      this.y = canvas.height;
      this.radius = rand(15, 30);
      this.color ='rgba(255, 255, 255, 0.75)';
      this.ySpeed= Math.random() * 2; 
      this.gravity = 0.01;
   }
   Bubbles.prototype.draw = function () 
   {
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
      ctx.fillStyle = this.color;
      ctx.fill();
      ctx.closePath();
   }
   Bubbles.prototype.update = function () 
   {
      this.y -= this.ySpeed;
      if (this.y - this.radius > 0) 
         this.ySpeed += this.gravity;
      this.draw();
   }
   function miniBubbles(x,y,radius) 
   {
      this.x = x;
      this.y = y;
      this.radius = radius;
      this.color = 'rgba(255, 255, 255, 0.5)';
      this.xSpeed=(Math.random() - 0.5) * 0.6;
      this.ySpeed=(Math.random() - 1) * 0.5;
      this.gravity = -0.03;
      this.timeToLive = 100;
   }
   miniBubbles.prototype.draw = function () {
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
      ctx.fillStyle = this.color;
      ctx.fill();
      ctx.closePath();
   }
   miniBubbles.prototype.update = function () {
      if (this.y - this.radius > 0) 
         this.ySpeed += this.gravity;
      this.x += this.xSpeed;
      this.y += this.ySpeed;
      this.timeToLive --;
      this.draw();
   }
   var backgroundGradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
   backgroundGradient.addColorStop(0, '#009cff')
   backgroundGradient.addColorStop(1, '#007bff')
   var bubbles = [];
   var minibubbles = [];
   var timer = 0;
   var spawnRate = 70;
   function animate() 
   {
      requestAnimationFrame(animate);
      ctx.fillStyle = backgroundGradient;
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      for (var i=bubbles.length-1;i>=0;i--)
      {
          bubbles[i].update();
       if (bubbles[i].y<0) 
          {
             bubbles.splice(i, 1);
          }
      }         
      for (var i=minibubbles.length-1;i>=0;i--)
      {
         minibubbles[i].update();
     if (minibubbles[i].timeToLive == 0) 
         {
            minibubbles.splice(i, 1);
         }
      }
      timer++;
      if (timer==spawnRate) 
      {
     bubbles.push(new Bubbles());
         timer=0;
     spawnRate = rand(50, 100);
      }
    }
    canvas.addEventListener('mousedown', function(){
        var x = event.pageX - canvas.getBoundingClientRect().left;
        var y = event.pageY - canvas.getBoundingClientRect().top;
        //Find the bubbles you click on
        for (var i=bubbles.length-1; i>=0; i--)
        {
            var bubble = bubbles[i];
            var dist = Math.sqrt(Math.pow(bubble.x-x,2)+ Math.pow(bubble.y- y,2));
            if (dist<= bubble.radius)
            {
                 var mx = bubble.x;
         var my = bubble.y;
                 var mr = rand(2,5);
         bubbles.splice(i, 1)
         for (var k = 0; k < bubble.radius/mr; k++) 
                 {
                    minibubbles.push(new miniBubbles(mx,my, mr));
         }
                 return;
            }
        }
    });
   animate();

2. Simple keyboard practice games

With the above foundation, we can write a simple keyboard exercise game, upper and lower case letters appear in the game panel, press a certain letter key on the keyboard, the corresponding letters disappear. The game process is shown in Figure 2.

 

Figure 2 keyboard practice games

Add an attribute letter to the bubbles object class to represent the letters displayed in the bubble.

Add a keyboard for windows, press keypress event to monitor and handle keyboard keys.

The complete HTML code is as follows.

JavaScript game example: simple keyboard practiceJavaScript game example: simple keyboard practice

Simple keyboard exercises




   var canvas = document.getElementById('myCanvas');
   var ctx = canvas.getContext('2d');
   canvas.height = innerHeight;
   canvas.width = innerWidth;
   var str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
   var cnt1=0;
   var cnt2=0;
   var cnt3=0;
   function rand(min, max)
   {
      return Math.floor(Math.random() * (max - min + 1) + min);
   }
   function Bubbles() 
   {
      this.x = rand(30,canvas.width - 30);
      this.y = canvas.height;
      this.radius = 20;
      this.color ='rgba(255, 255, 255, 0.75)';
      this.ySpeed= Math.random() * 2; 
      this.gravity = 0.01;
      this.letter=str.charAt(rand(0,str.length-1));
   }
   Bubbles.prototype.draw = function () 
   {
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
      ctx.fillStyle = this.color;
      ctx.fill();
      ctx.closePath();
      ctx.font = "Bold 20px Georgia";
      ctx.fillStyle = "Black";
      ctx.textAlign = 'center';
      ctx.baseline = 'middle';
      ctx.fillText(this.letter,this.x, this.y);
   }
   Bubbles.prototype.update = function () 
   {
      this.y -= this.ySpeed;
      if (this.y - this.radius > 0) 
         this.ySpeed += this.gravity;
      this.draw();
   }
   function miniBubbles(x,y,radius) 
   {
      this.x = x;
      this.y = y;
      this.radius = radius;
      this.color = 'rgba(255, 255, 255, 0.5)';
      this.xSpeed=(Math.random() - 0.5) * 0.6;
      this.ySpeed=(Math.random() - 1) * 0.5;
      this.gravity = -0.03;
      this.timeToLive = 100;
   }
   miniBubbles.prototype.draw = function () {
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
      ctx.fillStyle = this.color;
      ctx.fill();
      ctx.closePath();
   }
   miniBubbles.prototype.update = function () {
      if (this.y - this.radius > 0) 
         this.ySpeed += this.gravity;
      this.x += this.xSpeed;
      this.y += this.ySpeed;
      this.timeToLive --;
      this.draw();
   }
   var backgroundGradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
   backgroundGradient.addColorStop(0, '#009cff')
   backgroundGradient.addColorStop(1, '#007bff')
   var bubbles = [];
   var minibubbles = [];
   var timer = 0;
   var spawnRate = 70;
   function animate() 
   {
      requestAnimationFrame(animate);
      ctx.fillStyle = backgroundGradient;
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.font = "Bold 30px Georgia";
      ctx.fillStyle = "Black";
      ctx.textAlign = 'center';
      ctx.baseline = 'middle';
      Var MES = correct key press times: + cnt1 + "invalid key times: + CNT2 +" number of lost letters: + CNT3;  
      ctx.fillText(mess,canvas.width/2,35);
      
      for (var i=bubbles.length-1;i>=0;i--)
      {
          bubbles[i].update();
       if (bubbles[i].y<30) 
          {
             cnt3++;
             bubbles.splice(i, 1);
          }
      }         
      for (var i=minibubbles.length-1;i>=0;i--)
      {
         minibubbles[i].update();
     if (minibubbles[i].timeToLive == 0) 
         {
            minibubbles.splice(i, 1);
         }
      }
      timer++;
      if (timer==spawnRate) 
      {
     bubbles.push(new Bubbles());
         timer=0;
     spawnRate = rand(50, 100);
      }
    }
    window.addEventListener('keypress', function(e){
        var keyID = e.keyCode ? e.keyCode :e.which;
        for (var i=0;i<bubbles.length-1;i++)
        {
            var bubble = bubbles[i];
            if (keyID== bubble.letter.charCodeAt(0))
            {
                 var mx = bubble.x;
         var my = bubble.y;
                 var mr = rand(2,5);
         bubbles.splice(i, 1)
                 cnt1++;
         for (var k = 0; k < bubble.radius/mr; k++) 
                 {
                    minibubbles.push(new miniBubbles(mx,my, mr));
         }
                 return;
            }
        }
        cnt2++;
    },true);
   animate();

View Code