0
2

More than 3 years have passed since last update.

【JavaScript】乱数の作り方

Last updated at Posted at 2020-05-04

【JavaScript】乱数の作り方

0~1未満の値を生成する


    Math.random() * 1
    つまり
    Math.random()

0~3未満の値を生成する


    Math.random() * 3

小数点以下の値を含む

0~3未満の整数(0,1,2)を生成する


    Math.floor(Math.random() * 3)

切り捨てにMath.floorを使い小数点以下の値を含まない

0~4未満の整数(0,1,2,3)を生成する


    Math.floor(Math.random() * (1 + 3))
    つまり
    Math.floor(Math.random() * (4))

0~max未満の整数(0,...,max)を生成する


    Math.floor(Math.random() * (1 + max))

min~maxの整数を生成する

    Math.floor(Math.random() * (1 + max - min)) + min

応用:6面ダイス

    Math.floor(Math.random() * 6) + 1;

応用:6面ダイスを2個振る

    (Math.floor(Math.random() * 6) + 1) + (Math.floor(Math.random() * 6) + 1);

応用:12面ダイス

    Math.floor(Math.random() * 12) + 2;

補足

上のような例示はRPGツクールMVのダメージ計算式に入れることもできます。

またRPGツクールMV側でもMath.floor(Math.random*引数)をまとめたMath.randomInt関数が用意されています。


    Math.randomInt = function(max) {
        return Math.floor(max * Math.random());
    };

ダメージ計算式にMath.randomInt(6)+1と記述し、分散度を0%、攻撃タイプを必中にすることで1~6を出すことができます。

・分散度……ダメージの揺らぎになるRPGツクール側の要素。既定では20%。
・攻撃タイプ……物理攻撃、魔法攻撃、必中から成るRPGツクール側の要素。攻撃ミスの原因になる。既定では物理攻撃。

謝辞
@kuroudo119
@trinitroterunon

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2