|
1 | | -import { ITERATION_LIMIT, getCell, BOARD_SIZE } from "./board-helper"; |
| 1 | +import { getNeighbors, getCellIndexes } from "./board-helper"; |
2 | 2 |
|
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 | +} |
5 | 11 |
|
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 | +} |
10 | 22 |
|
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]; |
13 | 36 | } |
14 | 37 | } |
15 | 38 | } |
| 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