Battleship (#16)

* project: testing

* feat: updated testing configs

* feat: ship class and test

* feat: more testing

* feat: gameboard logic/tests complete

* feat: add player methods

* feat: add main app

* sync: pushing latest code to repo

* feat: add some basic styling and stuff

* feat: added UI logic

* feat: basic game is finished

* feat: add adjacent rules

* feat: basic game complete
This commit is contained in:
Smigz 2024-04-02 16:45:56 -04:00 committed by GitHub
parent d899a773bd
commit 099e6b13e7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
23 changed files with 10431 additions and 9218 deletions

43
battleship/src/app.js Normal file
View file

@ -0,0 +1,43 @@
export default class Game {
constructor(players) {
this.player1 = players.player1;
this.player2 = players.player2;
// this.main();
}
main() {
// TODO take turns picking points to shoot a ship
let count = 0;
// Main Game Loop
while (count < 100) {
this.handleUserMove();
this.handleCPUMove();
// console.log(
// this.player1.gameboard.scoreboard,
// this.player1.gameboard.sunkShipCount,
// this.player2.gameboard.scoreboard,
// );
if (this.player1.gameboard.sunkShipCount === 5) return;
count += 1;
}
}
handleUserMove(move = null) {
// let move = window.prompt('Enter your move in array fashion');
if (move) {
this.player2.gameboard.receiveAttack(JSON.parse(move));
}
this.player2.gameboard.shipStatus();
}
handleCPUMove() {
let move = this.player2.computerMoves(
this.player1.gameboard.scoreboard,
);
this.player1.gameboard.receiveAttack(move);
this.player1.gameboard.shipStatus();
}
}

View file

@ -0,0 +1,177 @@
import { Ship } from './ship';
class Gameboard {
constructor() {
// some code
this.ships = [];
this.sunkShipCount = 0;
// load settings
this.settings();
// Create Ships
this.createShips();
// Tracks the opponents attempts on the players gameboard
this.scoreboard = {
hits: new Set(),
misses: new Set(),
};
}
settings() {
this.shipCount = 5;
this.shipSize = [2, 3, 3, 4, 5];
}
createShips() {
for (let i = 0; i < this.shipSize.length; i++) {
let ship = new Ship(this.shipSize[i]);
while (true) {
let cords = this.generateCoordinates(this.shipSize[i]);
ship.coordinates = cords;
if (
!this.checkForDuplicateCoordinates(ship) &&
!this.checkForAdjacentCoordinates(ship)
) {
break;
}
}
this.ships.push(ship);
}
}
generateCoordinates(size) {
const coordinates = [];
const direction =
Math.floor(Math.random() * 2) === 1 ? 'vertical' : 'horizontal';
// if direction == vertial.. x should be the same.. else y will be the same
let x = Math.floor(Math.random() * 10) + 1;
let y = Math.floor(Math.random() * 10) + 1;
let startingPoint = Math.floor(Math.random() * 9) + 1;
if (startingPoint > 10 - size) startingPoint -= size;
for (let i = 1; i < size + 1; i++) {
if (direction === 'vertical') {
y = i + startingPoint;
coordinates.push([x, y]);
} else {
x = i + startingPoint;
coordinates.push([x, y]);
}
}
return coordinates;
}
checkForDuplicateCoordinates(ship) {
// needs to save coordinates to a list
let duplicates = false;
if (this.ships.length > 0) {
this.ships.forEach((s) => {
for (let i = 0; i < ship.coordinates.length; i++) {
let check = s.coordinates.find(
(s) =>
JSON.stringify(s) ===
JSON.stringify(ship.coordinates[i]),
);
if (check) {
duplicates = true;
}
}
});
}
return duplicates;
}
checkForAdjacentCoordinates(ship) {
// needs to save coordinates to a list
let adjacent = false;
let test = [];
const adj = [
[-1, 1],
[-1, 0],
[-1, -1],
[0, -1],
[1, -1],
[1, 0],
[1, 1],
[0, 1],
];
for (let y = 1; y < 11; y++) {
let rowData = [];
for (let x = 1; x < 11; x++) {
let adjPositions = [];
for (const [adjX, adjY] of adj) {
const tempX = x + adjX;
const tempY = y + adjY;
if (tempX >= 1 && tempX < 11 && tempY >= 1 && tempY < 11) {
adjPositions.push([tempX, tempY]);
}
}
rowData.push(adjPositions);
}
test.push(rowData);
}
if (this.ships.length > 0) {
this.ships.forEach((s) => {
for (let i = 0; i < ship.coordinates.length; i++) {
let x = ship.coordinates[i][1];
let y = ship.coordinates[i][0];
let adjacentCords = test[x - 1][y - 1];
for (let t = 0; t < adjacentCords.length; t++) {
let check = s.coordinates.find(
(s) =>
JSON.stringify(s) ===
JSON.stringify(adjacentCords[t]),
);
if (check) {
adjacent = true;
}
}
}
});
}
return adjacent;
}
receiveAttack(coordinate) {
let shipIndex;
for (let i = 0; i < this.ships.length; i++) {
let attacked = this.ships[i].coordinates.find(
(c) => JSON.stringify(coordinate) === JSON.stringify(c),
);
if (attacked) {
shipIndex = i;
this.ships[shipIndex].hit();
this.scoreboard.hits.add(JSON.stringify(coordinate));
return;
}
}
if (!shipIndex) this.scoreboard.misses.add(JSON.stringify(coordinate));
}
shipStatus() {
for (let i = 0; i < this.ships.length; i++) {
if (this.ships[i].isSunk()) {
this.sunkShipCount += 1;
this.ships.splice(i, 1);
}
}
}
}
export { Gameboard };

View file

@ -0,0 +1,24 @@
import { Gameboard } from './gameboard';
class Player {
constructor(name) {
this.gameboard = new Gameboard();
this.playerName = name;
}
computerMoves(scoreboard) {
function coordinates() {
let x = Math.floor(Math.random() * 10) + 1;
let y = Math.floor(Math.random() * 10) + 1;
return [x, y];
}
while (true) {
let potentialMove = coordinates();
if (!scoreboard.misses.has(JSON.stringify(potentialMove))) {
return potentialMove;
}
}
}
}
export { Player };

View file

@ -0,0 +1,16 @@
class Ship {
constructor(length) {
this.length = length;
this.hits = 0;
}
hit() {
this.hits += 1;
}
isSunk() {
return this.hits === this.length;
}
}
export { Ship };

9
battleship/src/index.js Normal file
View file

@ -0,0 +1,9 @@
import { Player } from './components/player';
import Game from './app';
import Website from './website';
import './style.css';
const player1 = new Player('Player1');
const player2 = new Player('CPU');
const game = new Game({ player1: player1, player2: player2 });
new Website(game);

31
battleship/src/style.css Normal file
View file

@ -0,0 +1,31 @@
#header {
display: flex;
justify-content: center;
}
.container {
display: flex;
justify-content: center;
align-content: center;
gap: 100px;
}
.grid {
display: flex;
width: 500px;
height: 500px;
flex-wrap: wrap;
}
.player2 div {
cursor: pointer;
}
.player2 div > div:hover {
background-color: gray;
}
.cell {
width: 48px;
height: 48px;
}

