0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScriptでおみくじゲームを作る流れ

Last updated at Posted at 2021-03-25

「大吉です」とブラウザに表示

index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>おみくじゲーム</title>
</head>
<body>
  大吉です。
</body>
</html>

JavaScriptで「大吉です!」とブラウザに表示

index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>おみくじゲーム</title>
</head>
<body>
  <script>
    document.write('大吉です!')
  </script>
</body>
</html>

関数を使って「大吉です!!」とブラウザに表示

index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>おみくじゲーム</title>
</head>
<body>
  <script>
    function omikuji() {
      document.write('大吉です!!')
    }
    omikuji()
  </script>
</body>
</html>

1/3の確率で「大吉です♪」とブラウザに表示

その他は、吉、小吉が出てくる。(仮)

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>おみくじゲーム</title>
</head>
<body>
  <script>
    function omikuji() {
      const fortune = Math.floor(Math.random()*3) // 0~2の間でランダムで数字が変化する
      if (fortune == 2) {
        document.write('大吉です♪')
      } else if (fortune == 1) {
        document.write('吉です')
      } else {
        document.write('小吉です')
      }
    }
    omikuji()
  </script>
</body>
</html>

Math.random は0以上1未満の数字(小数点以下含む)が取得できます。これに3をかけると、0以上3未満の数字になります。それをさらに Math.floor で処理すると、小数点以下が削られて、0, 1, 2 のいずれかの整数になります。

文字の大きさとか色とかを変えたりしてみる

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>おみくじゲーム</title>
  <style>
    h1 { color: red; font-size: 200px;}
    h2 { color: green; font-size: 100px;}
    h3 { color: blue; }
  </style>
</head>
<body>
  <script>
    function omikuji() {
      const fortune = Math.floor(Math.random()*3)
      if (fortune == 2) {
        document.write('<h1>大吉です♪</h1>')
      } else if (fortune == 1) {
        document.write('<h2>吉です</h2>')
      } else if (fortune == 0){
        document.write('<h3>小吉です</h3>')
      }
    }
    omikuji()
  </script>
</body>
</html>
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?