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.
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.
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--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="index.css"> <title>suporka color game</title> </head> <body> <p class="container"> <p class="wgt-home" id="page-one"> <h1>辨色力测试</h1> <p>找出所有色块里颜色不同的一个</p> <a id="start" class="btn btn-primary btn-lg">开始挑战</a> </p> <header class="header"> <h1>辨色力测试</h1> </header> <aside class="wgt-score"> </aside> <section id="screen" class="screen"> </section> <footer> <p> <a href="http://zxpsuper.github.io" style="color: #FAF8EF"> my blog</a></p> ©<a href="https://zxpsuper.github.io">Suporka</a> ©<a href="https://zxpsuper.github.io/Demo/advanced_front_end/">My book</a> ©<a href="https://github.com/zxpsuper">My Github</a> </footer> </p> </body> <!-- <script src="index.js"></script> --> <script src="colorGame.js"></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('#start'), 'click', function() { document.querySelector('#page-one').style.display = 'none' new ColorGame({ time: 30 }) }) } </script> </html>
/*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() { } }
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 class="result" style="width: 100%;"> <p class="block-inner" id="restart"> You score is ${score} <br/> click to start again</p> </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 id="score">${this.score}</span> 时间:<span id="timer">${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 < m.length; i++) m[i] = parseInt(m[i], 16); //rgb let specialColor = getRandomColorNumber(m[0], random) + getRandomColorNumber(m[1], random) + getRandomColorNumber(m[2], random); return [color, specialColor]; } /** * 获取随机颜色相近的 rgb 三色值 * @param {number} num 单色值 * @param {number} random 随机加减的数值 */ function getRandomColorNumber(num, random) { let temp = Math.floor(num + (Math.random() < 0.5 ? -1 : 1) * random); if (temp > 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 < 6) { col = this.step + 1; } else if (this.step < 12) { col = Math.floor(this.step / 2) * 2; } else if (this.step < 18) { col = Math.floor(this.step / 3) * 3; } else { col = 16; } // 小盒子宽度 let blockWidth = ((100 / col).toFixed(2) * 100 - 1) / 100; // 随机盒子index let randomBlock = Math.floor(col * col * Math.random()); // 解构赋值获取一般颜色和特殊颜色, es6 解构 let [normalColor, specialColor] = getColor(this.step); // es6 模板字符串 let item = `<p class="block" style="width: ${blockWidth}%;"> <p class="block-inner" style="background-color: #${normalColor}"></p> </p>`; // 包含所有盒子的数组 let arr = []; // 初始化数组 for (let i = 0; i < col * col; i++) arr.push(item); // 修改随机盒子 arr[randomBlock] = `<p class="block" style="width: ${blockWidth}%;"> <p class="block-inner" style="background-color: #${specialColor}" id="special-block"></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?
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!