Summary. ダメージ計算スクリプトの実装のうち、履歴機能についてです。

やること

ダメージ計算そのものとは直接関係ないですが、履歴機能があると便利なのでそれを実装します。

Function summary
save_history(maxsize) 現在のフォームの内容を履歴に残す。
履歴総数が maxsize を超えてしまう場合は、古い履歴を1つ削除する
make_history() 現在のフォームの内容から履歴を作る
load_history() historyフォームで指定された番号の履歴を読み込む

すべての履歴は History という配列に格納されます。HTML側の実行履歴欄に表示される数字は、History に格納されている各履歴を上から順に表示したものです(計算結果だけ)。

履歴の中身

promptフォームが持つすべてのコントロールの現在値を取得して配列にしたものです。

たとえば、AAの場合は次のようにして作られる配列です:
make_history = function(){
  return new Array(
    document.prompt.target.selectedIndex,
    document.prompt.state.selectedIndex,
    document.prompt.hisukoha.checked,
    document.prompt.floatflag.checked,
    document.prompt.recipe.value,
    document.prompt.result.value
  );
} 
逆に、履歴を再現するときは上と正反対のことをすればよいです:
load_history = function(){
  var i = document.history.histlist.selectedIndex;
  var hist = History[i];
  document.prompt.target.selectedIndex = hist[0];
  document.prompt.state.selectedIndex = hist[1];
  document.prompt.hisukoha.checked = hist[2];
  document.prompt.floatflag.checked = hist[3];
  document.prompt.recipe.value = hist[4];
  document.prompt.result.value = hist[5];
  document.history.histlist.selectedIndex = -1;
} 
他のバージョンだとフォームの内容物が少し違いますが、やることは大体同じです。

save_history 関数

非常に原始的な処理ですが、ここにフォームの更新が絡むので少し注意が必要です。
save_history = function(maxsize){
  var opts = document.history.histlist.options;
  var hist = make_history();
  var i = History.length;
 
  if(i >= maxsize){
    opts[0] = null;
    for(i = 0; i < maxsize - 1; i++){
      History[i] = History[i + 1];
    }
  }
 
  History[i] = hist;
  opts[i] = new Option(hist[5], hist[5]);
} 
このコードでは opts に対する処理が重要です。JavaScriptからセレクトボックスを変更するには、その options フィールドにアクセスします。

6行目のように null を代入すると、その要素が削除されます。





最終更新:2012年12月10日 09:39