1. 程式人生 > >html小遊戲——看你有多色

html小遊戲——看你有多色

前幾天一個朋友問了我要做看你有多色這樣的一個遊戲需要怎麼學,我也就自己寫了一下。

我有放在自己的個人網站上:檢視遊戲

原始碼也放在了github上:檢視原始碼

現在開始說明制過程:

專案結構

注:偷懶用了jquery,其實程式碼不多,完全可以原生js,另外,由於這次我沒有使用圖片,所以img裡面的內容是空的

game 
    -index.html
    -css
        -index.css
    -js
        -index.js
        -jqeuery.js
    -img

遊戲介面

  • loading: 主要用於載入遊戲資源
  • 啟動遊戲: 可以寫些遊戲規則,點選開始遊戲就開始遊戲
  • 遊戲中:遊戲進行的頁面
  • 遊戲暫停: 遊戲暫停的頁面
  • 遊戲結束: 遊戲結束的頁面

每個頁面使用一個div表示,進行到哪一步就將哪一個頁面div的display變為block,從而顯示。

程式碼展示

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>找找看</title>
    <meta name="viewport"
content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1">
<link href="./css/index.css" rel="stylesheet"> </head> <body> <!--載入頁面--> <div class="page loading" style="display: none"> <p>載入中...</p> </div> <!--開始遊戲頁面 -->
<div class="page index" style="display: none"> <h1>找找看</h1> <p class="tip"> 找出所有色塊裡顏色不同的一個 </p> <button class="start-game"> 開始遊戲 </button> </div> <!--遊戲中--> <div class="page room" style="display: block;"> <div class="top"> <span class="score">得分:0</span> <span class="time">60</span> <span class="btn btn-pause">暫停</span> </div> <div id="box"></div> </div> <!--暫停--> <div class="page pause"> <h1>遊戲暫停</h1> <button class="continue"> 繼續遊戲 </button> </div> <!--遊戲結束--> <div class="page over"> <h1>遊戲結束</h1> <p class="result"> 總分:0 </p> <button class="restart"> 重新開始 </button> </div> <script src="./js/jquery-1.7.1.min.js"></script> <script src="./js/index.js"></script> </body> </html>

index.css

