aboutsummaryrefslogtreecommitdiffstats
path: root/battleshipFiles
diff options
context:
space:
mode:
Diffstat (limited to 'battleshipFiles')
-rw-r--r--battleshipFiles/Battleship.js36
-rw-r--r--battleshipFiles/battleship.css15
-rw-r--r--battleshipFiles/battleshipBotFunctions.js279
-rw-r--r--battleshipFiles/battleshipFunctions.js211
-rw-r--r--battleshipFiles/battleshipGameFunctions.js362
-rw-r--r--battleshipFiles/battleshipUIFunctions.js173
-rw-r--r--battleshipFiles/battleshipUserFunctions.js97
-rw-r--r--battleshipFiles/constants.js27
8 files changed, 1200 insertions, 0 deletions
diff --git a/battleshipFiles/Battleship.js b/battleshipFiles/Battleship.js
new file mode 100644
index 0000000..9b2a62a
--- /dev/null
+++ b/battleshipFiles/Battleship.js
@@ -0,0 +1,36 @@
+class Battleship
+{
+ constructor(name)
+ {
+ // Set name
+ this.name = name;
+ // Initializing game map
+ this.gameMap = createGameMap();
+ // Declaring how many of which type ships there would be
+ this.shipsMap = new Map();
+ this.shipsMap.set(4, NUM_OF_4);
+ this.shipsMap.set(3, NUM_OF_3);
+ this.shipsMap.set(2, NUM_OF_2);
+ this.shipsMap.set(1, NUM_OF_1);
+ this.shipsArray = [];
+ for(let [key, value] of this.shipsMap)
+ for(let i = 0; i < value; i++)
+ this.shipsArray.push(key);
+
+ this.howManyShips = eval(this.shipsArray.join('+'));
+ // creating vars, used later
+ this.destroyedShips = 0;
+ }
+}
+function createGameMap()
+{
+ let gameMap = new Array(MAP_SIZE + 2);
+ for(let i = 0; i < MAP_SIZE + 2; i++)
+ gameMap[i] = new Array(MAP_SIZE + 2);
+
+ for(let i = 0; i < MAP_SIZE + 2; i++)
+ for(let j = 0; j < MAP_SIZE + 2; j++)
+ gameMap[i][j] = 0;
+
+ return gameMap;
+} \ No newline at end of file
diff --git a/battleshipFiles/battleship.css b/battleshipFiles/battleship.css
new file mode 100644
index 0000000..89ec109
--- /dev/null
+++ b/battleshipFiles/battleship.css
@@ -0,0 +1,15 @@
+.ul
+{
+ list-style-type: none;
+}
+
+#whosTurn {
+ position: fixed;
+ bottom: 10rem;
+ left: 50%;
+ translate: -50%;
+}
+
+body {
+ height: 100vh;
+}
diff --git a/battleshipFiles/battleshipBotFunctions.js b/battleshipFiles/battleshipBotFunctions.js
new file mode 100644
index 0000000..669a881
--- /dev/null
+++ b/battleshipFiles/battleshipBotFunctions.js
@@ -0,0 +1,279 @@
+function populateMapRandomly(player)
+{
+ for(let ship of player.shipsArray)
+ {
+ let isSet = false;
+ while(!isSet)
+ {
+ let direction = getRandomInt(0, 2) === 0 ? "horizontally" : "vertically";
+ let x, y;
+ // if(direction === "horizontally")
+ if(direction === "vertically")
+ {
+ x = getRandomInt(1, MAP_SIZE - ship + 2);
+ y = getRandomInt(1, MAP_SIZE + 1);
+ }
+ // else if(direction === "vertically")
+ else if(direction === "horizontally")
+ {
+ x = getRandomInt(1, MAP_SIZE + 1);
+ y = getRandomInt(1, MAP_SIZE - ship + 2);
+ }
+ if(checkPositionForShip(x, y, direction, ship, player) === true)
+ {
+ isSet = true;
+ putShipOnGameMap(player, x, y, direction, ship, false);
+ }
+ }
+ }
+}
+
+function botShot(bot, user, ai)
+{
+ // console.log("Shot number: " + ai.numberOfShots++ + (ai.shipWasShot.length !== 0 ? " (ship was shot)" : " (ship wasnt shot)"));
+ // console.log("Start: ", ai);
+
+ let superPositions = calculateSuperpositionsArray(bot, ai);
+ let userTable = document.getElementById("userTable");
+ let shotIndex = {x: 'x', y: 'y'};
+
+ if(ai.shipWasShot.length !== 0)
+ {
+ let x = ai.shipWasShot[0];
+ let y = ai.shipWasShot[1];
+
+ if(!ai.shotShipDirection)
+ {
+ let possibleShots = new Map();
+ if(x !== 1)
+ possibleShots.set("up", [superPositions[x - 1][y], x - 1, y]);
+ if(x !== 10)
+ possibleShots.set("down", [superPositions[x + 1][y], x + 1, y]);
+ if(y !== 1)
+ possibleShots.set("left", [superPositions[x][y - 1], x, y - 1]);
+ if(y !== 10)
+ possibleShots.set("right", [superPositions[x][y + 1], x, y + 1]);
+
+ possibleShots = new Map([...possibleShots.entries()].sort((a, b) => b[1][0] - a[1][0]));
+
+ if(possibleShots.entries().next().value[0] === "up" || possibleShots.entries().next().value[0] === "down")
+ ai.shotShipDirection = "vertically";
+ else
+ ai.shotShipDirection = "horizontally";
+
+ shotIndex.x = possibleShots.entries().next().value[1][1];
+ shotIndex.y = possibleShots.entries().next().value[1][2];
+
+ // if(possibleShots.entries().next().value[1][0] < 1)
+ // ai.shipWasShot = [];
+ }
+ else
+ {
+ let beforeFirst = {x: 'x', y: 'y'}, afterLast = {x: 'x', y: 'y'};
+ if(ai.shotShipDirection === "vertically")
+ {
+ // console.log("unsorted:", ai.shotShips);
+ ai.shotShips.sort((a, b) => a.x - b.x);
+ // console.log("sorted:", ai.shotShips);
+ beforeFirst.x = ai.shotShips.first().x - 1;
+ beforeFirst.y = ai.shotShips.first().y;
+ afterLast.x = ai.shotShips.last().x + 1;
+ afterLast.y = ai.shotShips.last().y;
+ }
+ else if(ai.shotShipDirection === "horizontally")
+ {
+ // console.log("unsorted:", ai.shotShips);
+ ai.shotShips.sort((a, b) => a.y - b.y);
+ // console.log("sorted:", ai.shotShips);
+ beforeFirst.x = ai.shotShips.first().x;
+ beforeFirst.y = ai.shotShips.first().y - 1;
+ afterLast.x = ai.shotShips.last().x;
+ afterLast.y = ai.shotShips.last().y + 1;
+ }
+ // if(superPositions[beforeFirst.x][beforeFirst.y] > 0 || superPositions[afterLast.x][afterLast.y] > 0)
+ // {
+ if(superPositions[beforeFirst.x][beforeFirst.y] > superPositions[afterLast.x][afterLast.y])
+ {
+ shotIndex.x = beforeFirst.x;
+ shotIndex.y = beforeFirst.y;
+ }
+ else
+ {
+
+ shotIndex.x = afterLast.x;
+ shotIndex.y = afterLast.y;
+ }
+ // }
+ // else
+ // ai.shipWasShot = [];
+ }
+
+ // if(!ai.shotShips.includes({x: shotIndex.x, y: shotIndex.y}))
+ ai.shotShips.push({x: shotIndex.x, y: shotIndex.y});
+ }
+ if(ai.shipWasShot.length === 0 || superPositions[shotIndex.x][shotIndex.y] === 0)
+ {
+ let indexes = getAllIndexes2D(superPositions, Math.max.apply(null,
+ superPositions.map(row => Math.max.apply(null, row))));
+ let t = indexes[getRandomInt(0, indexes.length)];
+ shotIndex.x = t[0];
+ shotIndex.y = t[1];
+ }
+
+ if(user.gameMap[shotIndex.x][shotIndex.y] !== 0)
+ {
+ ai.shipWasShot = [shotIndex.x, shotIndex.y];
+ user.gameMap[shotIndex.x][shotIndex.y] = 2;
+ ai.gameMap[shotIndex.x][shotIndex.y] = -3;
+ userTable.children[shotIndex.x - 1].children[shotIndex.y - 1].innerHTML = SHIP_HITTED;
+
+ if(ai.shotShips.length === 0)
+ ai.shotShips.push({x: shotIndex.x, y: shotIndex.y});
+ }
+ else
+ {
+ ai.gameMap[shotIndex.x][shotIndex.y] = -2;
+ userTable.children[shotIndex.x - 1].children[shotIndex.y - 1].innerHTML = SHIP_MISSED;
+ user.gameMap[shotIndex.x][shotIndex.y] = 3;
+
+ if(ai.shotShips.length > 1)
+ ai.shotShips.pop();
+
+ if(ai.shotShips.length === 1)
+ ai.shotShipDirection = "";
+
+ turnChange(bot.name);
+ }
+ if(ai.shotShips.length !== 0)
+ checkShotShips(bot, ai, superPositions);
+
+ // if(ai.shotShips.length !== 0)
+ // console.log("End: ", ai.gameMap, ai.shipWasShot, ai.shotShipDirection, ai.shotShips);
+
+ // if([0, 3].includes(bot.gameMap[shotIndex.x][shotIndex.y]) )//user.gameMap[shotIndex.x][shotIndex.y] !== 0)
+ if(user.gameMap[shotIndex.x][shotIndex.y] === 2)//user.gameMap[shotIndex.x][shotIndex.y] !== 0)
+ {
+ user.destroyedShips += 1;
+ if(user.destroyedShips === user.howManyShips)
+ ifWonEndGame(user, bot);
+ else if(IM_SPEED || REMOVE_WAITING)
+ setTimeout(() => botShot(bot, user, ai), 200);
+ else
+ setTimeout(() => botShot(bot, user, ai), BOT_DELAY);
+ }
+}
+
+function checkShotShips(bot, ai, superPositions)
+{
+ let longestShip = Math.max(...ai.shipsArray);
+ if(ai.shotShips.length > longestShip)
+ console.log("%cImpossible stanelo sie", "color: red;");
+ else if(ai.shotShips.length < longestShip)
+ {
+ let xFirst = ai.shotShips.first().x,
+ xLast = ai.shotShips.last().x,
+ yFirst = ai.shotShips.first().y,
+ yLast = ai.shotShips.last().y;
+ if(ai.shotShips.length === 1)
+ {
+ for(let i = -1; i < 3; i += 2)
+ {
+ if(!checkPositionForShotShip(xFirst + i, yFirst, ai.gameMap, superPositions)
+ || !checkPositionForShotShip(xFirst, yFirst + i, ai.gameMap, superPositions))
+ return;
+ }
+ // if(!checkPositionForShotShip(x - 1, y, ai.gameMap, superPositions)
+ // || !checkPositionForShotShip(x + 1, y, ai.gameMap, superPositions)
+ // || !checkPositionForShotShip(x, y - 1, ai.gameMap, superPositions)
+ // || !checkPositionForShotShip(x, y + 1, ai.gameMap, superPositions))
+ // return;
+ }
+ else if(ai.shotShips.length < longestShip)
+ {
+ // console.log("%cship.length > 1", "color: lightgreen;");
+ if(ai.shotShipDirection === "vertically")
+ {
+ ai.shotShips.sort((a, b) => a.x - b.x);
+ if(!checkPositionForShotShip(xFirst - 1, yFirst, ai.gameMap, superPositions)
+ || !checkPositionForShotShip(xLast + 1, yLast, ai.gameMap, superPositions))
+ return;
+ }
+ else if(ai.shotShipDirection === "horizontally")
+ {
+ ai.shotShips.sort((a, b) => a.y - b.y);
+ if(!checkPositionForShotShip(xFirst, yFirst - 1, ai.gameMap, superPositions)
+ || !checkPositionForShotShip(xLast, yLast + 1, ai.gameMap, superPositions))
+ return;
+ }
+ }
+ }
+
+ // console.log("%cimma destroy shotShips", "color: lightblue;");
+ ai.shotShips.forEach(shotShip => {
+ ai.gameMap[shotShip.x][shotShip.y] = -1;
+ });
+
+ removeElementFromArray(ai.shotShips.length, ai.shipsArray);
+ ai.shipWasShot = [];
+ ai.shotShips = [];
+ ai.shotShipDirection = "";
+}
+
+function checkPositionForShotShip(x, y, gameMap, superPositions)
+{
+ if(superPositions[x][y] === 0 || gameMap[x][y] === -2)
+ return true;
+}
+
+function calculateSuperpositionsArray(bot, ai)
+{
+ let gameMap = createGameMap();
+
+ for(let ship of ai.shipsArray)
+ {
+ for(let i = 1; i <= MAP_SIZE; i++)
+ {
+ for(let j = 1; j <= MAP_SIZE; j++)
+ {
+ if(checkPositionForSuperShip(i, j, "horizontally", ship, ai))
+ for(let k = j; k < j + ship; k++)
+ if(gameMap[i][k] !== -3)
+ gameMap[i][k] += 1;
+ if(ship !== 1 && checkPositionForSuperShip(i, j, "vertically", ship, ai))
+ for(let k = i; k < i + ship; k++)
+ if(gameMap[k][j] !== -3)
+ gameMap[k][j] += 1;
+ }
+ }
+ }
+ // console.table(gameMap)
+ return gameMap;
+}
+
+function checkPositionForSuperShip(x, y, direction, ship, player)
+{
+ if(direction === "horizontally")
+ {
+ if(y + ship <= MAP_SIZE + 1 && checkPositionForShip(x, y, "horizontally", ship, player))
+ {
+ for(let k = y; k < y + ship; k++)
+ if(player.gameMap[x][k] === -2)
+ return false;
+ }
+ else
+ return false;
+ }
+ else if(direction === "vertically")
+ {
+ if(x + ship <= MAP_SIZE + 1 && checkPositionForShip(x, y, "vertically", ship, player))
+ {
+ for(let k = x; k < x + ship; k++)
+ if(player.gameMap[k][y] === -2)
+ return false;
+ }
+ else
+ return false;
+ }
+
+ return true;
+}
diff --git a/battleshipFiles/battleshipFunctions.js b/battleshipFiles/battleshipFunctions.js
new file mode 100644
index 0000000..ce4efff
--- /dev/null
+++ b/battleshipFiles/battleshipFunctions.js
@@ -0,0 +1,211 @@
+const getRandomInt = (min, max) => Math.floor(Math.random() * (max - min) + min);
+Array.prototype.last = function() {return this[this.length - 1];};
+Array.prototype.first = function() {return this[0];};
+const removeElementFromArray = (value, array) => {
+ let index = array.indexOf(value);
+ if(index > -1)
+ array.splice(index, 1);
+};
+
+function startNewGame()
+{
+ let user = new Battleship("user");
+ let bot = new Battleship("bot");
+ let ai = new Battleship("ai");
+ delete ai.howManyShips;
+ delete ai.name;
+ delete ai.shipsMap;
+ ai.numberOfShots = 1;
+ // ai.gameMap = createGameMap();
+ ai.shotShips = [];
+ ai.shipWasShot = [];
+ ai.shotShipDirection = "";
+ //bot.ai = {};
+ window.vars = {};
+
+
+ createUI(user, bot, ai);
+
+ populateMapRandomly(bot);
+ if(IM_SPEED)
+ populateMapRandomly(user);
+ generateGameMap(bot);
+
+ generateGameMap(user);
+ if(!IM_SPEED)
+ generateShipsUl(user);
+ if(IM_SPEED)
+ document.getElementById("button").click();
+ if(!IM_SPEED)
+ positionShips(user);
+ //calculateSuperpositionsArray(bot, ai);
+
+ //botShot(bot, user);
+ let doTest = false;
+ if(doTest)
+ {
+ setTimeout(() => {
+ document.body.innerHTML = "";
+ window.vars = undefined;
+ startNewGame();
+ }, 200);
+ }
+}
+
+function positionShips(player)
+{
+ let table = document.getElementById("userTable");
+
+ window.vars.shipDirection = "horizontally";
+
+ window.vars.player = player;
+ table.addEventListener('contextmenu', onRightClick);
+
+ // table.addEventListener("mouseleave", clearUserShipPosition);
+ table.onmouseleave = clearUserShipPosition;
+
+ [...table.children].forEach((tr, trNumber) => {
+ [...tr.children].forEach((td, tdNumber) => {
+ td.onmouseenter = () => showUserShipPosition(tr, trNumber, td, tdNumber, player);
+ td.onclick = () => putShipOnGameMap(player, trNumber + 1, tdNumber + 1, undefined, undefined, true);
+ });
+ });
+}
+
+function onRightClick()
+{
+ window.vars.shipDirection = window.vars.shipDirection === "horizontally" ? "vertically" : "horizontally";
+ showUserShipPosition(window.vars.givenTr, window.vars.givenTrNumber, window.vars.givenTd, window.vars.givenTdNumber, window.vars.player);
+}
+
+function putShipOnGameMap(player, x, y, direction, ship, update)
+{
+ if(player.gameMap[x][y] === 1)
+ {
+ clearUserShipPosition();
+
+ let gettedShip = getShip(x, y, player);
+ player.shipsArray.push(gettedShip.array.length);
+ player.shipsArray.sort((a, b) => b - a);
+
+ for(let coordinates of gettedShip.array)
+ player.gameMap[coordinates.x][coordinates.y] = 0;
+
+ for(let td of gettedShip.table)
+ td.className = TABLE_BG_COLOR;
+
+ generateShipsUl(player);
+ window.vars.selectedShip = document.getElementById("ul").children[0].children[0].children[0];
+
+ for(let i = 0; i < MAP_SIZE; i++)
+ window.vars.selectedTd[i] = undefined;
+
+ for(let td of window.vars.selectedShip.children)
+ td.className = SHIP_BG_COLOR;
+
+ window.vars.isPlaceable = false;
+ return;
+ }
+ // Checking if there are all arguments and sense for this function
+ if(player.shipsArray.length === 0 || /*window.vars.wasShipPlaced ||*/ (update && !window.vars.isPlaceable))
+ return false;
+ if(direction === undefined)
+ direction = window.vars.shipDirection;
+ if(ship === undefined)
+ ship = window.vars.selectedShip.children.length;
+
+ // Preventing ability to place all ships on one td
+ // TODO: usunac 2 linie
+ // if(window.vars.wasShipPlaced !== undefined)
+ // window.vars.wasShipPlaced = true;
+
+ // Correct x and y, because mouse position !== ship start
+ [x, y] = correctXY(x, y, ship, direction);
+
+ // Updating gameMap
+ if(direction === "vertically")
+ for(let i = 0; i < ship; i++)
+ player.gameMap[x + i][y] = 1;
+ else if(direction === "horizontally")
+ for(let i = 0; i < ship; i++)
+ player.gameMap[x][y + i] = 1;
+
+ // Preventing newly colored td's on table form being turn back to TABLE_BG_COLOR
+ if(window.vars.selectedTd !== undefined)
+ for(let i = 0; i < MAP_SIZE; i++)
+ window.vars.selectedTd[i] = undefined;
+
+ if(update)
+ {
+ // Update GUI efficiently
+ let table = document.getElementById(player.name + "Table");
+ if(direction === "vertically")
+ for(let i = 0; i < ship; i++)
+ table.children[x + i - 1].children[y - 1].className = SHIP_BG_COLOR;
+ else if(direction === "horizontally")
+ for(let i = 0; i < ship; i++)
+ table.children[x - 1].children[y + i - 1].className = SHIP_BG_COLOR;
+
+ // Removing ship from shipsArray
+ removeElementFromArray(ship, player.shipsArray);
+
+ // Removing ship from ul of ships, if there's no other ships exiting function and removing onmouseenter
+ window.vars.selectedShip.parentNode.parentNode.remove();
+ if(player.shipsArray.length === 0)
+ {
+ // Remove all vars and listeners
+ [...document.getElementById("userTable").children].forEach(tr => {
+ [...tr.children].forEach(td => {
+ td.onmouseenter = undefined;// () => {return;};
+ });
+ });
+ document.getElementById("userTable").onmouseleave = undefined;
+ document.getElementById("userTable").removeEventListener('contextmenu', onRightClick);
+ window.vars = {};
+
+ document.getElementById("whosTurn").style.display = "none";
+ document.getElementById("button").style.display = "inline-block";
+ return;
+ }
+
+ window.vars.selectedShip = document.getElementById("ul").children[0].children[0].children[0];
+
+ // Setting color of newly selected ship
+ for(let td of window.vars.selectedShip.children)
+ td.className = SHIP_BG_COLOR;
+ }
+}
+
+function correctXY(x, y, ship, direction)
+{
+ if(direction === "vertically" && x + ship > MAP_SIZE + 1)
+ x -= (x - 1 + ship) - MAP_SIZE;
+ else if(direction === "horizontally" && y + ship > MAP_SIZE + 1)
+ y -= (y - 1 + ship) - MAP_SIZE;
+
+ return [x, y];
+}
+
+function getAllIndexes2D(array, value)
+{
+ let indexes = [];
+ array.forEach((row, i) => {
+ row.forEach((val, j) => {
+ if(val === value)
+ indexes.push([i, j]);
+ });
+ });
+
+ return indexes;
+}
+
+function updateGameMap(player)
+{
+ let table = document.getElementById(player.name + "Table");
+ [...table.children].forEach((tr, i) => {
+ [...tr.children].forEach((td, j) => {
+ if([1, 2].includes(player.gameMap[i + 1][j + 1]))
+ td.className = SHIP_BG_COLOR;
+ });
+ });
+} \ No newline at end of file
diff --git a/battleshipFiles/battleshipGameFunctions.js b/battleshipFiles/battleshipGameFunctions.js
new file mode 100644
index 0000000..0a29bff
--- /dev/null
+++ b/battleshipFiles/battleshipGameFunctions.js
@@ -0,0 +1,362 @@
+function startGame(player, bot, ai)
+{
+ window.vars.whosTurn = "user";
+
+ document.getElementById("button").style.display = "none";
+ document.getElementById("whosTurn").style.display = "inline";
+ document.getElementById("whosTurn").innerText = "Twoja tura";
+
+ let userTable = document.getElementById("userTable");
+ let botTable = document.getElementById("botTable");
+ userTable.onclick = () => window.alert("To Twoja tabela -_- <script player.iq--; </script>");
+ [...botTable.children].forEach((tr, trNumber) => {
+ [...tr.children].forEach((td, tdNumber) => {
+ td.onmouseenter = () => showUserShotPosition(td);
+ // td.onmouseenter = showUserShotPosition;
+ td.onmouseleave = () => hideUserShotPosition(td);
+ // td.onmouseleave = hideUserShotPosition;
+ td.onclick = () => userShot(td, bot, trNumber + 1, tdNumber + 1, player, ai);
+ });
+ });
+}
+
+// function showUserShotPosition()
+// {
+// this.innerHTML = "╳";
+// }
+const showUserShotPosition = td => td.innerHTML = "╳";
+
+const hideUserShotPosition = td => td.innerHTML = "";
+
+function userShot(td, bot, x, y, user, ai)
+{
+ if(window.vars.whosTurn === "bot")
+ {
+ window.alert("Tura sztucznej inteligencji");
+ return;
+ }
+ if(bot.gameMap[x][y] !== 0)
+ {
+ bot.destroyedShips += 1;
+ if(bot.destroyedShips === bot.howManyShips)
+ console.log("here");
+ bot.gameMap[x][y] = 2;
+ td.innerHTML = SHIP_HITTED;
+
+ // Coloring whole ship when it sunk
+ // if(IM_SPEED)
+ // checkForNearbyShips(x, y, bot);
+ if(checkIfWholeShipWasShotStart(x, y, bot))
+ destroyShip(bot, x, y);
+ // destroyShip(td, bot, x, y);
+
+ if(bot.destroyedShips === bot.howManyShips)
+ console.log("here2");
+ // bot.destroyedShips += 1;
+ if(bot.destroyedShips === bot.howManyShips)
+ ifWonEndGame(bot, user);
+ }
+ else
+ {
+ bot.gameMap[x][y] = 3;
+ td.innerHTML = SHIP_MISSED;
+ turnChange(user.name);
+ }
+
+ td.onclick = undefined;
+ td.onmouseenter = undefined;
+ td.onmouseleave = undefined;
+
+ // if(IM_SPEED)
+ // checkForNearbyShips(x, y, bot);
+
+ // if(bot.gameMap[x][y] !== 0)
+ // if([0, 3].includes(bot.gameMap[x][y]))
+ if(bot.gameMap[x][y] === 3)
+ {
+ if(IM_SPEED || REMOVE_WAITING)
+ botShot(bot, user, ai);
+ else
+ setTimeout(() => botShot(bot, user, ai), BOT_DELAY);
+ }
+ // if((!IM_SPEED || !REMOVE_WAITING) && bot.gameMap[x][y] === 0)
+ // setTimeout(() => botShot(bot, user, ai), 1000);
+ // else if(bot.gameMap[x][y] === 0)
+ // botShot(bot, user, ai);
+}
+
+function checkForNearbyShips(x, y, player)
+{
+ if(player.gameMap[x][y] === 2)
+ if(checkIfWholeShipWasShotStart(x, y, player))
+ destroyShip(player, x, y);
+ else
+ {
+ if(player.gameMap[x - 1][y] === 2)
+ if(checkIfWholeShipWasShotStart(x - 1, y, player))
+ destroyShip(player, x - 1, y);
+
+ if(player.gameMap[x + 1][y] === 2)
+ if(checkIfWholeShipWasShotStart(x + 1, y, player))
+ destroyShip(player, x + 1, y);
+
+ if(player.gameMap[x][y - 1] === 2)
+ if(checkIfWholeShipWasShotStart(x, y - 1, player))
+ destroyShip(player, x, y - 1);
+
+ if(player.gameMap[x][y + 1] === 2)
+ if(checkIfWholeShipWasShotStart(x, y + 1, player))
+ destroyShip(player, x, y + 1);
+ }
+}
+
+function destroyShip(bot, x, y)
+{
+ // let tdNumber = x - 1;
+ // let trNumber = y - 1;
+ // let td = document.getElementById(bot.name + "Table").children[tdNumber].children[tdNumber];
+ // let direction = getShipDirection(x, y, bot);
+
+ let ship = getShip(x, y, bot);
+ for(let td of ship.table)
+ {
+ td.classList.remove(SHIP_BG_COLOR);
+ td.classList.add("bg-danger");
+ }
+ // return ship.table.length;
+}
+
+function getShip(x, y, player)
+{
+ let direction = getShipDirection(x, y, player);
+ let table = document.getElementById(player.name + "Table");
+ let output = {};
+ output.array = [];
+ output.table = [];
+
+ if(typeof direction !== "string")
+ {
+ output.array[0] = {
+ 'x': x,
+ 'y': y
+ };
+ output.table[0] = table.children[output.array[0].x - 1].children[output.array[0].y - 1];
+ }
+ else
+ {
+ let i, j;
+ if(direction === "up" || direction === "down")
+ {
+ i = x;
+ j = x;
+
+ // while(player.gameMap[i + 1][y] !== 0)
+ while(![0, 3].includes(player.gameMap[i + 1][y]))
+ i++;
+ // while(player.gameMap[j - 1][y] !== 0)
+ while(![0, 3].includes(player.gameMap[j - 1][y]))
+ j--;
+
+ for(let k = 0; j <= i; j++, k++)
+ {
+ output.array[k] = {
+ 'x': j,
+ 'y': y
+ };
+ output.table[k] = table.children[output.array[k].x - 1].children[output.array[k].y - 1];
+ }
+ }
+ else if(direction === "left" || direction === "right")
+ {
+ i = y;
+ j = y;
+ // while(player.gameMap[x][i + 1] !== 0)
+ while(![0, 3].includes(player.gameMap[x][i + 1]))
+ i++;
+ // while(player.gameMap[x][j - 1] !== 0)
+ while(![0, 3].includes(player.gameMap[x][j - 1]))
+ j--;
+
+ for(let k = 0; j <= i; j++, k++)
+ {
+ output.array[k] = {
+ 'x': x,
+ 'y': j
+ };
+ output.table[k] = table.children[output.array[k].x - 1].children[output.array[k].y - 1];
+ }
+ }
+ }
+
+ return output;
+}
+
+function getShipDirection(x, y, player)
+{
+ // if(player.gameMap[x - 1][y] !== 0 && player.gameMap[x + 1][y] !== 0)
+ // return "vertical";
+ //
+ // else if(player.gameMap[x][y - 1] !== 0 && player.gameMap[x][y + 1] !== 0)
+ // return "horizontal";
+
+ if(![0, 3].includes(player.gameMap[x - 1][y]))// !== 0)
+ return "up";
+
+ else if(![0, 3].includes(player.gameMap[x + 1][y]))// !== 0)
+ return "down";
+
+ else if(![0, 3].includes(player.gameMap[x][y - 1]))// !== 0)
+ return "left";
+
+ else if(![0, 3].includes(player.gameMap[x][y + 1]))// !== 0)
+ return "right";
+
+ else
+ return true;
+}
+
+function checkIfWholeShipWasShotStart(x, y, bot)
+{
+ let direction = getShipDirection(x, y, bot);
+ if(typeof direction === "string")
+ {
+ // window.vars.howLongIsShip = 1;
+ if(direction === "up" || direction === "down")
+ {
+ // let output = true;
+ // if(!checkIfWholeShipWasShot(x - 1, y, bot, "up", -1, 0))
+ // output = false;
+ // if(!checkIfWholeShipWasShot(x + 1, y, bot, "down", 1, 0))
+ // output = false;
+ // if(output || window.vars.howLongIsShip === Math.max(...bot.shipsArray))
+ if((checkIfWholeShipWasShot(x - 1, y, bot, "up", -1, 0)
+ && checkIfWholeShipWasShot(x + 1, y, bot, "down", 1, 0)))
+ // || (window.vars.howLongIsShip === Math.max(...bot.shipsArray)))
+ {
+ removeElementFromArray(window.vars.howLongIsShip, bot.shipsArray);
+ return true;
+ }
+ else
+ return false;
+
+ }
+ // return (checkIfWholeShipWasShot(x - 1, y, bot, "up", -1, 0) &&
+ // checkIfWholeShipWasShot(x + 1, y, bot, "down", 1, 0));
+ else if(direction === "left" || direction === "right")
+ {
+ // let output = true;
+ // if(!checkIfWholeShipWasShot(x, y - 1, bot, "left", 0, -1))
+ // output = false;
+ // if(!checkIfWholeShipWasShot(x, y + 1, bot, "right", 0, 1))
+ // output = false;
+ // if(output || window.vars.howLongIsShip === Math.max(...bot.shipsArray))
+ if((checkIfWholeShipWasShot(x, y - 1, bot, "left", 0, -1)
+ && checkIfWholeShipWasShot(x, y + 1, bot, "right", 0, 1)))
+ // || window.vars.howLongIsShip === Math.max(...bot.shipsArray))
+ {
+ removeElementFromArray(window.vars.howLongIsShip, bot.shipsArray);
+ return true;
+ }
+ else
+ return false;
+ }
+ // return (checkIfWholeShipWasShot(x, y - 1, bot, "left", 0, -1) &&
+ // checkIfWholeShipWasShot(x, y + 1, bot, "right", 0, 1));
+ }
+ // else
+ // {
+ // if(((bot.gameMap[x - 1][y] === 3 || x - 1 < 1)
+ // && (bot.gameMap[x + 1][y] === 3 || x + 1 > 10)
+ // && (bot.gameMap[x][y - 1] === 3 || y - 1 < 1)
+ // && (bot.gameMap[x][y + 1] === 3 || y + 1 > 10))
+ // || Math.max(...bot.shipsArray) === 1)
+ // {
+ // removeElementFromArray(1, bot.shipsArray);
+ // console.log(bot.shipsArray);
+ // return true;
+ // }
+ // else
+ // return false;
+ // }
+ return direction;
+}
+
+function checkIfWholeShipWasShot(x, y, bot, direction, xShift, yShift)
+{
+ if(bot.gameMap[x][y] === 3 || bot.gameMap[x][y] === 0)// || x > 10 || x < 1 || y > 10 || y < 1)
+ return true;
+ else if(bot.gameMap[x][y] === 1)
+ return false;
+ else if(bot.gameMap[x][y] === 2)
+ {
+ // window.vars.howLongIsShip++;
+ // console.log(window.vars.howLongIsShip);
+ return checkIfWholeShipWasShot(x + xShift, y + yShift, bot, direction, xShift, yShift);
+ }
+ // else if(bot.gameMap[x][y] === 3)
+ // return true;
+}
+
+function turnChange(from)
+{
+ let whosTurn = document.getElementById("whosTurn");
+ if(from === "user")
+ {
+ whosTurn.innerHTML = "Tura sztucznej inteligencji";
+ window.vars.whosTurn = "bot";
+ }
+ else if(from === "bot")
+ {
+ whosTurn.innerHTML = "Twoja tura";
+ window.vars.whosTurn = "user";
+ }
+}
+
+function ifWonEndGame(player, winner)
+{
+ let userTable = document.getElementById("userTable");
+ let botTable = document.getElementById("botTable");
+ let whosTurn = document.getElementById("whosTurn");
+ userTable.onclick = undefined;
+ [...botTable.children].forEach((tr, trNumber) => {
+ [...tr.children].forEach((td, tdNumber) => {
+ td.onmouseenter = undefined;
+ td.onmouseleave = undefined;
+ td.onclick = undefined;
+ });
+ });
+ let ifContinue = true;
+ if(player.name === "bot")
+ {
+ whosTurn.innerHTML = "Wygrałeś";
+ window.alert("Gratulacje użytkowniku, udało Ci się pokonać naszą zaawansowaną sztuczną inteligencję, Twoje dane zostały do nas wysłane, mozłiwe że niedługo się z Tobą skontaktujemy ze względu na Twoją wybitną inteligencję");
+ document.body.innerHTML = "";
+ window.vars = undefined;
+ startNewGame();
+ }
+ else
+ {
+ updateGameMap(winner);
+ whosTurn.innerHTML = "Przegrałeś, HA HA HA";
+ setTimeout(() => {
+ if(player.name === "user")
+ ifContinue = window.confirm("HA HA HA, przegrałeś, jeśli lubisz marnować czas i spróbować jeszcze raz kliknij OK");
+ if(ifContinue)
+ {
+ document.body.innerHTML = "";
+ window.vars = undefined;
+ startNewGame();
+ }
+ else
+ {
+ document.body.innerHTML = "";
+ window.vars = undefined;
+ let div = document.body.appendChild(document.createElement("div"));
+ div.classList.add("container");
+ div.classList.add("text-center");
+ let h1 = div.appendChild(document.createElement("h1"));
+ h1.innerHTML = "<strong>Przegrałeś HA HA HA</strong>";
+ }
+ }, 5000);
+ }
+}
diff --git a/battleshipFiles/battleshipUIFunctions.js b/battleshipFiles/battleshipUIFunctions.js
new file mode 100644
index 0000000..a80b0f3
--- /dev/null
+++ b/battleshipFiles/battleshipUIFunctions.js
@@ -0,0 +1,173 @@
+function createUI(player, bot, ai)
+{
+ // Creating and appending container
+ let containerFluid = document.createElement("div");
+ containerFluid.className = "container-fluid";
+ containerFluid.id = "container-fluid";
+ document.body.appendChild(containerFluid);
+
+ // Creating and appending row
+ let row = document.createElement("div");
+ row.className = "row";
+ row.id = "row";
+ row.style.marginTop = "10px";
+ containerFluid.appendChild(row);
+
+ // Creating and appending col-2 for ships to insert
+ let colWithOptions = document.createElement("div");
+ colWithOptions.className = "col-2";
+ colWithOptions.id = "colWithOptions";
+ row.appendChild(colWithOptions);
+
+ // Creating and appending ul
+ let ul = document.createElement("ul");
+ ul.className = "ul";
+ ul.id = "ul";
+ colWithOptions.appendChild(ul);
+
+ // Creating col-5 for user game map
+ let colWithUserMap = document.createElement("div");
+ colWithUserMap.className = "col-5";
+ colWithUserMap.id = "colWithUserMap";
+ row.appendChild(colWithUserMap);
+
+ // Creating col-5 for bot game map
+ let colWithBotMap = document.createElement("div");
+ colWithBotMap.className = "col-5";
+ colWithBotMap.id = "colWithBotMap";
+ row.appendChild(colWithBotMap);
+
+ // Creating second row for button
+ let row2 = document.createElement("div");
+ row2.className = "row";
+ row2.id = "row2";
+ row2.style.marginTop = "10px";
+ containerFluid.appendChild(row2);
+
+ // Creating col-12 for button
+ let colWithButton = document.createElement("div");
+ colWithButton.className = "col-12 text-center";
+ colWithButton.id = "colWithButton";
+ row2.appendChild(colWithButton);
+
+ // Creating button that will start da game
+ let button = document.createElement("button");
+ button.type = "button";
+ button.className = "btn btn-success btn-lg font-weight-bolder";
+ button.id = "button";
+ button.style.width = (TABLE_WIDTH / MAP_SIZE * 4).toString() + "vh";
+ button.style.height = (TABLE_WIDTH / MAP_SIZE * 2).toString() + "vh";
+ button.style.fontSize = (TABLE_WIDTH / MAP_SIZE / 2.1).toString() + "vh";
+ button.style.display = "none";
+ button.innerHTML = "Start <em>Da</em> Game";
+ button.onclick = () => startGame(player, bot, ai);
+ colWithButton.appendChild(button);
+
+ // Creating whosTurn sign
+ let whosTurn = document.createElement("h2");
+ whosTurn.innerHTML = "Statek można zdjąć z planszy klikając na niego";
+ whosTurn.style.display = "inline";
+ whosTurn.id = "whosTurn";
+ colWithButton.appendChild(whosTurn);
+}
+
+function generateGameMap(player)
+{
+ let col;
+ if(player.name === "user")
+ col = document.getElementById("colWithUserMap");
+ else
+ col = document.getElementById("colWithBotMap");
+
+ let table = document.createElement("table");
+ table.className = "table table-bordered table-sm";
+ table.id = player.name === "user" ? "userTable" : "botTable";
+ table.style.width = TABLE_WIDTH.toString() + "vh";
+ table.style.height = TABLE_WIDTH.toString() + "vh";
+ table.oncontextmenu = (e) => {e.preventDefault(); e.stopPropagation();};
+ for(let i = 1; i <= MAP_SIZE; i++)
+ {
+ let tr = table.appendChild(document.createElement("tr"));
+ for(let j = 1; j <= MAP_SIZE; j++)
+ {
+ let td = document.createElement("td");
+ td.className = "text-center align-middle font-weight-bold";
+ td.style.width = (TABLE_WIDTH / 10).toString() + "vh";
+ td.style.height = (TABLE_WIDTH / 10).toString() + "vh";
+ td.style.fontSize = (TABLE_WIDTH / 10 / 1.7).toString() + "vh";
+ td.style.padding = '0';
+ td.style.margin = '0';
+ if(player.gameMap[i][j] !== 0 && (player.name === "user" || IM_SPEED))
+ td.classList.add(SHIP_BG_COLOR);
+ else
+ td.classList.add(TABLE_BG_COLOR);
+ tr.appendChild(td);
+ }
+ }
+
+ col.appendChild(table);
+}
+
+function generateShipsUl(player)
+{
+ if(player.name !== "user")
+ throw "Cannot generate ships ul for not user";
+
+ let ul = document.getElementsByTagName("ul")[0];
+ [...ul.children].forEach(li => li.remove());
+
+ if(player.shipsArray.length === 0)
+ return false;
+
+ player.shipsArray.forEach((ship, index) =>
+ {
+ // Generate table/gameMap
+ let li = document.createElement("li");
+ let table = document.createElement("table");
+
+ table.className = "table table-bordered table-sm";
+ table.style.height = (TABLE_WIDTH / MAP_SIZE).toString() + "vh";
+ table.style.width = (TABLE_WIDTH / MAP_SIZE * ship).toString() + "vh";
+ let tr = table.appendChild(document.createElement("tr"));
+
+ for(let i = 0; i < ship; i++)
+ {
+ let td = tr.appendChild(document.createElement("td"));
+ td.className = TABLE_BG_COLOR;
+ td.addEventListener("mouseenter", () =>
+ {
+ if(![...window.vars.selectedShip.children].includes(td))
+ for(let t of [...tr.children])
+ t.className = "bg-light";
+ });
+ td.addEventListener("mouseleave", () =>
+ {
+ if(![...window.vars.selectedShip.children].includes(td))
+ for(let t of [...tr.children])
+ t.className = TABLE_BG_COLOR;
+ });
+ }
+ li.appendChild(table);
+ ul.appendChild(li);
+
+ // Select first ship
+ table.onclick = () => selectShip(tr); // to be able to change selected ship
+ if(index === 0)
+ {
+ window.vars.selectedShip = tr;
+ selectShip(tr);
+ }
+ //return false;
+ });
+}
+
+function selectShip(tr)
+{
+ for(let td of [...window.vars.selectedShip.children])
+ td.className = TABLE_BG_COLOR;
+
+ for(let td of [...tr.children])
+ td.className = SHIP_BG_COLOR;
+
+ window.vars.selectedShip = tr;
+} \ No newline at end of file
diff --git a/battleshipFiles/battleshipUserFunctions.js b/battleshipFiles/battleshipUserFunctions.js
new file mode 100644
index 0000000..86cb12f
--- /dev/null
+++ b/battleshipFiles/battleshipUserFunctions.js
@@ -0,0 +1,97 @@
+function showUserShipPosition(givenTr, givenTrNumber, givenTd, givenTdNumber, player)
+{
+ // Preventing ability to place all ships on one td
+ window.vars.wasShipPlaced = false;
+
+ if(givenTr == null)
+ {
+ if(typeof window.vars.givenTr === "undefined")
+ throw "window.vars.givenTr === undefined";
+ }
+ else
+ {
+ window.vars.givenTr = givenTr;
+ window.vars.givenTd = givenTd;
+ window.vars.givenTrNumber = givenTrNumber;
+ window.vars.givenTdNumber = givenTdNumber;
+ }
+
+ let ship = window.vars.selectedShip.children.length;
+ let newShip = ship;
+
+ if(window.vars.selectedTd === undefined)
+ window.vars.selectedTd = new Array(MAP_SIZE);
+
+ clearUserShipPosition();
+
+ let color;
+ if(checkPositionForShip(givenTrNumber + 1, givenTdNumber + 1, window.vars.shipDirection, ship, player))
+ {
+ color = "bg-success";
+ window.vars.isPlaceable = true;
+ //givenTd.onclick = () => putShipOnGameMap(player, givenTdNumber + 1, givenTrNumber + 1, window.vars.shipDirection, ship, true);
+ }
+ else
+ {
+ color = "bg-danger";
+ window.vars.isPlaceable = false;
+ }
+
+ if(window.vars.shipDirection === "vertically")
+ {
+ if(ship + givenTrNumber > MAP_SIZE)
+ newShip = MAP_SIZE - givenTrNumber;
+
+ for(let i = givenTrNumber - (ship - newShip); i < givenTrNumber + newShip; i++)
+ {
+ let td = givenTr.parentNode.children[i].children[givenTdNumber];
+ window.vars.selectedTd[i] = [td, td.className];
+ td.className = color;
+ }
+ }
+ else if(window.vars.shipDirection === "horizontally")
+ {
+ if(ship + givenTdNumber > MAP_SIZE)
+ newShip = MAP_SIZE - givenTdNumber;
+
+ for(let i = givenTdNumber - (ship - newShip); i < givenTdNumber + newShip; i++)
+ {
+ window.vars.selectedTd[i] = [givenTr.children[i], givenTr.children[i].className];
+ givenTr.children[i].className = color;
+ }
+ }
+ // }
+}
+
+function clearUserShipPosition()
+{
+ // Clear selection from table, used with onMouseLeave
+ window.vars.selectedTd.forEach(oldTd => {
+ if(oldTd !== undefined)
+ oldTd[0].className = oldTd[1];
+ });
+}
+
+function checkPositionForShip(x, y, direction, ship, player)
+{
+ // Changing x and y to match them with start of ship shown with onmouseenter
+ [x, y] = correctXY(x, y, ship, direction);
+
+ if(direction === "vertically")
+ {
+ for(let i = -1; i <= ship; i++)
+ for(let j = -1; j < 2; j++)
+ if(player.gameMap[x + i][y + j] === 1 || player.gameMap[x + i][y + j] === -1)
+ return false;
+ }
+ else if(direction === "horizontally")
+ {
+ for(let i = -1; i <= ship; i++)
+ for(let j = -1; j < 2; j++)
+ if(player.gameMap[x + j][y + i] === 1 || player.gameMap[x + j][y + i] === -1)
+ return false;
+ }
+
+ return true;
+}
+
diff --git a/battleshipFiles/constants.js b/battleshipFiles/constants.js
new file mode 100644
index 0000000..3b9df00
--- /dev/null
+++ b/battleshipFiles/constants.js
@@ -0,0 +1,27 @@
+ const MAP_SIZE = 10;
+ const NUM_OF_4 = 1;
+ const NUM_OF_3 = 2;
+ const NUM_OF_2 = 3;
+ const NUM_OF_1 = 4;
+ const TABLE_WIDTH = 60;
+ const TABLE_BG_COLOR = "bg-secondary";
+ const SHIP_BG_COLOR = "bg-info";
+ const SHIP_HITTED = "❌";
+ const SHIP_MISSED = "✘";
+ const BOT_DELAY = 1000;
+ let REMOVE_WAITING = false; // Cheats
+ let IM_SPEED = false; // Cheats
+ /*
+const MAP_SIZE = 10;
+const NUM_OF_4 = 1;
+const NUM_OF_3 = 0;
+const NUM_OF_2 = 0;
+const NUM_OF_1 = 0;
+const TABLE_WIDTH = 60;
+const TABLE_BG_COLOR = "bg-secondary";
+const SHIP_BG_COLOR = "bg-info";
+const SHIP_HITTED = "❌";
+const SHIP_MISSED = "✘";
+let IM_SPEED = false; // Cheats
+let REMOVE_WAITING = true; // Cheats
+*/ \ No newline at end of file