2

For a computer science class, I’m making a simple 4 screen game (home, game, win, lose screen). I went with “whack a mole” because it seemed pretty simple but I’ve been stuck for the past day. I have 6 holes and a mole and I would for the mole to move RANDOMLY to one of the other holes. I have no idea how to make it possible. Is it possible to make a list with 6 positions (6holes) and then make the program choose one of the positions randomly for the mole to move to??

  • 4
    If you add your positions to an `Array`, you could then use this answer to pick one at random: [Getting a random value from a JavaScript array](https://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array) – Tyler Roper Dec 18 '18 at 21:11

1 Answers1

2

Show a random mole every 500 ms.

const moles = ['_','_','_','_','_','_'];

let position = 0;

function showMole() {
  moles[position] = '_';
  position = Math.floor(Math.random() * moles.length);
  moles[position] = 'O';
  document.getElementById('output').innerText = moles.join('');
  setTimeout(showMole, 500);
}

showMole();
<div id="output"></div>
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60