/* 重置樣式 */
html,body,h1,h2,h3,h4,h5,h6,div,dl,dt,dd,ul,ol,li,p,blockquote,pre,hr,figure,table,caption,th,td,form,fieldset,legend,input,button,textarea,menu{margin:0;padding:0;}
header,footer,section,article,aside,nav,hgroup,address,figure,figcaption,menu,details{display:block;}
table{border-collapse:collapse;border-spacing:0;}
caption,th{text-align:left;font-weight:normal;}
html,body,fieldset,img,iframe,abbr{border:0;}
i,cite,em,var,address,dfn{font-style:normal;}
[hidefocus],summary{outline:0;}
li{list-style:none;}
h1,h2,h3,h4,h5,h6,small{font-size:100%;}
sup,sub{font-size:83%;}
pre,code,kbd,samp{font-family:inherit;}
q:before,q:after{content:none;}
textarea{overflow:auto;resize:none;}
label,summary{cursor:default;}
a,button{cursor:pointer;}
h1,h2,h3,h4,h5,h6,em,strong,b{font-weight:normal;}
del,ins,u,s,a,a:hover{text-decoration:none;}
body,textarea,input,button,select,keygen,legend{font:16px/1 "Microsoft Yahei", Arial, Helvetica, Sans-Serif,\5b8b\4f53;color:#333;outline:0;}
a,a:hover{color:#444;}
button{padding:0;margin:0;border:0;background-color:#fff;}

html, body { height: 100%; width: 100%; overflow: hidden;}
body { background-color: rgb(18, 149, 73);}
.page { display: none; position: relative; height: 100%; max-width: 600px; margin: 0 auto; color: #fff; text-align: center; }
.loading { display: block;}
.loading p {
    position: absolute; top: 50%; left: 50%; width: 200px; height: 30px; margin-left: -100px; margin-top: -15px;
    line-height: 30px; font-size: 26px;
}
.index h1 { font-size: 30px; padding: 30px 0; }
.index p { height: 40px; line-height: 40px; font-size: 20px; color: #adffe0; text-align: center;}
.index button, .pause button, .over button{
    display: block; position: absolute; bottom: 100px; left: 50%;
    height: 50px; width: 220px; margin-left: -110px; border-radius: 7px;
    line-height: 50px; box-shadow: 0 5px #da9622;
    color: inherit; cursor: pointer; font-weight: 700; font-size: 20px;
    background: #fcad26;
}
#box {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 500px;
    height: 500px;
    margin-left: -260px;
    margin-top: -260px;
    border-radius: 10px;
    padding: 10px;
    background-color: #ddd;
}

@media only screen and (max-width: 500px) and (min-width: 414px) {
    #box {
        width: 380px;
        height: 380px;
        margin-left: -200px;
        margin-top: -200px;
    }
}
@media only screen and (max-width: 414px) and (min-width: 375px) {
    #box {
        width: 340px;
        height: 340px;
        border-radius: 8px;
        margin-left: -180px;
        margin-top: -180px;
    }
}
@media only screen and (max-width: 375px) {
    #box {
        width: 300px;
        height: 300px;
        border-radius: 5px;
        margin-left: -160px;
        margin-top: -160px;
    }
}
#box span {
    display: block;
    float: left;
    border-radius: 10px;
    cursor: pointer;
    border: 5px solid #ddd;
    position: relative;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
#box.lv2 span {
    width: 50%;
    height: 50%;
}
#box.lv3 span {
    width: 33.3333%;
    height: 33.3333%;
}
#box.lv4 span {
    width: 25%;
    height: 25%;
}
#box.lv5 span {
    width: 20%;
    height: 20%;
}
#box.lv6 span {
    width: 16.666%;
    height: 16.666%;
}
#box.lv7 span {
    width: 14.285%;
    height: 14.285%;
}
.score {
    position: absolute;
    top: 10px;
    left: 5px;
    color: #adffe0;
}
.time {
    position: absolute;
    top: 5px;
    left: 50%;
    display: block;
    color: #fff;
    width: 50px;
    margin-left: -25px;
    height: 24px;
    line-height: 24px;
    border-radius: 10px;
    text-align: center;
    font-size: 20px;
    font-weight: 700;
    background-color: rgb(117, 214, 171);
}
.btn-pause{
    display: block; position: absolute; top: 5px; right: 5px;
    height: 24px; width: 60px; border-radius: 7px;
    line-height: 24px; box-shadow: 0 4px #da9622;
    color: inherit; cursor: pointer; font-weight: 500; font-size: 16px;
    background: #fcad26;
}
.pause h1, .over h1{
    height: 150px;
    line-height: 150px;
    font-size: 30px;
}
.over p {
    font-size: 26px;
}

index.js

