0
votes

I'm building a small tic tac toe game.

When it is the computer turn to play, I make him pick a random number to pick an element from an array.

My problem is that the random number will be 3 for example, but the element picked from the array won't be arr[3], but arr[4].

it is a problem because if the number picked is the end of the array, it will return undefined.

here is the javascript code:

var grid = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9'];
var choice = 9;

function myFunction(clicked_id){
  $('#' + clicked_id).html('X');
  grid.splice(grid.indexOf(clicked_id), 1);
  choice -= 1;
    setTimeout(computer, 1000);
  player.push(clicked_id);
  findElement(player);
  console.log(player);
  console.log(grid);
  console.log(grid.length)

}

function computer(){
  var ran = Math.floor(Math.random() * choice);
  var res = grid[ran - 1];
    $('#' + res).html('O');
    grid.splice(grid.indexOf(res), 1);
  cpu.push(grid[ran]);
  findElement(cpu);
  choice -= 1;
  console.log(ran);
  console.log(cpu);
} 

Here is what will be logged in the console log: ["item1"] -> What I clicked on

["item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9"] -> new modified array after using splice.

8 -> new array length

5 - random number picked by computer

["item8"] -> element picked by the computer in the array (arr[6])

'item6' is the box checked on the tic tac toe game.

Here is a link to my codepen to see the code in action.

https://codepen.io/nico3d911/pen/odvmPR?editors=0001

Thanks for your help!

2
what is choice -+ 1; supposed to do?dave
probably a typo, I suppose it was -=Calvin Nunes
Yes sorry it was a typo. Fixing it didn't fix my problem still :DNicolas Hochard

2 Answers

1
votes

Note that JS is using zero-based indexing - therefore item1 has index 0, item2 has index 1 etc. up to item9 with index 8.

Math.random() returns a number between 0 and 1 inclusive, which means that Math.random() * 9 can return 9 which is out of bounds - the maximum index is 8 for an array of length 9.

Changing the upper bound should fix your problem:

var ran = Math.floor(Math.random() * (choice - 1))

A small nitpick: grid.indexOf(res) is always equal to ran, you can just use grid.splice(ran, 1);

0
votes

My issue was coming from the fact that I was using splice before pushing the array element into its new array.

Here is the correct javascript code:

function computer(){
  var ran = Math.floor(Math.random() * choice);
  var res = grid[ran];
  $('#' + res).html('O');
  cpu.push(grid[ran]); // this line needs to be before having the element removed.
  grid.splice(grid.indexOf(res), 1);
  findElement(cpu);
  choice -= 1;
  console.log(ran);
  console.log(cpu);
}

The console log are just here to help me fixed the bug.

Thanks for your help!