js-battleship/src/js/Player.js
2023-08-02 18:18:27 -07:00

40 lines
1.1 KiB
JavaScript

import { Gameboard } from "./Gameboard.js";
// Players can take turns playing the game by attacking the enemy Gameboard
export const Player = (name = "AI") => {
// initializes Player's gameboard
const board = Gameboard();
// for AI only, initialize moves array
const moves = [];
// move function takes an enemy and coordinates as args
const move = (enemy, y = null, x = null) => {
// if Player is AI, do a random move
if (name === "AI") {
(function roll() {
y = Math.round(Math.random() * 9);
x = Math.round(Math.random() * 9);
})();
function unique() {
let bool = true;
for (let i = 0; i < moves.length; i++) {
if (moves[i][0] === y && moves[i][1] === x) {
bool = false;
}
}
return bool;
}
while (!unique) roll();
// push random move to moves array and FIRE!
moves.push(new Array(y, x));
enemy.board.receiveAttack(y, x);
return;
}
// otherwise get coords from user - these will be passed in from UI
enemy.board.receiveAttack(y, x);
};
return {
board,
move,
name,
};
};