先上

codepen

 

https://codepen.io/frenkieli/pen/agmKvQ

 

首先建立基本框架,可接複製CSS和HTML就可以囉

 

然後是建立重點的javascript程式碼

 

 

=================製作隨機骰數字的功能============

function rand(min,max){
    var num;
    var mix=max-min;
    num=Math.floor(Math.random()*(mix+1))+min;
    return num;
}        

====================宣告要用到的所有公用數字=================
        var tds = new Array;
        var timeclock;
        var num = 0;
        var maxNum = rand(48, 80);
        var count = 0;
        var start = document.getElementById('start');
        var timeGo = 500;

============利用迴圈將td中的id串成陣列=================
        for (let i = 0; i < 16; i++) {
            tds[i] = document.getElementById(`td${i}`);
        }

===============重置遊戲開始遊戲和按鈕防呆功能製作=============
        function gogoLuck() {
            console.log(num);
            tds[num].innerHTML = num + 1;
            tds[num].style.backgroundColor = "#fff";
            timeGo = 500;
            count = 0;
            num = 0;
            maxNum = rand(48, 80);
            console.log(maxNum);
            init();
            start.removeEventListener('click', gogoLuck, false);
        }

        console.log(maxNum);

 

================主要判斷區和遊戲功能區=======================
        function gogoBox(e) {
            if (count < 9) {
                timeGo = timeGo - 50;
                //預計跑三次
            } else if (maxNum < 10 && timeGo < 500) {
                timeGo = timeGo + 50;
            }

            if (num == 16) {
                num = 0;
            }
            tds[num].style.backgroundColor = "#fa0";
            console.log(num);
            if (num == 0) {
                tds[15].style.backgroundColor = "#fff";
            } else {
                tds[num - 1].style.backgroundColor = "#fff";
            }

            if (maxNum == 0) {
                tds[num].innerHTML = rand(50, 99) * 100;
                clearInterval(timeclock);
                start.addEventListener('click', gogoLuck, false);
                return;
            }
            maxNum -= 1;
            num += 1;
            count += 1;
            init();
        }

============利用一次性計時器建立加減速功能===========
        function init() {
            console.log('init');
            timeclock = setTimeout(gogoBox, timeGo);
        }

 

============讀取完建立DOM之後再載入函式============

        window.addEventListener('load', init, false);

 

簡單的小遊戲但是可以測試出很多東西喔!

自己建立看看吧!(看的出來我打得很生疏吧= =)

創作者介紹
創作者 驢子的生活日記 的頭像
驢子

驢子的生活日記

驢子 發表在 痞客邦 留言(0) 人氣( 513 )