var game = {};
//快取
game.pages = $('.page');
game.startBtn = $('.start-game').eq(0);
game.pauseBtn = $('.btn-pause').eq(0);
game.continueBtn = $('.continue').eq(0);
game.restartBtn = $('.restart').eq(0);
game.blockBox = $('#box');
game.scoreBox = $('.score').eq(0);
game.timeBox = $('.time').eq(0);
game.resultBox = $('.result').eq(0);
game.eventType = document.ontouchstart ? 'touchstart' : 'click';
game.imgUrls = [];
game.time = 60;
game.score = 0;
game.level = 0;
game.levelMap = [2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7];
game.colorDiff = [115, 100, 100, 85, 85, 85, 70, 70, 70, 70, 55, 55, 55, 55, 55, 40, 40, 40, 40, 40, 40, 25, 25, 25, 25, 25, 25, 25, 10, 10, 10, 10, 10, 10, 10, 10];
game.diffIndex = 0;
//載入遊戲
game.loading = function () {
    var imgCounts = this.imgUrls.length;
    if ( imgCounts == 0) {
        this.switchPage(1);
        this.initEvent();
    } else {
        var num = 0,
            self = this;
        function count () {
            num++;
            if ( num == imgCounts ) {
                self.switchPage(1);
                self.initEvent();
            }
        }
        for ( var i = 0; i < imgCounts; i++ ) {
            var img = new Image();
            img.onload = count;
            img.src = this.imgUrls[i];
        }
    }
};
//初始化事件
game.initEvent = function () {
    this.startBtn.on(this.eventType, this.start.bind(this));
    this.restartBtn.on(this.eventType, this.start.bind(this));
    this.blockBox.on(this.eventType, this.clickBlock.bind(this));
    this.pauseBtn.on(this.eventType, this.pause.bind(this));
    this.continueBtn.on(this.eventType, this.continue.bind(this));
};
//點選方塊事件
game.clickBlock = function ( event ) {
    if ( event.target.tagName.toLowerCase() === 'span' ) {
        //選對了
        if ( $(event.target).index() == this.diffIndex ) {
            this.level++;
            this.score++;
            this.render();
        } else {
            this.over()
        }
    }
};
//開始遊戲
game.start = function () {
    this.switchPage(2);
    this.render();
    this.timeCount();
};
//遊戲介面渲染
game.render = function () {
    //獲取有n*n
    var num = this.levelMap[this.level] ? this.levelMap[this.level] : this.levelMap[this.levelMap.length - 1],
        colorDiff = this.colorDiff[this.level] ? this.colorDiff[this.level] : this.colorDiff[this.colorDiff.length - 1],
        color = [],
        lvColor = [];
    //分數
    this.scoreBox.html('得分:' + this.score);
    //時間
    this.timeBox.html(this.time);
    //給box新增類名
    this.blockBox[0].className = 'lv' + num;
    //得到不同塊的index
    this.diffIndex = Math.floor(Math.random() * num * num);
    //獲取顏色
    color = this.getColor(257 - colorDiff);
    lvColor = this.getLvColor(color[0], colorDiff);
    //新增block
    var str = '';
    num *= num;
    for ( var i = 0; i < num; i++ ) {
        if ( i == this.diffIndex ) {
            str += '<span style="background-color: ' + lvColor[1] + ';"></span>';
        } else {
            str += '<span style="background-color: ' + color[1] + ';"></span>';
        }
    };
    this.blockBox.html(str);
};
//得到隨機顏色
game.getColor = function (max) {
    var t = [Math.floor(Math.random() * max), Math.floor(Math.random() * max), Math.floor(Math.random() * max)];
    return [t, "rgb(" + t.join(",") + ")"];
};
//得到不同的顏色
game.getLvColor = function (color, diff) {
    var r = [];
    r[0] = color[0] + diff;
    r[1] = color[1] + diff;
    r[2] = color[2] + diff;
    return [r, "rgb(" + r.join(",") + ")"];
};
//遊戲結束處理
game.over = function () {
    this.switchPage(4);
    this.resultBox.html('總分:' + this.score);
    clearInterval(this.timer);
    this.time = 60;
    this.score = 0;
    this.level = 0;
};
//遊戲暫停處理
game.pause = function () {
    clearInterval(this.timer);
    this.switchPage(3);
};
//繼續遊戲
game.continue = function () {
    this.switchPage(2);
    this.timeCount();
};
//計時器
game.timeCount = function () {
    var self = this;
    game.timer = setInterval(function(){
        self.time--;
        self.timeBox.html(self.time);
        if ( self.time == 0 ) {
            self.over.call(self);
        }
    }, 1000)
};
//換頁
game.switchPage = function ( index ) {
    this.pages.css('display', 'none');
    this.pages.eq(index).css('display', 'block');
};

//遊戲入口,觸發載入
game.loading();

大家可以看到js程式碼,所有的變數和函式都新增到了game={}這個物件上,以防發生全域性汙染。

