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:
Mike 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

21
battleship/.eslintrc.js Normal file
View file

@ -0,0 +1,21 @@
module.exports = {
env: {
browser: true,
es2021: true,
node: true,
},
extends: ['eslint:recommended', 'prettierd'],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
overrides: [
{
files: ['tests/**/*'],
plugins: ['jest'],
env: {
'jest/globals': true,
},
},
],
};

132
battleship/.gitignore vendored Normal file
View file

@ -0,0 +1,132 @@
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

4
battleship/.prettierrc Normal file
View file

@ -0,0 +1,4 @@
{
"tabWidth": 4,
"singleQuote": true
}

View file

@ -0,0 +1,6 @@
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
'@babel/preset-typescript',
],
};

9591
battleship/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

36
battleship/package.json Normal file
View file

@ -0,0 +1,36 @@
{
"name": "webpack-template",
"version": "1.0.0",
"description": "Vanilla template for webpack",
"main": "index.js",
"scripts": {
"test": "jest",
"start": "webpack serve --open --config webpack.dev.js",
"build": "webpack --config webpack.prod.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.23.9",
"@babel/preset-env": "^7.23.9",
"@babel/preset-typescript": "^7.23.3",
"@types/jest": "^29.5.12",
"babel-jest": "^29.7.0",
"css-loader": "^6.8.1",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-jest": "^27.9.0",
"html-webpack-plugin": "^5.6.0",
"jest": "^29.7.0",
"style-loader": "^3.3.3",
"ts-jest": "^29.1.2",
"webpack": "^5.89.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1",
"webpack-merge": "^5.10.0"
},
"dependencies": {
"lodash": "^4.17.21"
}
}

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';
}
}

View file

@ -0,0 +1,77 @@
import { Gameboard } from '../src/components/gameboard';
const gb = new Gameboard();
it('should place ships at random coordinates', () => {
// wait
});
it('should return random coordinates', () => {
const size = 3;
const coordinates = gb.generateCoordinates(size);
for (let i = 0; i < coordinates.length; i++) {
expect(coordinates[i][0]).toBeLessThan(11);
expect(coordinates[i][1]).toBeLessThan(11);
expect(coordinates[i][0]).toBeGreaterThan(0);
expect(coordinates[i][1]).toBeGreaterThan(0);
}
// expect(coordinates).toBe(3);
expect(coordinates).toHaveLength(size);
});
it('should create 5 ships', () => {
expect(gb.ships).toHaveLength(5);
});
it('should create 5 ships with lengths of 2,3,3,4,5', () => {
const size = [2, 3, 3, 4, 5];
for (let i = 0; i < 5; i++) {
expect(gb.ships[i].length).toBe(size[i]);
}
});
it('should contain unique random coordinates for each ship', () => {
let ships = [];
let count = 0;
let duplicates = false;
gb.ships.forEach((ship) => {
for (let i = 0; i < ship.coordinates.length; i++) {
let test = ships.find(
(s) =>
JSON.stringify(s) === JSON.stringify(ship.coordinates[i]),
);
if (!test) ships.push(ship.coordinates[i]);
if (test) {
duplicates = true;
}
}
});
expect(duplicates).toBeFalsy();
});
it('should show a ship was hit and increase the hit count', () => {
let attacks = [8, 5];
gb.ships[0].coordinates = [[8, 5]];
gb.receiveAttack(attacks);
expect(gb.ships[0].hits).toBe(1);
});
it('should report if a ship is sunk', () => {
gb.ships[0].length = 1;
expect(gb.ships[0].isSunk()).toBeTruthy();
});
it('should track hits and misses', () => {
expect(gb.scoreboard.hits.size).toBe(1);
expect(gb.scoreboard.misses.size).toBe(0);
gb.receiveAttack([-1, -1]);
expect(gb.scoreboard.misses.size).toBe(1);
});
it('should have a sunk count of 1 and only four ships now', () => {
gb.shipStatus();
expect(gb.ships).toHaveLength(4);
expect(gb.sunkShipCount).toBe(1);
});

View file

@ -0,0 +1,18 @@
import { Gameboard } from '../src/components/gameboard';
class Player {
constructor(name) {
this.gameboard = new Gameboard();
this.playerName = name;
}
}
let p = new Player('Player1');
it('should contain a gameboard', () => {
expect(p.gameboard).toHaveProperty(
'ships',
'scoreboard',
'shipCount',
'sunkShipCount',
);
});

View file

@ -0,0 +1,27 @@
import { Ship } from '../src/components/ship';
it('should have length, number of times hit, and if sunk', () => {
// Small ship
const _ship = new Ship(2);
expect(_ship).toEqual({
length: 2,
hits: 0,
});
});
it('if hit, hit count should increase', () => {
const _ship = new Ship(2);
_ship.hit();
expect(_ship.hits).toBe(1);
});
it('is not sunk', () => {
const _ship = new Ship(2);
expect(_ship.isSunk()).toBeFalsy();
});
it('is sunk', () => {
const _ship = new Ship(2);
_ship.hits = 2;
expect(_ship.isSunk()).toBeTruthy();
});

View file

@ -0,0 +1,34 @@
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
index: './src/index.js',
},
plugins: [
new HtmlWebpackPlugin({
title: 'Battleship',
}),
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
],
},
};

10
battleship/webpack.dev.js Normal file
View file

@ -0,0 +1,10 @@
const { merge } = require("webpack-merge");
const common = require("./webpack.common.js");
module.exports = merge(common, {
mode: "development",
devtool: "inline-source-map",
devServer: {
static: "./dist",
},
});

View file

@ -0,0 +1,6 @@
const { merge } = require("webpack-merge");
const common = require("./webpack.common.js");
module.exports = merge(common, {
mode: "production",
});

View file

@ -1,12 +1,22 @@
module.exports = {
env: {
browser: true,
es2021: true,
node: true,
},
extends: ["eslint:recommended", "prettier"],
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
},
env: {
browser: true,
es2021: true,
node: true,
},
extends: ['eslint:recommended', 'prettier'],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
overrides: [
{
files: ['tests/**/*'],
plugins: ['jest'],
env: {
'jest/globals': true,
},
},
],
};

View file

@ -1,3 +1,6 @@
module.exports = {
presets: [['@babel/preset-env', { targets: { node: 'current' } }]],
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
'@babel/preset-typescript',
],
};

9207
testing/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -14,10 +14,17 @@
"devDependencies": {
"@babel/core": "^7.23.9",
"@babel/preset-env": "^7.23.9",
"@babel/preset-typescript": "^7.23.3",
"@types/jest": "^29.5.12",
"babel-jest": "^29.7.0",
"css-loader": "^6.8.1",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-jest": "^27.9.0",
"html-webpack-plugin": "^5.6.0",
"jest": "^29.7.0",
"style-loader": "^3.3.3",
"ts-jest": "^29.1.2",
"html-webpack-plugin": "^5.6.0",
"jest": "^29.7.0",
"style-loader": "^3.3.3",