138
battleship/src/website.js Normal file
View file

@ -0,0 +1,138 @@
export default class Website {
constructor(game) {
this.game = game;
this.container = document.createElement('div');
this.container.classList.add('container');
this.header = document.createElement('header');
this.header.id = 'header';
this.footer = document.createElement('footer');
this.footer.id = 'footer';
this.createHeader();
this.updateScreen();
document.body.append(this.header, this.container, this.footer);
}
createHeader() {
let title = document.createElement('h1');
title.textContent = 'Battleship';
this.header.appendChild(title);
}
drawGrid(player = null) {
const div = document.createElement('div');
div.style.border = '1px solid black';
div.classList.add('grid');
let misses = player.gameboard.scoreboard.misses;
let hits = player.gameboard.scoreboard.hits;
let shipCoordinates = player.gameboard.ships.map(
(ship) => ship.coordinates,
);
let allShipCoordinates = shipCoordinates.concat(...shipCoordinates);
for (let i = 1; i < 11; i++) {
for (let j = 1; j < 11; j++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.dataset.cell = `[${j}, ${i}]`;
cell.style.border = '1px solid black';
div.appendChild(cell);
if (player.playerName === 'Player1') {
allShipCoordinates.forEach((ship) => {
if (JSON.stringify([j, i]) === JSON.stringify(ship)) {
cell.style.backgroundColor = 'blue';
}
});
}
if (hits.has(JSON.stringify([j, i]))) {
cell.style.backgroundColor = 'red';
} else if (misses.has(JSON.stringify([j, i]))) {
cell.style.backgroundColor = 'black';
}
}
}
return div;
}
updateScreen() {
// Clear screen before update
this.container.innerHTML = '';
const playerOneDiv = document.createElement('div');
playerOneDiv.classList.add('player1');
const h2 = document.createElement('h2');
h2.classList.add('player-title');
h2.textContent = 'Player 1';
playerOneDiv.append(h2, this.drawGrid(this.game.player1));
const playerTwoDiv = document.createElement('div');
playerTwoDiv.classList.add('player2');
playerTwoDiv.addEventListener('click', (event) =>
this.handleAttackClick(event),
);
const h2Cpu = document.createElement('h2');
h2Cpu.classList.add('player-title');
h2Cpu.textContent = 'CPU';
playerTwoDiv.append(h2Cpu, this.drawGrid(this.game.player2));
this.container.append(playerOneDiv, playerTwoDiv);
}
handleAttackClick(event) {
let move = event.target.dataset.cell
? JSON.parse(event.target.dataset.cell)
: null;
// Exit if the block has already been clicked
let available = this.game.player2.gameboard.scoreboard;
if (
available.misses.has(JSON.stringify(move)) ||
available.hits.has(JSON.stringify(move)) ||
!move
)
return;
this.game.handleUserMove(JSON.stringify(move));
this.updateScreen();
if (this.isGameOver()) {
let winner = this.announceWinner();
this.container.textContent = `Gameover ${winner} has won the game`;
}
this.CPUMove();
}
CPUMove() {
this.game.handleCPUMove();
this.updateScreen();
if (this.isGameOver()) {
let winner = this.announceWinner();
this.container.textContent = `Gameover ${winner} has won the game`;
}
}
isGameOver() {
return (
this.game.player1.gameboard.ships.length === 0 ||
this.game.player2.gameboard.ships.length === 0
);
}
announceWinner() {
if (this.game.player1.gameboard.ships.length === 0) {
return 'CPU';
}
return 'Player 1';
}
}