Home > Web Front-end > JS Tutorial > How to implement a number matching game using javascript

How to implement a number matching game using javascript

亚连
Release: 2018-06-20 17:25:43
Original
2247 people have browsed it

The editor below will share with you an example of how to implement a digital matching game using JavaScript. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor and take a look.

The game effect is shown in the picture below:

How to implement a number matching game using javascript

Rules:

In the 4X5 grid, there are 10 random numbers that are not equal to each other, and there are two copies of each data (that is, 20 numbers, there are two Two equal ten pairs), randomly distributed in 20 grids. The game starts and a sequence of twenty numbers pops up. Each time you click the grid, the data in the current grid will be displayed and temporarily retained until the next click. If the data displayed by the next click is different from the retained data, the data retained by the previous click will disappear (still exist in the grid but not show). If the two data displayed by continuous clicks are the same, both data will be displayed and will not disappear again.

Until all data are displayed by continuously clicking on the same data, the game is over and the game time is reported. At this point you can click Start Game or Refresh to continue.

Analysis:

1: Twenty grids correspond to twenty data, two sets of ten equal random numbers are generated and placed Array, the array subscript determines the display position.

2: There are three states of each grid: data hiding, temporary data retention and permanent display. The data hidden grid is temporarily retained by the next click. The grid that temporarily retains data will be permanently displayed or data hidden by clicking the next time. It is judged based on whether the data obtained twice in a row are equal. After permanent display, the status is no longer changeable and can only be displayed permanently. At this time, it is invalid for clicks.

3: Timing starts when the first grid is clicked after clicking the start button. The timer cannot be stopped until the game is completed or you click Refresh to restart.

4: It follows that a Boolean value is needed here to record whether the game has started. The game that has already started should reject the start button, and the timer runs until the game is completed. When the game is complete, change the boolean value, the timer stops working, the game time is displayed, and the start button becomes available.

Implementation:

The table is created through script, and the elements in it are first displayed as "" empty strings by default. Displayed by corresponding click. CSS styles can be set by yourself.

<table border:1>
  <script>
   var rowlength = 4;
   var collength = 5;
   var str = &#39;&#39;;
   for (var i = 0; i < rowlength; i++) {
    str += &#39;<tr>&#39;
    for (var j = 0; j < collength; j++) {
     //这里将每个td的id拼接为imgxx xx为元素索引
     var index = i * collength + j;
     var id = "img" + index;
     //注意这里字符串 每个&#39;&#39;是一个字符串进行输出
      str += &#39;<td id="&#39; + id + &#39;" onclick="showImg(&#39; + index + &#39;)">&#39;;
     str += &#39;</td>&#39;;
    }
    str += &#39;</tr>&#39;
   }
   document.write(str);
  </script>
 </table>
Copy after login

NEW_STARTVariable that records whether the game can be started

times records the elapsed time

trans records the flip status of each grid, each array The grid has three states: 0: hidden - 1: displayed (can still be flipped) - 2: displayed (cannot be flipped). That is, each element of the array has only three possible values ​​0, 1, 2)

numArr A random sequence array of thirty numbers

var NEW_START = true;
  var times = 0;
  var trans = [];
  var numArr = [];
Copy after login

Method of obtaining elements through ID:

 function $(id) {
  return document.getElementById(id);
   }
Copy after login

The following is a function to obtain twenty random numbers, ten equal groups (see: Generating random numbers in a specified range)

function getNum() {
    var index = 0;
    var arrLength = rowlength * collength / 2;
    var arr = new Array();
    while (index < arrLength) {
     var flag = true;
     var num = parseInt(Math.random() * 100);
     for (var i in arr) {
      if (arr[i] == num || arr[i] < 1) {
       flag = false;
      }
     }
     if (flag == true) {
      arr[index] = num;
      index++;
     }
    }
    //alert(arr.length);
    //arr是十个互不相等的随机数 
    // newArr数组就是每个随机数都有两个的数组
    var newArr = new Array();
    for (var i = 0; i < arrLength; i++) {
     newArr[i] = arr[i];
     newArr[arrLength + i] = arr[i];
    }
    return newArr;
   }
Copy after login

Creating tables and generating random number arrays are all preparatory work.

The following is the specific logic:

Click function to start the game

<input type="button"
 id="startButton" 
value="开始游戏" 
onclick="init()">
Copy after login

Click to start the game, you need to initialize the game related Parameters, please note that if it has already started, you need to reject the processing. Use the sorting function to shuffle the array elements to achieve randomness.