遊戲載入

有遊戲載入這個步驟的主要目的是在遊戲載入資源的時候讓使用者知道具體的載入過程,免得載入過慢時使用者離開頁面。

程式碼為:

...
game.imgUrls = [];
...
//載入遊戲
game.loading = function () {
    var imgCounts = this.imgUrls.length;
    if ( imgCounts == 0) {
        this.switchPage(1);
        this.initEvent();
    } else {
        var num = 0,
            self = this;
        function count () {
            num++;
            if ( num == imgCounts ) {
                self.switchPage(1);
                self.initEvent();
            }
        }
        for ( var i = 0; i < imgCounts; i++ ) {
            var img = new Image();
            img.onload = count;
            img.src = this.imgUrls[i];
        }
    }
};

這段程式碼並不難理解,game.imgUrls為存放圖片url的陣列,遊戲載入的時候通過獲取到這個陣列的長度,判斷是否進行圖片載入。

如果不需要載入就切換到開始遊戲的介面,並且新增事件處理。

其中,this.switchPage函式的程式碼為:

...
game.pages = $('.page');
...
//換頁
game.switchPage = function ( index ) {
    this.pages.css('display', 'none');
    this.pages.eq(index).css('display', 'block');
};

當載入圖片存在時,即imgUrls不為空陣列,那麼開始載入圖片

var num = 0,
    self = this;
    function count () {
        num++;
        if ( num == imgCounts ) {
            self.switchPage(1);
            self.initEvent();
        }
    }
    for ( var i = 0; i < imgCounts; i++ ) {
        var img = new Image();
        img.onload = count;
        img.src = this.imgUrls[i];
    }

程式碼中,迴圈遍歷了imgUrls,將src賦給一個img物件,然後onload(載入完成)就將計數+1,當計數和圖片數量一致時說明全部載入完成,然後就換頁和新增事件。

開始遊戲介面

這個介面主要功能是顯示提示資訊,和點選開始遊戲按鈕時開始遊戲。

這裡寫圖片描述

新增事件都放在game.initEvent函式中

...
game.startBtn = $('.start-game').eq(0);
...
game.eventType = document.ontouchstart ? 'touchstart' : 'click';
...
//初始化事件
game.initEvent = function () {
    ...
    this.startBtn.on(this.eventType, this.start.bind(this));
    ...
};

給圖中的“開始遊戲”按鈕綁定了touchstart(click)事件,處理為game.start()——開始遊戲

遊戲進行中的處理

這裡寫圖片描述

遊戲元素很少,有4個:得分、時間、暫停按鈕、裝方塊的盒子。

思路為:

當遊戲開始時,等級預設為0,等級為0的方塊為 2 x 2 放置,其他等級n x n 由 levelMap確定,當level超過陣列長度時,取7.

game.levelMap = [2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7];

然後生成對應數字的方塊html,放進裝方塊的盒子,同時給每個方塊生成顏色,其中一個不同,當點選方塊時判斷是否選到不同,選對則晉級,選錯則遊戲結束。

開始講解程式碼:

