jewel Class

ブラウザの更新ボタンをクリックする度に個数が変わります。


【Source Code】
<script type="text/javascript">
function jewel_class(num, max)
{   this.num = num;     //現在の個数
    this.max = max;     //取り除く最大数

    this.disp = function()
    {
        for(i=0; i<this.num; i++)
        {   document.write("<img src='img/jewel.gif'>");
            if (i%10==9)    document.write("<br>");
        }
        document.write("<br>");
    }

    this.table = function()
    {
        document.write('<br><table border="1">');
        document.write('<tr><td>現在の個数</td><td>');
        document.write(this.num, '</td></tr>');
        document.write('<tr><td>取り除く最大数</td><td>');
        document.write(this.max, '</td></tr>');
        document.write('</table>');
    }
}
</script>
</head>

<body>
<h1>jewel Class</h1>
<h3>ブラウザの更新ボタンをクリックする度に個数が変わります。</h3>

<script type="text/javascript">
  n= Math.floor(Math.random() * 10)+11;
  m= Math.floor(Math.random() * 4)+2;
  var cls = new jewel_class(n, m);
  cls.disp();
  cls.table();
</script>

石を表示する jewel_class Class を <head> の中で定義します。
constructor で石の個数と一度に取り除くことが出来る最大値を受け取って内部変数に保存します。
<script type="text/javascript">
function jewel_class(num, max)
{   this.num = num;     //現在の個数
    this.max = max;     //取り除く最大数

num 個の石の画像を描画する関数です。
一行に10個ずつ並べて描画します。
    this.disp = function()
    {   for(i=0; i<this.num; i++)
        {   document.write("<img src='img/jewel.gif'>");
            if (i%10==9)    document.write("<br>");
        }
        document.write("<br>");
    }

現在 Class で保持している領域の値を table に表示する関数です。
    this.table = function()
    {   document.write('<br><table border="1">');
        document.write('<tr><td>現在の個数</td><td>');
        document.write(this.num, '</td></tr>');
        document.write('<tr><td>取り除く最大数</td><td>');
        document.write(this.max, '</td></tr>');
        document.write('</table>');
    }

jewel_class の呼び出し方です。
乱数で石の個数(n)と一度に取り除くことが出来る最大値(m)を設定します。
Math.random() は 0.0 以上 1.0 未満の乱数を発生させる関数です。
var cls = new jewel_class(n, m); で Class を生成します。
cls.disp(); で Class の disp() 関数を呼び出します。
cls.table(); で Class の table() 関数を呼び出します。
実際に石を取り除くプログラムは 石取ゲーム-2 を参照して下さい
<script type="text/javascript">
  n= Math.floor(Math.random() * 10)+11;
  m= Math.floor(Math.random() * 4)+2;
  var cls = new jewel_class(n, m);
  cls.disp();
  cls.table();

前田稔の超初心者のプログラム入門
超初心者のプログラム入門(JavaScript)