Skip to content

Commit 4794960

Browse files
committed
step 10
1 parent 8bf8ad6 commit 4794960

File tree

1 file changed

+46
-9
lines changed

1 file changed

+46
-9
lines changed

src/services/ia-helper.js

Lines changed: 46 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,52 @@
1-
import { ITERATION_LIMIT, getCell, BOARD_SIZE } from "./board-helper";
1+
import { getNeighbors, getCellIndexes } from "./board-helper";
22

3-
export function findTargetCell(boardCells) {
4-
let cell = "";
3+
function getCommonDirection(cell1, cell2) {
4+
const { row: row1 } = getCellIndexes(cell1);
5+
const { row: row2 } = getCellIndexes(cell2);
6+
if (row1 === row2) {
7+
return ["left", "right"];
8+
}
9+
return ["up", "down"];
10+
}
511

6-
for (let i = 0; i < ITERATION_LIMIT; i++) {
7-
const row = Math.floor(Math.random() * BOARD_SIZE) + 1;
8-
const column = Math.floor(Math.random() * BOARD_SIZE) + 1;
9-
cell = getCell(row, column);
12+
function findUnexploredNeighbors(cell, directions, boardCells) {
13+
const { row, column } = getCellIndexes(cell);
14+
const neighbors = Object.keys(getNeighbors(row, column))
15+
.filter((key) => directions.includes(key))
16+
.map((key) => getNeighbors(row, column)[key]);
17+
const unexploredCells = neighbors.filter((cellAddress) =>
18+
["empty", "ship"].includes(boardCells[cellAddress].status),
19+
);
20+
return unexploredCells;
21+
}
1022

11-
if (["empty", "ship"].includes(boardCells[cell].status)) {
12-
return cell;
23+
function nextTarget(candidates, boardCells) {
24+
let filteredDirections = ["up", "down", "left", "right"];
25+
if (candidates.length > 1) {
26+
filteredDirections = getCommonDirection(candidates[0], candidates[1]);
27+
}
28+
for (let cell in candidates) {
29+
const unexploredNeighbors = findUnexploredNeighbors(
30+
candidates[cell],
31+
filteredDirections,
32+
boardCells,
33+
);
34+
if (unexploredNeighbors.length !== 0) {
35+
return unexploredNeighbors[0];
1336
}
1437
}
1538
}
39+
40+
export function findTargetCell(boardCells) {
41+
const candidates = Object.keys(boardCells).filter(
42+
(keyCell) => boardCells[keyCell].status === "hit",
43+
);
44+
if (candidates.length === 0) {
45+
const missed = Object.keys(boardCells).filter(
46+
(keyCell) =>
47+
!["hit", "sunk", "missed"].includes(boardCells[keyCell].status),
48+
);
49+
return missed[Math.floor(Math.random() * missed.length)];
50+
}
51+
return nextTarget(candidates, boardCells);
52+
}

0 commit comments

Comments
 (0)