LoginSignup
0
1

More than 3 years have passed since last update.

JavaScriptを学ぶ④(ランダム宝探しゲームの作成♪)

Last updated at Posted at 2019-08-13

<script>
  'use strict';

  const num= 5;
  const winner = Math.floor(Math.random() * num);

for (let i = 0; i < num; i++){
  const rizard = document.createElement('div');
  rizard.classList.add('box');
  if(i === winner){
    rizard.dataset.result = 'win';
  }else{
    rizard.dataset.result = 'lose';
  }

  rizard.addEventListener('click',function(){
    if(rizard.dataset.result === 'win'){
      rizard.textContent = 'Win!';
      rizard.classList.add('win');
    }else{
      rizard.textContent = 'Lose!';
      rizard.classList.add('lose');
    }
  });
  document.body.appendChild(rizard);
}
</script>
body{
  display:flex;
  flex-wrap:wrap;
}
.box{
  width:100px;
  height:100px;
  background:skyblue;
  cursor:pointer;
  transition:0.8s;
  margin: 0 8px 8px 0;
  text-align:center;
  line-height: 100px;
}
.win{
  background:pink;
  border-radius:50%;
  transform:rotate(360deg);
}
.lose{
  transform:scale(0.9);
}

なかなかプログラムがややこしくなりましたが、
1つずつ確実に理解していきましょう(^^)

const num= 5;
const winner = Math.floor(Math.random() * num);
の部分から見ていきます♪

Math.floor(Math.random() * num);

Math.floor(Math.random() * num);
の部分は、検索すればすごく良い記事を見つけました♪:relaxed:
いまさらですが、Math.random()

館単に書くと、Math.random()は0~1未満の小数をランダムで作り出します。
`Math.floorで小数を切り捨てるという意味になります:v:

●Math.floor(数字)
小数以下を切り捨てして整数にします 以外にも、
●Math.ceil(数字)
数字を切り上げして整数にします
●Math.round(数字)
数字を四捨五入して整数にします

よって、
const winner = Math.floor(Math.random() * num);
は、0~5未満のランダムの数字を小数点切り捨てで作成し、
その数字を、winnerという定数にするよ~という意味になるということですね(^^)

次は、、、
for (let i = 0; i < num; i++){
const rizard = document.createElement('div');
rizard.classList.add('box');
if(i === winner){
rizard.dataset.result = 'win';
}else{
rizard.dataset.result = 'lose';
}

dataset.result

ここの部分は、dataset.resultを調べてのですが、イマイチ分からず……
悲しいですが、気にしすぎずに次にいきたいと思います:cry:

0
1
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
1