依稀記得幾年前朋友圈流行的辨色小遊戲,找出顏色不一樣的矩形。前些天突發奇想,打算本身手寫一個相似的遊戲,話很少說,先上 Demo . --項目源碼javascript
本實例基於 ES6 實現,併兼容 ie9及以上。css
index.html index.css index.js
html
本文主要講述如何使用 js 實現功能,html css 不在此範圍。直接上代碼。java
<!--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>
<div class="container">
<div class="wgt-home" id="page-one">
<h1>辨色力測試</h1>
<p>找出全部色塊裏顏色不一樣的一個</p>
<a id="start" class="btn btn-primary btn-lg">開始挑戰</a>
</div>
<header class="header">
<h1>辨色力測試</h1>
</header>
<aside class="wgt-score">
</aside>
<section id="screen" class="screen">
</section>
<footer>
<div> <a href="http://zxpsuper.github.io" style="color: #FAF8EF"> my blog</a></div>
©<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>
</div>
</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() {
}
}
複製代碼
一個遊戲對象有其默認的配置,也能夠由使用者單獨設置,所以——node
// index.js
class ColorGame {
constructor(userOption) {
this.option = {
time: 30, // 總時長
end: score => {
document.getElementById(
"screen"
).innerHTML = `<div class="result" style="width: 100%;"> <div class="block-inner" id="restart"> You score is ${score} <br/> click to start again</div> </div>`;
addEvent(document.getElementById("restart"), "click", () => {
this.init();
});
} // 結束函數
}
this.init(userOption); // 初始化,合併用戶配置
}
}
複製代碼
此遊戲中能夠配置的爲遊戲總時長 time 以及結束方法 end()。webpack
上述代碼中游戲結束時顯示用戶得分,而且使其點擊能夠從新開始遊戲,addEvent() 爲兼容 ie 的事件監聽方法,代碼以下:git
// 事件兼容方法
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() 帶參數時爲初始化遊戲,不帶參數爲遊戲從新開始的功能。所以——es6
// 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() 爲兼容性合併配置的寫法,具體代碼以下:github
// 合併參數方法
function extend(o, n, override) {
for (var p in n) {
if (n.hasOwnProperty(p) && (!o.hasOwnProperty(p) || override))
o[p] = n[p];
}
}
複製代碼
nextStep() 爲此遊戲的核心方法,下面將詳細介紹。web
// index.js
class ColorGame {
constructor(userOption) {
// ...
}
init(userOption) {
// ...
}
nextStep() {
}
}
複製代碼
遊戲主體爲 n*n 的矩陣圖形,而且每一個小盒子的大小一致,只是其中有一塊顏色不同凡響,每一個關卡的通常顏色也不相同,所以咱們須要隨機獲取一個顏色,而且根據關卡級別的增長返回一個逐漸接近通常顏色的特殊顏色。
顏色由 RGB 三色構成,三色值越接近,則顏色顯示越接近。隨着等級的增長,兩種顏色的三色值差無限接近與 0. 此時我想起了中學時代的反比例函數(無限接近於x軸), 本文用的是 100/step(隨着step增大而減少).
/** * 根據關卡等級返回相應的通常顏色和特殊顏色 * @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);
}
複製代碼
講完了基本的方法,接下講述nextStep() 方法。
首先,矩陣必需要有最多的列數限制,過小很差操做,顯示也很差看。
其次,肯定每一個關卡的列數 col,便可得知小盒子的總個數 col * col, 將每一個盒子的 HTML 片斷字符串存入長度爲 col * col 的數組 arr 中,再隨機修改其中一個的顏色賦值爲特殊顏色,並給這個 div 一個特殊 id,且監聽此 dom 元素的點擊事件,若點擊了,則進入下一個關卡。
// 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 = `<div class="block" style="width: ${blockWidth}%;"> <div class="block-inner" style="background-color: #${normalColor}"></div> </div>`;
// 包含全部盒子的數組
let arr = [];
// 初始化數組
for (let i = 0; i < col * col; i++) arr.push(item);
// 修改隨機盒子
arr[randomBlock] = `<div class="block" style="width: ${blockWidth}%;"> <div class="block-inner" style="background-color: #${specialColor}" id="special-block"></div> </div>`;
// 修改頁面 dom 元素
document.getElementById("screen").innerHTML = arr.join("");
// 監聽特殊盒子點擊事件
addEvent(document.getElementById("special-block"), "click", () => {
this.nextStep();
this.score++;
// 修改得分
document.getElementById("score").innerHTML = this.score;
});
}
}
複製代碼
寫到這裏,請打開 index.html ,是否是實現了該有的功能?故事是否是就這麼結束了?嗯,細心的你可能會發現,此遊戲在 ie 中行不通,ie 不兼容 es6 語法。怎麼辦?
爲了兼容 ie , 咱們須要把 es6 語法轉化爲 es5, 使用 babel 編譯便可。
咱們發現此 js 文件只可經過 script 標籤引入,我想讓它兼容 common.js 或者 require.js 的模塊引入,該怎麼作?
--UMD, 這裏有篇文章講述到 js 的模塊化,裏面有涉及 UMD, 有須要的同窗能夠看看——Javascript 模塊化
下面具體講述如何使用 webpack 實現上述需求:
// 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 文件最後一行添加 export default ColorGame
執行命令webpack --config ./webpack.js
index.html 引入生成的 colorGame.js
便可。