ミッション一覧に戻る
的を当てろ

的を当てろ

03/26 13:45
ミッション内容

「的を当てろ」

ミッション:画面のランダムな場所に現れる的をクリックして、点数を稼ごう!

コードを写そう

HTMLタブに下のコードを貼り付けてください。

html
<p id="score">0点</p>
<div id="target">🎯</div>

CSSタブに下のコードを貼り付けてください。

css
body {
  margin: 0;
  min-height: 100vh;
  overflow: hidden;
}

#score {
  font-size: 1.5rem;
  padding: 10px;
}

#target {
  position: fixed;
  font-size: 60px;
  cursor: pointer;
  user-select: none;
}

JSタブに下のコードを貼り付けてください。

js
const target = document.querySelector('#target');
const score  = document.querySelector('#score');
let count = 0;

target.style.left = Math.random() * (window.innerWidth  - 80) + 'px';
target.style.top  = Math.random() * (window.innerHeight - 80) + 'px';

target.addEventListener('click', function() {
  count = count + 1;
  score.textContent = count + '点';

  target.style.left = Math.random() * (window.innerWidth  - 80) + 'px';
  target.style.top  = Math.random() * (window.innerHeight - 80) + 'px';
});

的をクリックするたびにランダムな場所に移動し、点数が増えることを確認してください。

コードを読み解こう

position: fixed でランダムな座標に置く

js
target.style.left = Math.random() * (window.innerWidth  - 80) + 'px';
target.style.top  = Math.random() * (window.innerHeight - 80) + 'px';

「精霊を呼び出す場所」で event.clientX / Y を使ってクリックした座標に要素を置きました。今回は Math.random() を使ってランダムな座標を自分で計算しています。

window.innerWidth は画面の幅、window.innerHeight は画面の高さをピクセルで返します。- 80 しているのは的(60px)が画面からはみ出さないようにするためです。

的をクリックしたあと座標を書き直す

js
target.addEventListener('click', function() {
  // 点数を増やす
  count = count + 1;
  score.textContent = count + '点';

  // 新しい場所に移動する
  target.style.left = Math.random() * (window.innerWidth  - 80) + 'px';
  target.style.top  = Math.random() * (window.innerHeight - 80) + 'px';
});

クリックされたあと style.leftstyle.top を新しいランダムな値で上書きすることで、的が別の場所に「移動」します。

同じコードが2箇所に出てくるのは(最初の配置とクリック後の移動)、「繰り返し」という共通のパターンになっています。

改造しよう

ミッション:的のサイズを変えよう

css
#target {
  font-size: 60px;  ← 大きくすると当てやすく、小さくすると難しくなる
}

サイズを変えたとき、JSの - 80 の値もサイズに合わせて調整してみましょう。


自己チェック

  • [ ] 的をクリックするとランダムな場所に移動する
  • [ ] クリックするたびに点数が増える
  • [ ] Math.random()position: fixed を使っている