2015/06/09

模擬轉盤遊戲

公司有一個 case 要在網頁模仿轉盤亮燈的功能,陽春的寫法如下。

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Game</title>
    <link rel="stylesheet" href="game.css">
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="game.js"></script>
</head>
<body>
<button type="button" id="start">start</button>
<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>
</body>
</html>

CSS

ul {
    margin: 0;
    padding: 0;
    list-style: none;
}
li {
    width: 100px;
    height: 100px;
    border: 2px solid red;
    float: left;
    margin: 2px;
}
.on {
    border: 2px solid pink;
}

JS

$(function() {
    var start = $('#start');
    var lis = $('li');

    start.on('click', function() {
        var rounds = 40 + Math.floor((Math.random() * lis.size()));

        $(this).prop('disabled', true);
        spin(lis.filter(':first'), rounds);
    });

    function spin(li, rounds) {
        var duration = rounds < 5 ? 1000 : 70;

        lis.clearQueue();
        li.delay(duration).queue(function() {
            var next = $(this).next('li');

            lis.removeClass('on');

            if (next.size() === 0) {
                next = lis.filter(':first');
            }

            li.addClass('on');

            if (rounds - 1 >= 0) {
                spin(next, rounds -1);
            } else {
                start.prop('disabled', false);
            }
        });
    }
});

Sample Code

沒有留言: