search
HomeWeb Front-endJS TutorialHow to implement a 'color identification' mini game in ES6

The content of this article is about the method of implementing a "color identification" mini-game in ES6. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Preface

I vaguely remember the color identification game that was popular in the circle of friends a few years ago, to find rectangles with different colors. A few days ago, I had a sudden idea to write a similar game by hand. Without further ado, let’s start with the demo. --Project source code

This example is implemented based on ES6 and is compatible with ie9 and above.

2. Project structure

index.html index.css index.js

This article mainly talks about how to use js to implement functions, html css is not here scope. Go directly to the code.

<!--index.html-->
nbsp;html>



  <meta>
  <meta>
  <meta>
  <link>
  <title>suporka color game</title>



  <p>
    </p><p>
      </p><h1 id="辨色力测试">辨色力测试</h1>
      <p>找出所有色块里颜色不同的一个</p>
      <a>开始挑战</a>
    
    <header>
      <h1 id="辨色力测试">辨色力测试</h1>
    </header>

    <aside>
    </aside>

    <section>
    </section>
    
    <footer>
      <p> <a> my blog</a></p>
      ©<a>Suporka</a>
      ©<a>My book</a>
      ©<a>My Github</a>
    </footer>
  

<!-- <script src="index.js"></script> -->
<script></script>
<script>
  // 事件兼容方法,兼容ie
  function addEvent(element, type, handler) {
    if (element.addEventListener) {
      element.addEventListener(type, handler, false);
    } else if (element.attachEvent) {
      element.attachEvent("on" + type, handler);
    } else {
      element["on" + type] = handler;
    }
  }
  window.onload = function () {
    addEvent(document.querySelector(&#39;#start&#39;), &#39;click&#39;, function() {
      document.querySelector(&#39;#page-one&#39;).style.display = &#39;none&#39;
      new ColorGame({
        time: 30
      })
    })
  }
</script>
/*index.css*/
body {
  background-color: #FAF8EF;
}
footer {
  display: block;
  margin-top: 10px;
  text-align: center;
}
h1 {
  font-size: 2em;
  margin: .67em 0;
}
a {
  text-decoration: none;
}
footer a {
  margin-right: 14px;
}
.container {
  margin: auto;
  padding: 0 10px;
  max-width: 600px;
}
.wgt-home {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding-top: 50px;
  font-size: 20px;
  background: #fc0;
  text-align: center;
  color: #fff;
}

.wgt-home p {
  margin-top: 4em;
}

.btn {
  display: inline-block;
  margin-bottom: 0;
  font-weight: 400;
  text-align: center;
  vertical-align: middle;
  cursor: auto;
  background-image: none;
  border: 1px solid transparent;
  white-space: nowrap;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.42857143;
  border-radius: 4px;
  -webkit-user-select: none;
  user-select: none;
}
.btn-lg {
  padding: 10px 16px;
  font-size: 18px;
  line-height: 1.33;
  border-radius: 6px;
}
.btn-primary {
  color: #fff;
  background-color: #428bca;
  border-color: #357ebd;
}
.wgt-home .btn {
  margin-top: 4em;
  width: 50%;
  max-width: 300px;
}
.screen {
  display: block;
  margin-top: 10px;
  padding: 1px;
}
.screen .block {
  float: left;
  box-sizing: border-box;
  padding: 1px;
}
.screen .block .block-inner {
  content: ' ';
  display: block;
  width: 100%;
  padding-top: 100%;
  border-radius: 2px;
  -webkit-user-select: none;
  user-select: none;
}
.result {
  color: red;
  text-align: center;
  font-size: 20px;
  cursor: pointer;
}
// index.js
// es6 class
class ColorGame {
  constructor() {
  }
}

3. Function implementation

A game object has its default configuration, which can also be set individually by the user, so——

// index.js
class ColorGame {
  constructor(userOption) {
    this.option = {
      time: 30, // 总时长
      end: score => {
        document.getElementById(
          "screen"
        ).innerHTML = `<p>
        </p><p> You score is ${score} <br> click to start again</p>
      `;
        addEvent(document.getElementById("restart"), "click", () => {
          this.init();
        });
      } // 结束函数
    }
    this.init(userOption); // 初始化,合并用户配置
  }
}

Configurable in this game It is the total game duration time and the end method end().

In the above code, the user's score is displayed when the game ends, and the user can click to restart the game. addEvent() is an event listening method compatible with IE. The code is as follows:

// 事件兼容方法
function addEvent(element, type, handler) {
  if (element.addEventListener) {
    element.addEventListener(type, handler, false);
  } else if (element.attachEvent) {
    element.attachEvent("on" + type, handler);
  } else {
    element["on" + type] = handler;
  }
}

init() with The parameter is used to initialize the game, and the function without parameters is used to restart the game. Therefore -

// index.js
class ColorGame {
  constructor(userOption) {
    // ...
  }
  init(userOption) {

    this.step = 0; // 关卡
    this.score = 0; // 得分

    if (userOption) {
      if (Object.assign) {
        // 合并用户配置, es6写法
        Object.assign(this.option, userOption);
      } else {
        // 兼容es6写法
        extend(this.option, userOption, true);
      }
    }

    // 倒计时赋值
    this.time = this.option.time;
    // 设置初始时间和分数
    document.getElementsByClassName(
      "wgt-score"
    )[0].innerHTML = `得分:<span>${this.score}</span>
    时间:<span>${this.time}</span>`;

    // 开始计时, es6 箭头函数
    window.timer = setInterval(() => {
      if (this.time === 0) {
        // 如果时间为0,clearInterval并调用结束方法
        clearInterval(window.timer);
        this.option.end(this.score);
      } else {
        this.time--;
        document.getElementById("timer").innerHTML = this.time;
      }
    }, 1000);

    this.nextStep(); // 下一关
  }
}

extend() is the way to write the compatibility merge configuration. The specific code is as follows:

// 合并参数方法
function extend(o, n, override) {
  for (var p in n) {
    if (n.hasOwnProperty(p) && (!o.hasOwnProperty(p) || override))
      o[p] = n[p];
  }
}

nextStep() This is the core method of the game, which will be introduced in detail below.

// index.js
class ColorGame {
  constructor(userOption) {
    // ...
  }
  init(userOption) {
    // ...
  }
  nextStep() {
  }
}

The main body of the game is an n*n matrix graphic, and the size of each small box is the same, except that one piece of it has a different color, and the general color of each level is also different. , so we need to randomly obtain a color and return a special color that gradually approaches the general color as the level increases.

The color is composed of RGB three colors. The closer the three color values ​​are, the closer the color display is. As the level increases, the trichromatic value difference of the two colors is infinitely close to 0. At this time, I remembered the inverse proportional function in middle school (infinitely close to the x-axis). This article uses 100/step (Decreases as the step increases).

/**
 * 根据关卡等级返回相应的一般颜色和特殊颜色
 * @param {number} step 关卡级别
 */
function getColor(step) {
  // rgb 随机加减 random
  let random = Math.floor(100/step);

  // 获取随机一般颜色,拆分三色值
  let color = randomColor(17, 255),
    m = color.match(/[\da-z]{2}/g);

  // 转化为 10 进制
  for (let i = 0; i  255) {
    return "ff";
  } else if (temp > 16) {
    return temp.toString(16);
  } else if (temp > 0) {
    return "0" + temp.toString(16);
  } else {
    return "00";
  }
}

/**
 * 随机颜色
 * @param {number} min 最小值
 * @param {number} max 最大值
 */
function randomColor(min, max) {
  var r = randomNum(min, max).toString(16);
  var g = randomNum(min, max).toString(16);
  var b = randomNum(min, max).toString(16);
  return r + g + b;
}
/**
 * 随机数
 * @param {number} min 最小值
 * @param {number} max 最大值
 */
function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

After talking about the basic methods, let’s talk about the nextStep() method.

First of all, the matrix must have a maximum number of columns. If it is too small, it is difficult to operate and the display will not look good.

Secondly, determine the number of columns col in each level, and then you can know the total number of small boxes col col, store the HTML fragment string of each box into a length of col In the array arr of col, randomly modify the color of one of them to a special color, give this p a special id, and monitor the click event of this dom element. If clicked, enter the next level.

// index.js
class ColorGame {
  constructor(userOption) {
    // ...
  }
  init(userOption) {
    // ...
  }
  nextStep() {
    // 记级
    this.step++;
    let col; // 列数
    // 设置列数,最高不超过16
    if (this.step 
    <p></p>
  `;

    // 包含所有盒子的数组
    let arr = [];

    // 初始化数组
    for (let i = 0; i 
    <p></p>
  `;

    // 修改页面 dom 元素
    document.getElementById("screen").innerHTML = arr.join("");

    // 监听特殊盒子点击事件
    addEvent(document.getElementById("special-block"), "click", () => {
      this.nextStep();
      this.score++;
      // 修改得分
      document.getElementById("score").innerHTML = this.score;
    });
  }
}

Writing this, please open index.html. Has the function been implemented? Is this the end of the story? Well, if you are careful, you may find that this game does not work in IE, and IE is not compatible with es6 syntax. what to do?

4. Compatibility and expansion

In order to be compatible with IE, we need to convert the es6 syntax into es5 and use babel to compile it.

We found that this js file can only be imported through the script tag. I want it to be compatible with common.js or require.js module import. What should I do?

--UMD, here is an article about the modularization of js, which involves UMD. Students in need can take a look - Javascript Modularization

The following is a detailed description of how to use webpack To achieve the above requirements:

// webpack.js

const path = require('path');

module.exports = {
  entry: {
    index: './index.js', //入口
  },
  module: {
    rules: [
      { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
  ],
  output: {
    path: path.resolve(__dirname, './'),
    library: 'ColorGame',
    libraryExport: "default",
    libraryTarget: 'umd',
    filename: 'colorGame.js',
  },
};

index.js file, add export default ColorGame

to the last line of the file and execute the command webpack --config ./webpack.js

index.html to introduce the generated colorGame.js can

The above is the detailed content of How to implement a 'color identification' mini game in ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use