function init() {
    //如果已经开始 拒绝点击
    if (NEW_START == false) {
     return;
    }
    //结束时用于显示时间的h4标签
    $(&#39;end&#39;).innerHTML = &#39;&#39;;
    var count = rowlength * collength;
    //将每个格子的数据隐藏 初始化每个格子的翻转状态
    for (var i = 0; i < count; i++) {
     $(&#39;img&#39; + i).innerHTML = &#39;&#39;;
     trans[i] = 0;
    }
    //将游戏用时置为0
    times = 0;
    $(&#39;gametime&#39;).innerHTML = times + &#39;秒&#39;;
    //获取随机的三十个数的随机序列数组 注意排序函数的使用
    numArr = getNum().sort(function () {
     return Math.random() - 0.5;
    });
    alert("已生成随机数,按表格顺序排列:" + numArr);
   }
Copy after login

Timing function

When you click on the first grid, you need to start timing. NEW_START=false means it has already started. You need to ensure that the timer is only started when the game is in progress. Calls itself once per second and displays the elapsed time in real time through innerHTML.

用时:<span id="gametime">0秒</span>
 function countTime() {
    if (NEW_START == false) {
     setTimeout(&#39;countTime()&#39;, 1000);
     $(&#39;gametime&#39;).innerHTML = times + "秒";
     times++;
    }
   }
Copy after login

The click function of each grid (super important)

Refuses to click the grid before it starts (no effect). Enter the game and click on the first grid. The game starts and the status changes. NEW_START=false means that a new game has been started and cannot be created. Timing begins.

The subsequent click event needs to determine the clicked grid to process different logic:

Clicking on an element that has been permanently displayed does not process return.

Clicking on an element that has just been displayed but is not permanently displayed does not handle return.

(Note that to determine whether the same element is the same element, the index index is found directly in trans through the status value and compared)

Click on the undisplayed element to get the value and compare it with the previously displayed element Comparison:

is equal, the status value of the corresponding index in trans is changed to 2, indicating that

is permanently displayed, and the corresponding index status value of the newly clicked element in trans is changed to 1 (temporarily Reserved), the index value of the previously clicked element is 0 (needs to be hidden).

After setting the status value, you need to update the display immediately (refreshUI function). When updating the display, it operates based on the array trans that records the status value.

function showImg(index) {
    //未点击开始,还未初始化,退出
    if (numArr[0] == undefined) {
     return;
    }
    //初次点击进入,开启计时
    if (NEW_START) {
     NEW_START = false;
     countTime();
    }
    //1-点击已经彻底显示的元素 退出
    if (trans[index] == 2) {
     return;
    }
    //将点击的格子的元素显示出来,并改变翻转状态
    //alert(index);
    //alert(numArr)
    var clickEle = $(&#39;img&#39; + index);
    clickEle.innerHTML = numArr[index];
    //已点击元素的index
    var transIndex;
    for (var i in trans) {
     if (trans[i] == 1) {
      transIndex = i;
     }
    }
    //2-如果点击的是刚刚已显示元素
    if (transIndex == index) {
     trans[index] = 1;
     return;
    }
    //3-点击新元素 与先前显示元素对比 两种情况-相等 不等
    else {
     if (numArr[transIndex] == numArr[index]) {
      trans[transIndex] = 2;
      trans[index] = 2;
     } else {
      trans[transIndex] = 0;
      trans[index] = 1;
     }
    }
    refreshUI();
   }
Copy after login

Set the displayed function refreshUI based on the status value

根据trans中每个元素的值,改变对应索引的格子的值。注意,如果格子的数据永久显示,需要记录已经永久显示的格子的数量,当等于所有格子数量时,表示已经全部显示。需要判定游戏结束,显示出游戏用时。

function refreshUI() {
    //此处用fore循环会最后存在一个undefined
    //count记录已经被彻底显示的个数
    var count = 0;
    for (var i = 0; i < trans.length; i++) {
     if (trans[i] == 0) {
      $(&#39;img&#39; + i).innerHTML = &#39;&#39;;
     }
     if (trans[i] == 1) {
      $(&#39;img&#39; + i).innerHTML = numArr[i];
     }
     if (trans[i] == 2) {
      $(&#39;img&#39; + i).innerHTML = numArr[i]
      count++;
     }
    }
    if (count == collength * rowlength) {
     NEW_START = true;
     var endTime = times;
     $(&#39;end&#39;).innerHTML = &#39;用时&#39; + endTime + &#39;秒!!游戏结束,点击开始游戏继续&#39;;
     $(&#39;gametime&#39;).innerHTML = endTime + "秒";
    }
   }
Copy after login

通过数组和表格的配合,实现How to implement a number matching game using javascript,加深对表格创建和数组的运用。处理逻辑和数据显示分离,根据状态值做到不同显示的状态。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在vue中如何实现跳转到之前页面

在Nginx中如何配置多站点vhost

在express+mockjs中如何实现后台数据发送

使用mock.js生成随机数据

使用Node.js如何实现资讯爬虫(详细教程)

The above is the detailed content of How to implement a number matching game using javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template