game.time = 60;     //遊戲時間
game.score = 0;     //得分
game.level = 0;     //等級
game.levelMap = [2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7]; // n x n 的方塊
game.colorDiff = [115, 100, 100, 85, 85, 85, 70, 70, 70, 70, 55, 55, 55, 55, 55, 40, 40, 40, 40, 40, 40, 25, 25, 25, 25, 25, 25, 25, 10, 10, 10, 10, 10, 10, 10, 10]; // 色差,等級越高,色差越小
game.diffIndex = 0; //不同顏色方塊的index
...
//開始遊戲(點選開始遊戲就觸發這個函式)
game.start = function () {
    this.switchPage(2);   //換頁到遊戲介面
    this.render();        //render函式處理遊戲介面渲染,主要包括生成方塊,顏色等等
    this.timeCount();     //開啟計時器
};
//遊戲介面渲染
game.render = function () {
    /**
     * num       為n * n 的方塊中的n,由等級決定,等級超過陣列最大就取最後一個
     * colorDiff 為色差,由等級決定,等級超過陣列最大就取最後一個
     */
    var num = this.levelMap[this.level] ? 
                this.levelMap[this.level] : 
                this.levelMap[this.levelMap.length - 1],
        colorDiff = this.colorDiff[this.level] ? 
                        this.colorDiff[this.level] : 
                        this.colorDiff[this.colorDiff.length - 1],
        color = [],
        lvColor = [];
    //顯示分數
    this.scoreBox.html('得分:' + this.score);
    //顯示時間
    
            
           

相關推薦

html遊戲——

前幾天一個朋友問了我要做看你有多色這樣的一個遊戲需要怎麼學,我也就自己寫了一下。 我有放在自己的個人網站上:檢視遊戲 原始碼也放在了github上:檢視原始碼 現在開始說明制過程: 專案結構 注:偷懶用了jquery,其實程式碼不多,完全可以原

遊戲2:HTML5製作網頁遊戲看看--createjs

效果: index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>看你有多色</title> &

益智遊戲能否通關?

技術 blog ima 小遊戲 .cn enter src targe arr 就是它 ↓↓↓ I am ready益智小遊戲看你能否通關?

懂Python?完這6道題差不多能算清楚了!

Python在設計上堅持了清晰劃一的風格,這使得Python成為一門易讀、易維護,並且被大量使用者所歡迎的、用途廣泛的語言。設計者開發時總的指導思想是,對於一個特定的問題,只要有一種最好的方法來解決就好了。            

android應用開發全程實錄-熟悉listview?

本文轉載自http://www.cnblogs.com/noTice520/archive/2011/12/05/2276379.html 這是一篇我看到的講解Listview比較全面的文章,所以轉了過來。文章如下: 今天給大家帶來《android應用開發全程實錄》中關於listvie

iOS 遊戲專案——話我猜升級版

級別: ★☆☆☆☆ 標籤:「iOS」「小遊戲專案」「你話我猜」 作者: MrLiuQ 審校: QiShare團隊 前言:最近公司部門在組織團建,需要準備兩個團建小遊戲, 分別是“數字速算升級版”和“你話我猜升級版”。 小編琢磨了一下,發現這個兩個小專案很適合iOS入門學習,故這篇文章誕生了。 本

新潮又酷炫,3D列印鞋離遠?

新潮、酷炫,是很多時尚一族不變的追求與信仰。身為潮流達人的你,是否注意到近來在運動圈與3D列印圈頻繁曝光的新晉主角——3D列印鞋?譬如,輕盈舒適、拒絕水分的耐克Flyprint 3D,一體成型、無縫銜接的匹克FUTURE 3.0,實現了個性化定製的阿迪達斯Futurecraft 4D,更加輕便、更強抓地

新潮又酷炫,3D打印鞋離遠?

進行 sha 自己的 帶來 一起 以及 ESS 是否 blog 新潮、酷炫,是很多時尚一族不變的追求與信仰。身為潮流達人的你,是否註意到近來在運動圈與3D打印圈頻繁曝光的新晉主角——3D打印鞋?譬如,輕盈舒適、拒絕水分的耐克Flyprint 3D,一體成型、無縫銜接的

溫柔,就強大

我一直主張要以貌取人,“貌”不是說都要有五官出色的臉,而是包括你的臉、你的身材、你的衣著、你的言行舉止,以及一切能夠表現外在上的內在。 相由心生是時光給每個人的一種名片,以貌取人就是最符合自然規律的一種社交方式,也是科學和靠譜的。 站姿可以看出才華,坐姿有你的教養,聲音流露性情,眼睛

五款朋友都在玩的微信遊戲怎麼能錯過

隨著去年跳一跳的風靡,微信小遊戲也俘獲了大部分的人,微信小程式不僅省手機記憶體空間,還簡單易上手,不費流量,可以說十分方便了。當你閒暇時間不知道幹什麼的時候,不如開啟微信如好友pk一把小遊戲。那你除了跳一跳,還知道其他什麼小遊戲嗎?今天小編就給你介紹幾款好玩的

如何入門微信遊戲開發,哪些學習資料?

開發微信小遊戲並非難事1.首先,微信小遊戲的開發方法目前微信小遊戲已釋出 17 款首發遊戲,包括六款棋牌類遊戲,以及歡樂消消消、愛消除、坦克大戰、保衛蘿蔔等休閒遊戲。可以看到微信遊戲的開發方式答主有一些COCOS的開發經驗,於是這裡我們主要探討COCOS製作小遊戲的方法2.需

Py之tkinter:python最簡單的猜字遊戲進入python的GUI世界

from tkinter import *  import tkinter.simpledialog as dl  import tkinter.messagebox as mb    root = Tk()   w = Label(root, text = "Guess N

VB6升級到VB2010之五: 從Unload 升級成Me.CloseVB2010類~

新版本的Visual Basic 2010,你會發現原來用於關閉視窗的Unload Me無法使用了... 沒錯,Unload Me 現在已經升級為Me.Close() 看到了沒有,Visual Basic 2010類吧。 其實,你再往下看... 你會發現Visua

比“虛幻4”還牛逼的遊戲引擎 到底神奇?

提到最逼真的遊戲引擎,你第一反應是什麼?虛幻4?那你就out了。獨立開發團隊Atomontage從05年就開始研究一種超真實體素3D引擎,他們的目標就是讓這個引擎成為實時3D遊戲的終極解決方案。日前,Atomontag

瞭解hybris ?

       HR:請問你對hybris有多少了解?   程式設計師:不太瞭解,但是你們不是要找java開發麼,只要它是java寫的就沒什麼差別吧?業務我都可以學的。   HR:……   程式設計師會如願走入奇妙的hybris世界嗎?   hybris是什麼?如果

前端面試 js 瞭解call,apply,bind?

函式原型鏈中的 apply,call 和 bind 方法是 JavaScript 中相當重要的概念,與 this 關鍵字密切相關,相當一部分人對它們的理解還是比較淺顯,所謂js基礎紮實,繞不開這些基礎常用的API,這次讓我們來徹底掌握它們吧! 目錄 call,apply,bind的基本介紹 call/a

通過「解救人質」遊戲學會碰撞檢測

遊戲開發中,碰撞檢測無處不在,今天就通過一個簡單的小遊戲教你學會如何在 Cocos Creator 中進行碰撞檢測。配合官方文件學習效果更加(官方文件傳送門:https://docs.cocos.com/creator/manual/zh/physics/collision/),關注公眾號「遊戲開發小白變怪獸

Python獲取全網電影,深夜電影難道不是學習的初衷嗎?

Python Pythonweb 爬蟲 程序員 職業 你以為這是×××?NO,這只是簡單的Python爬蟲。如今各種各樣的影視Vip收費出現在我們的視野中,對於我們來說也許是一部期待已久的電影電視,可是對於網站,App開發人員來說只是一組數據,為了一組數據去付費、等廣告時間,我覺得還是有

程式設計師薪資調查,薪資到底高,資料就知道!

 全球約有1850萬程式設計師,中國佔10%,隨著“網際網路+”、“雲端計算”以及“智慧硬體”等領域發展迅速,程式設計師再次迎來第二春! 如果有想學習java的程式設計師,可來我們的java學習扣qun:72340,3928免費送java的視訊教程噢!小編是一名5年java開發經驗的全

Java長見到的面試題,能答出幾題,就知道自己菜了

作者:Java3y 前言 只有光頭才能變強 Redis目前還在看,今天來分享一下我在秋招看過(遇到)的一些面試題(相對比較常見的) 0、final關鍵字 簡要說一下final關鍵字,final可以用來修飾什麼? 這題我是在真實的面試中遇到的,當時答得不太好,現在來整理一