iT邦幫忙

0

一起來 side project 吧(3/40) - 午餐小瑪莉 - 先看看別人怎麼做的

olen 2020-04-12 23:57:092097 瀏覽
  • 分享至 

  • xImage
  •  

創作之前,你得先會模仿

在寫這篇文章之前,我對這主題要怎麼實現其實也是 have no idea..

好在生在這個網路資訊發達的年代, 善用google, 可以解決你人生很多問題

所以我們這周就來看一下其他大大的範例
小瑪莉模擬 by MrJohnson

Imgur
小巧且完整 ~

好的,那我們來看一下code, 那麼從哪裡開始看呢?
先大致上瀏覽一下程式, 我們可以看到

var no = 0;
var stopPlay = 0;
var runTimes = 0;
var sec = 50;
init();
function play() {
    ...
}
function init() {
    ...
}
$("button").click(function() {
    ...
});

$(".popup-close").click(function() {
    ...
});

hmm... 四個變數no, stopPlay, runTimes, sec, 看不太懂...

一切操作的起始就在"立即抽獎"button的點擊事件開始, 所以我們首先看到buuton onClick function的部分

$("button").click(function() {
  if (runTimes > 0) return;
  stopPlay = Math.floor(Math.random() * (20 - 0) + 20);
  $(this).attr("disabled", true);
  play();
});

這邊可以看到作者將 stopPlay 指定了一個亂數, 接著執行 play函式
接著我們看一下play裡面在幹嘛

function play() {
  no++;
  runTimes++;
  if (no >= 11) {
    no = 1;
  }
  if (runTimes > stopPlay) {
    $(".light").css("animation-duration", "2s");
    var href = $("#letmeopen");
    $(href).fadeIn(250);
    $("#winPrizes").text($(".active").text());
    $(href).children$("popup-box").removeClass("transform-out").addClass("transform-in");
    e.preventDefault();
  } else if (runTimes + 10 > stopPlay) {
    $(".no" + no)
      .addClass("active")
      .siblings()
      .removeClass("active");
    setTimeout(play, (sec = sec * 1.4));
  } else {
    $(".no" + no)
      .addClass("active")
      .siblings()
      .removeClass("active");
    setTimeout(play, sec);
    $(".light").css("animation-duration", ".3s");
  }
}

我們先忽略程式中裡面關於DOM的操作, 所以整體看起來是這樣的

function play() {
  no++;
  runTimes++;
  if (no >= 11) {
    no = 1;
  }
  if (runTimes > stopPlay) {
    // dosomething
  } else if (runTimes + 10 > stopPlay) {
    // dosomething
    setTimeout(play, (sec = sec * 1.4));
  } else {
    // dosomething
    setTimeout(play, sec);
  }
}
  • 這樣看起來就清楚多了, 在這裡面由於變數stopPlay已經被指定了一個亂數, 在runTime大於stopPlay之前, 它會重複執行play函式本身, 間隔為sec
  • 當runTime 與 stopPlay 間隔10以內時, 間隔每次*1.4

那no是幹嘛用的呢, 我們看一下else裡面其他部分

$(".no" + no)
  .addClass("active")
  .siblings()
  .removeClass("active");

這邊做了一些DOM的操作, 再參照HTML的部分, 我們可以知道no 就是對應到HTML的獎項DOM, 至此我們可以歸納出整段程式的運作邏輯

  • 先骰個骰子 (骰之前重置一下參數)
  • stopPlay:這次要前進幾步
  • runTime:現在走到第幾步
  • no:當前的燈號是停在哪一格上面 (如果no>=11也就是超過總格數了, 那就重置為1)
  • 如果還沒走到指定的步數就在走一步 (如果再十步內就要走到了,那就愈走愈慢)
  • 配合目前走道的格數no去做DOM的效果操作, 如果走完了就popup出中獎詳細資訊

到這邊我們就理解了一個簡易的小瑪莉遊戲的程式邏輯及操作方式, 咱下周見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言