-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
110 lines (88 loc) · 2.58 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
let valueId, indexEliminar;
let arrHum = [], arrMac = [], validar = [];
let player, coincidentes = 0;
arrOriginal = [1,2,3,4,5,6,7,8,9];
const possibleCombinations = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[3, 5, 7]
];
let clickScreen = document.querySelectorAll('.cell');
function listening() {
for(let i = 0; i<clickScreen.length; i++){
clickScreen[i].addEventListener("click",function () {
valueId = this.id;
valueId = parseInt(valueId);
player = 'el humano';
if (arrOriginal.includes(valueId)) {
humanPlayer();
}else if(arrOriginal.length>0){
alert('Ingrese por favor un valor valido');
}else{
alert('El juego a terminado');
}
});
}
}
function humanPlayer() {
document.getElementById(`${valueId}`).innerHTML = "X";
arrHum.push(valueId);
arrHum.sort();
indexEliminar = arrOriginal.indexOf(valueId)
arrOriginal.splice(indexEliminar, 1);
console.log(arrHum);
console.log(arrOriginal);
if(arrHum.length>2){
validar = arrHum;
validate();
}
if (arrOriginal.length>0) {
setTimeout(() => {
machinePlayer();
}, 250);
}
}
function machinePlayer() {
valueId = arrOriginal[Math.floor(Math.random() * arrOriginal.length)];
document.getElementById(`${valueId}`).innerHTML = "O";
arrMac.push(valueId);
arrMac.sort();
indexEliminar = arrOriginal.indexOf(valueId)
arrOriginal.splice(indexEliminar, 1);
console.log(arrMac);
console.log(arrOriginal);
if(arrMac.length>2){
validar = arrMac;
player = 'la maquina';
validate();
}
}
function validate() {
for(let j = 0; j<possibleCombinations.length; j++){
coincidentes = 0;
for(let k = 0; k<validar.length;k++){
if (validar[k] == possibleCombinations[j][0] || validar[k] == possibleCombinations[j][1] || validar[k] == possibleCombinations[j][2]) {
coincidentes++;
if (coincidentes>2) {
setTimeout(() => {
alert(`Gano ${player}`);
}, 350);
arrOriginal = [];
reset();
}
if (coincidentes<2 && (arrOriginal.length<1)) {
reset();
}
}
}
}
}
function reset() {
console.log('juego terminado');
}
listening();