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!
Aucun commentaire:
Enregistrer un commentaire