Skip to content

Instantly share code, notes, and snippets.

@Jorger
Created September 15, 2019 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jorger/2368f2e1dcd40b5733e0e9f5f6df9236 to your computer and use it in GitHub Desktop.
Save Jorger/2368f2e1dcd40b5733e0e9f5f6df9236 to your computer and use it in GitHub Desktop.
/**
* Inferir un ataque teniendo posiciones conocidas.
* @param {*} board
*/
const inferAttack = board => {
const boardSize = DIMENSION_BOARD - 1;
let newRow = 0;
let newCol = 0;
let inferredAttack = false;
let counterLoop = 0;
do {
// :( A veces se queda en un ciclo aleatorio :(
if (counterLoop >= 100) {
break;
}
const listRandom =
shipsFoundIA[2] ||
[1, 2, 3, 4].filter(v => {
if (shipsFoundIA[3]) {
for (let i = 0; i < shipsFoundIA[3].length; i++) {
if (v === shipsFoundIA[3][i]) {
return false;
}
}
}
return true;
});
const randomDirection = randomNumber(0, listRandom.length - 1);
const directionCol =
listRandom[randomDirection] === 1
? -1
: listRandom[randomDirection] === 3
? 1
: 0;
const directionRow =
listRandom[randomDirection] === 2
? -1
: listRandom[randomDirection] === 4
? 1
: 0;
newRow = shipsFoundIA[0] + directionRow;
newCol = shipsFoundIA[1] + directionCol;
// Primero saber que no se salga del canvas
if (
newRow >= 0 &&
newRow <= boardSize &&
newCol >= 0 &&
newCol <= boardSize
) {
if (board[newRow][newCol] === 2) {
// En esa posición hay un elemento del barco ya dañado
shipsFoundIA[0] = newRow;
shipsFoundIA[1] = newCol;
} else {
if (board[newRow][newCol] === 0 || board[newRow][newCol] === 1) {
shipsFoundIA[2] = [listRandom[randomDirection]];
inferredAttack = true;
break;
}
}
}
if (!inferredAttack) {
if (listRandom.length === 1) {
if (!shipsFoundIA[3]) {
shipsFoundIA[3] = [listRandom[randomDirection]];
} else {
shipsFoundIA[3].push(listRandom[randomDirection]);
}
shipsFoundIA[2] = undefined;
}
}
counterLoop++;
} while (1);
return [newRow, newCol, inferredAttack];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment