Compare commits

..

No commits in common. "fd28365c98d583e830829594d3165651f3cd76fc" and "27342f1c2ca9aaa4148f52284ad0d8b64f98027c" have entirely different histories.

22 changed files with 176 additions and 830 deletions

427
index.js
View File

@ -22,14 +22,6 @@ import mysql from 'mysql';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
var packageJSON;
fs.readFile(path.join(__dirname, 'package.json'), function (err, data) {
if (err) throw err;
packageJSON = JSON.parse(data);
});
const app = express();
const flags = process.env.flags ? process.env.flags.split(",") : null;
@ -49,12 +41,6 @@ const redis = createClient();
redis.on('error', err => console.log('Redis Client Error', err));
await redis.connect();
const prefixes = ["game:*", "timer:*", "loginTimer:*"];
prefixes.forEach(prefix => {
redis.eval(`for _,k in ipairs(redis.call('keys', '${prefix}')) do redis.call('del', k) end`, 0);
});
const limiter = rateLimit({
windowMs: 40 * 1000,
limit: 500,
@ -121,19 +107,6 @@ app.get('/privacy', (req, res) => {
});
app.get('/', async (req, res) => {
const locale = new Lang(req.acceptsLanguages());
if (req.session.activeGame && await redis.json.get(req.session.activeGame)) {
res.render("error", {
helpers: {
error: "Your account is currently taking part in a game from another session",
fallback: "/",
t: (key) => { return locale.t(key) }
}
});
return;
}
let login = loginState(req);
if (login == 0) {
@ -170,8 +143,7 @@ app.get('/', async (req, res) => {
res.render('index', {
helpers: {
t: (key) => { return locale.t(key) },
ver: packageJSON.version
t: (key) => { return locale.t(key) }
}
});
} else {
@ -192,8 +164,7 @@ app.get('/', async (req, res) => {
res.render('index', {
helpers: {
t: (key) => { return locale.t(key) },
ver: packageJSON.version
t: (key) => { return locale.t(key) }
}
});
});
@ -284,7 +255,7 @@ app.post('/api/login', (req, res) => {
res.render("error", {
helpers: {
error: "Unknown login error occured",
error: "Wystąpił nieznany błąd logowania",
fallback: "/login",
t: (key) => { return locale.t(key) }
}
@ -296,7 +267,7 @@ app.post('/api/login', (req, res) => {
res.render("error", {
helpers: {
error: "Wrong e-mail address",
error: "Niepoprawny adres e-mail",
fallback: "/login",
t: (key) => { return locale.t(key) }
}
@ -318,7 +289,7 @@ app.post('/api/auth', async (req, res) => {
res.render("error", {
helpers: {
error: "Wrong authorisation code",
error: "Niepoprawny kod logowania",
fallback: "/auth",
t: (key) => { return locale.t(key) }
}
@ -329,7 +300,7 @@ app.post('/api/auth', async (req, res) => {
res.render("error", {
helpers: {
error: "Wrong authorisation code",
error: "Niepoprawny kod logowania",
fallback: "/login",
t: (key) => { return locale.t(key) }
}
@ -338,18 +309,16 @@ app.post('/api/auth', async (req, res) => {
});
app.post('/api/nickname', (req, res) => {
if (loginState(req) == 2 && req.body.nickname != null && 3 <= req.body.nickname.length && req.body.nickname.length <= 16) {
if (loginState(req) == 2 && req.session.nickname == null && req.body.nickname != null && 3 <= req.body.nickname.length && req.body.nickname.length <= 16) {
req.session.nickname = req.body.nickname;
req.session.activeGame = null;
auth.setNickname(req.session.userId, req.body.nickname).then(() => {
res.redirect('/');
});
} else {
const locale = new Lang(req.acceptsLanguages());
res.render("error", {
helpers: {
error: "The nickname does not meet the requirements: length from 3 to 16 characters",
error: "Nazwa nie spełnia wymogów: Od 3 do 16 znaków, nie może być pusta",
fallback: "/nickname",
t: (key) => { return locale.t(key) }
}
@ -358,22 +327,11 @@ app.post('/api/nickname', (req, res) => {
});
app.get('/game', async (req, res) => {
const game = await redis.json.get(`game:${req.query.id}`);
// if (req.session.activeGame) {
// res.render("error", {
// helpers: {
// error: "Your account is currently taking part in a game from another session",
// fallback: "/",
// t: (key) => { return locale.t(key) }
// }
// });
// return;
// }
if (req.session.nickname == null) {
res.redirect('/setup');
} else if (!req.query.id || !game || !req.session.activeGame || req.session.activeGame !== req.query.id) {
} else if (req.query.id == null || game == null || game.state == 'expired' || req.session.activeGame == null) {
auth.getLanguage(req.session.userId).then(language => {
var locale;
if (language) {
@ -386,7 +344,7 @@ app.get('/game', async (req, res) => {
res.render("error", {
helpers: {
error: "The specified game was not found",
error: "Nie znaleziono wskazanej gry",
fallback: "/",
t: (key) => { return locale.t(key) }
}
@ -519,7 +477,7 @@ io.on('connection', async (socket) => {
});
}
if (!await GInfo.isPlayerInGame(socket) && session.nickname) {
if (!await GInfo.isPlayerInGame(socket) && session.nickname != null) {
// if (session.nickname == null) {
// socket.disconnect();
// return;
@ -618,7 +576,6 @@ io.on('connection', async (socket) => {
// Teraz utwórz objekt partii w trakcie w bazie Redis
const gameId = uuidv4();
redis.json.set(`game:${gameId}`, '$', {
type: 'pvp',
hostId: opp.request.session.userId,
state: "pregame",
startTs: (new Date()).getTime() / 1000,
@ -671,10 +628,6 @@ io.on('connection', async (socket) => {
const s = io.sockets.sockets.get(sid);
s.leave(msg);
});
GInfo.timer(gameId, 60, () => {
AFKEnd(gameId);
});
} else {
callback({
status: "alreadyInLobby",
@ -683,83 +636,6 @@ io.on('connection', async (socket) => {
}
});
socket.on('create pve', (difficulty, callback) => {
if (socket.rooms.size === 1) {
callback({
status: "ok"
});
switch (difficulty) {
case 'simple':
difficulty = 0;
break;
case 'smart':
difficulty = 1;
break;
case 'overkill':
difficulty = 2;
break;
default:
difficulty = 1;
break;
}
// Teraz utwórz objekt partii w trakcie w bazie Redis
const gameId = uuidv4();
redis.json.set(`game:${gameId}`, '$', {
type: 'pve',
difficulty: difficulty,
hostId: session.userId,
state: "pregame",
startTs: (new Date()).getTime() / 1000,
ready: [false, true],
boards: [
{
ships: [],
shots: [],
stats: {
shots: 0,
hits: 0,
placedShips: 0,
sunkShips: 0,
},
},
{
ships: [],
shots: [],
stats: {
shots: 0,
hits: 0,
placedShips: 0,
sunkShips: 0,
},
}
],
nextPlayer: 0,
});
session.reload((err) => {
if (err) return socket.disconnect();
session.activeGame = gameId;
session.save();
});
socket.emit("gameReady", gameId);
GInfo.timer(gameId, 60, () => {
AFKEnd(gameId);
});
} else {
callback({
status: "alreadyInLobby",
});
}
});
socket.on('logout', () => {
session.destroy();
});
@ -769,7 +645,7 @@ io.on('connection', async (socket) => {
io.to(socket.rooms[1]).emit("player left");
}
});
} else if (session.nickname && (await GInfo.getPlayerGameData(socket)).data.type === "pvp") {
} else if (session.nickname != null) {
const playerGame = await GInfo.getPlayerGameData(socket);
if (playerGame.data.state === 'pregame') {
@ -803,8 +679,6 @@ io.on('connection', async (socket) => {
AFKEnd(playerGame.id);
});
}
} else {
socket.disconnect();
}
socket.on('ready', async (callback) => {
@ -901,7 +775,7 @@ io.on('connection', async (socket) => {
if (bships.checkTurn(playerGame.data, session.userId)) {
const enemyIdx = session.userId === playerGame.data.hostId ? 1 : 0;
let hit = await GInfo.shootShip(socket, enemyIdx, posX, posY);
let hit = await GInfo.shootShip(socket, posX, posY);
await redis.json.arrAppend(`game:${playerGame.id}`, `.boards[${enemyIdx}].shots`, { posX: posX, posY: posY });
await GInfo.incrStat(socket, 'shots');
@ -950,7 +824,7 @@ io.on('connection', async (socket) => {
} else if (hit.status === -1) {
const locale = new Lang(session.langs);
socket.emit("toast", locale.t("board.You have already shot at this field"));
socket.emit("toast", locale.t("You have already shot at this field"));
return;
}
@ -963,223 +837,6 @@ io.on('connection', async (socket) => {
}
});
socket.on('disconnecting', async () => {
const playerGame = await GInfo.getPlayerGameData(socket);
if (playerGame !== null) {
AFKEnd(playerGame.id);
await GInfo.resetTimer(playerGame.id);
}
});
} else if (session.nickname && (await GInfo.getPlayerGameData(socket)).data.type === "pve") {
const playerGame = await GInfo.getPlayerGameData(socket);
if (playerGame.data.state === 'pregame') {
socket.join(playerGame.id);
if (io.sockets.adapter.rooms.get(playerGame.id).size === 1) {
GInfo.resetTimer(playerGame.id);
io.to(playerGame.id).emit('players ready');
socket.emit('player idx', 0);
let UTCTs = Math.floor((new Date()).getTime() / 1000 + 180);
io.to(playerGame.id).emit('turn update', { turn: 0, phase: "preparation", timerToUTC: UTCTs });
GInfo.timer(playerGame.id, 180, async () => {
finishPrepPhase(socket, playerGame);
placeAIShips(socket);
});
await redis.json.set(`game:${playerGame.id}`, '$.state', "preparation");
} else if (io.sockets.adapter.rooms.get(playerGame.id).size > 2) {
socket.disconnect();
}
} else {
socket.disconnect();
}
socket.on('ready', async (callback) => {
if (!(callback && typeof callback === 'function')) {
return;
}
const playerGame = await GInfo.getPlayerGameData(socket);
const playerIdx = 0;
const userNotReady = !playerGame.data.ready[playerIdx];
if (playerGame && playerGame.data.state === 'preparation' && userNotReady) {
await GInfo.setReady(socket);
const playerGame = await GInfo.getPlayerGameData(socket);
if (playerGame.data.ready[0] && playerGame.data.ready[1]) {
// Both set ready
await GInfo.resetTimer(playerGame.id);
callback();
await finishPrepPhase(socket, playerGame);
await placeAIShips(socket);
}
}
});
socket.on('place ship', async (type, posX, posY, rot) => {
const playerGame = await GInfo.getPlayerGameData(socket);
if (type < 0 || type > 3) {
return;
}
if (playerGame && playerGame.data.state === 'preparation') {
const playerShips = await GInfo.getPlayerShips(socket);
let canPlace = bships.validateShipPosition(playerShips, type, posX, posY, rot);
let shipAvailable = bships.getShipsAvailable(playerShips)[type] > 0;
if (!canPlace) {
const locale = new Lang(session.langs);
socket.emit("toast", locale.t("board.You cannot place a ship like this"));
} else if (!shipAvailable) {
const locale = new Lang(session.langs);
socket.emit("toast", locale.t("board.You have ran out of ships of that type"));
} else {
await GInfo.placeShip(socket, { type: type, posX: posX, posY: posY, rot: rot, hits: Array.from(new Array(type + 1), () => false) });
socket.emit("placed ship", { type: type, posX: posX, posY: posY, rot: rot });
await GInfo.incrStat(socket, 'placedShips');
}
}
});
socket.on('remove ship', async (posX, posY) => {
const playerGame = await GInfo.getPlayerGameData(socket);
if (playerGame && playerGame.data.state === 'preparation') {
const deletedShip = await GInfo.removeShip(socket, posX, posY);
socket.emit("removed ship", { posX: posX, posY: posY, type: deletedShip.type });
await GInfo.incrStat(socket, 'placedShips', -1);
}
});
socket.on('shoot', async (posX, posY) => {
let playerGame = await GInfo.getPlayerGameData(socket);
if (playerGame && playerGame.data.state === 'action') {
if (bships.checkTurn(playerGame.data, session.userId)) {
const enemyIdx = 1;
let hit = await GInfo.shootShip(socket, enemyIdx, posX, posY);
await redis.json.arrAppend(`game:${playerGame.id}`, `.boards[${enemyIdx}].shots`, { posX: posX, posY: posY });
await GInfo.incrStat(socket, 'shots');
if (!hit.status) {
socket.emit("shot missed", enemyIdx, posX, posY);
} else if (hit.status === 1) {
socket.emit("shot hit", enemyIdx, posX, posY);
await GInfo.incrStat(socket, 'hits');
} else if (hit.status === 2) {
socket.emit("shot hit", enemyIdx, posX, posY);
await GInfo.incrStat(socket, 'hits');
io.to(playerGame.id).emit("ship sunk", enemyIdx, hit.ship);
await GInfo.incrStat(socket, 'sunkShips');
if (hit.gameFinished) {
let hostNickname = session.nickname;
let difficulty;
switch (playerGame.data.difficulty) {
case 0:
difficulty = "simple";
break;
case 1:
difficulty = "smart";
break;
case 2:
difficulty = "overkill";
break;
}
let guestNickname = `AI (${difficulty})`;
socket.emit("game finished", 0, guestNickname);
playerGame = await GInfo.getPlayerGameData(socket);
auth.saveMatch(playerGame.id, (new Date).getTime() / 1000 - playerGame.data.startTs, "pve", session.userId, '77777777-77777777-77777777-77777777', playerGame.data.boards, 1, difficulty);
GInfo.resetTimer(playerGame.id);
endGame(playerGame.id);
return;
}
} else if (hit.status === -1) {
const locale = new Lang(session.langs);
socket.emit("toast", locale.t("board.You have already shot at this field"));
return;
}
await GInfo.passTurn(socket);
[posX, posY] = await GInfo.makeAIMove(socket, playerGame.difficulty);
hit = await GInfo.shootShip(socket, 0, posX, posY);
await redis.json.arrAppend(`game:${playerGame.id}`, `.boards[0].shots`, { posX: posX, posY: posY });
await GInfo.incrStat(socket, 'shots', 1, 1);
if (!hit.status) {
socket.emit("shot missed", 0, posX, posY);
} else if (hit.status === 1) {
socket.emit("shot hit", 0, posX, posY);
await GInfo.incrStat(socket, 'hits', 1, 1);
} else if (hit.status === 2) {
socket.emit("shot hit", 0, posX, posY);
await GInfo.incrStat(socket, 'hits', 1, 1);
socket.emit("ship sunk", 0, hit.ship);
await GInfo.incrStat(socket, 'sunkShips', 1, 1);
if (hit.gameFinished) {
let difficulty;
switch (playerGame.data.difficulty) {
case 0:
difficulty = "simple";
break;
case 1:
difficulty = "smart";
break;
case 2:
difficulty = "overkill";
break;
}
let guestNickname = `AI (${difficulty})`;
socket.emit("game finished", 1, guestNickname);
playerGame = await GInfo.getPlayerGameData(socket);
auth.saveMatch(playerGame.id, (new Date).getTime() / 1000 - playerGame.data.startTs, "pve", session.userId, '77777777-77777777-77777777-77777777', playerGame.data.boards, 0, difficulty);
GInfo.resetTimer(playerGame.id);
endGame(playerGame.id);
return;
}
}
await GInfo.passTurn(socket);
GInfo.resetTimer(playerGame.id);
GInfo.timer(playerGame.id, 30, () => {
AFKEnd(playerGame.id);
});
}
}
});
socket.on('disconnecting', async () => {
const playerGame = await GInfo.getPlayerGameData(socket);
if (playerGame !== null) {
@ -1219,7 +876,7 @@ function endGame(gameId) {
}
}
redis.unlink(`game:${gameId}`);
redis.json.del(`game:${gameId}`);
}
function AFKEnd(gameId) {
@ -1227,34 +884,6 @@ function AFKEnd(gameId) {
endGame(gameId);
}
async function finishPrepPhase(socket, playerGame) {
await GInfo.endPrepPhase(socket);
const members = [...roomMemberIterator(playerGame.id)];
for (let i = 0; i < members.length; i++) {
const sid = members[i][0];
const socket = io.sockets.sockets.get(sid);
let placedShips = await GInfo.depleteShips(socket);
placedShips.forEach(shipData => {
socket.emit("placed ship", shipData)
});
if (placedShips.length > 0) {
const locale = new Lang(socket.session.langs);
socket.emit("toast", locale.t("board.Your remaining ships have been randomly placed"))
}
}
GInfo.timer(playerGame.id, 30, () => {
AFKEnd(playerGame.id);
});
}
async function placeAIShips(socket, playerGame) {
await GInfo.depleteShips(socket, 1);
}
function roomMemberIterator(id) {
return io.sockets.adapter.rooms.get(id) == undefined ? null : io.sockets.adapter.rooms.get(id).entries();
}
@ -1298,3 +927,27 @@ function checkFlag(key) {
return false;
}
}
async function finishPrepPhase(socket, playerGame) {
await GInfo.endPrepPhase(socket);
const members = [...roomMemberIterator(playerGame.id)];
for (let i = 0; i < members.length; i++) {
const sid = members[i][0];
const socket = io.sockets.sockets.get(sid);
let placedShips = await GInfo.depleteShips(socket);
placedShips.forEach(shipData => {
socket.emit("placed ship", shipData)
});
if (placedShips.length > 0) {
const locale = new Lang(socket.session.langs);
socket.emit("toast", locale.t("board.Your remaining ships have been randomly placed"))
}
}
GInfo.timer(playerGame.id, 30, () => {
AFKEnd(playerGame.id);
});
}

View File

@ -65,22 +65,6 @@
"You will be redirected soon": "You will be redirected soon",
"Opponent:": "Opponent"
},
"PvE": {
"Create": "PvE / Create",
"Choose the difficulty mode": "Choose the difficulty mode",
"difficulty": {
"Simple": {
"description": "In this mode, the bot is just randomly shooting at fields, without any intelligence."
},
"Smart": {
"description": "In this mode, the bot understands the rules of the game and will try to predict where your ships could be and knows where they couldn't."
},
"Overkill": {
"description": "This mode is an absolute overkill - the bot knows exact positions of all your ships and will shoot at them in random order with 100% accuracy. To win in this mode, you need to have 100% accuracy for the entire game."
}
},
"Begin": "Begin"
},
"Profile": {
"Loading": "Loading...",
"Player since:": "Player since:",
@ -94,12 +78,7 @@
},
"Settings": {
"General": "General",
"Account": "Account",
"Log out": "Log out",
"Current nickname:": "Current nickname:",
"Change nickname": "Change nickname"
"Log out": "Log out"
},
"General": {
"Unknown error occured": "Unknown error occured",
@ -144,7 +123,7 @@
"Four-masted": "Four-masted",
"Available:": "Available:",
"To sunk": "To sunk",
"Sunk ships": "Sunk ships",
"Single-mastedPlu": "Single-masted:",
"Two-mastedPlu": "Two-masted:",
"Three-mastedPlu": "Three-masted:",

View File

@ -65,22 +65,6 @@
"You will be redirected soon": "Wkrótce nastąpi przekierowanie",
"Opponent:": "Przeciwnik"
},
"PvE": {
"Create": "PvE / Stwórz",
"Choose the difficulty mode": "Wybierz tryb trudności",
"difficulty": {
"Simple": {
"description": "W tym trybie, bot po prostu losowo strzela w pola, bez żadnej inteligencji."
},
"Smart": {
"description": "W tym trybie, bot rozumie zasady gry i próbuje przewidywać gdzie Twoje statki mogą być oraz wie gdzie ich na pewno nie ma. Jest to tryb najbardziej zbliżony to przeciętnego gracza."
},
"Overkill": {
"description": "Ten tryb to kompletna przesada - bot zna dokładne pozycje wszystkich Twoich statków i będzie strzelał do nich w losowej kolejności ze 100% celnością. By wygrać na tym trybie, musisz mieć 100% celność przez całą grę."
}
},
"Begin": "Rozpocznij"
},
"Profile": {
"Loading": "Wczytywanie...",
"Player since:": "Gracz od:",
@ -95,12 +79,7 @@
},
"Settings": {
"General": "Ogólne",
"Account": "Konto",
"Log out": "Wyloguj się",
"Current nickname:": "Aktualny nickname:",
"Change nickname": "Zmień nickname"
"Log out": "Wyloguj się"
},
"General": {
"Unknown error occured": "Wystąpił nieznany błąd",
@ -145,7 +124,7 @@
"Four-masted": "Czteromasztowiec",
"Available:": "Dostępne:",
"To sunk": "Do zatopienia",
"Sunk ships": "Zatopione statki",
"Single-mastedPlu": "Jednomasztowce:",
"Two-mastedPlu": "Dwumasztowce:",
"Three-mastedPlu": "Trójmasztowce:",

View File

@ -1,6 +1,6 @@
{
"name": "statki-backend",
"version": "0.7.4",
"version": "0.7.0",
"description": "Backend do gry w statki",
"main": "index.js",
"type": "module",

View File

@ -108,12 +108,13 @@ nav span:hover {
}
#pvpCreateView .modes div {
height: 17rem;
width: 15rem;
background-color: black;
border: solid 1px white;
border-radius: 15px;
user-select: none;
padding: 2rem 3rem;
padding: 1rem 3rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
@ -350,30 +351,6 @@ nav span:hover {
text-decoration: underline;
}
#settingsView .versionInfo {
margin-top: 3rem;
font-family: 'Roboto Mono', monospace;
font-size: 15px;
}
#settingsView button {
background-color: black;
color: white;
border-radius: 15px;
border: 1px solid white;
text-align: center;
padding: 0.5rem 2rem;
outline: none;
cursor: pointer;
font-size: 1rem;
transition: all 0.3s;
}
#settingsView button:hover {
background-color: white;
color: black;
}
#logout {
color: var(--danger);
cursor: pointer;
@ -384,60 +361,3 @@ nav span:hover {
#logout:hover {
opacity: 0.6;
}
/* PvE */
#vsAiView .modes {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 2rem;
}
#vsAiView .modes div {
/* height: 7rem; */
width: 15rem;
background-color: black;
border: solid 1px white;
border-radius: 15px;
user-select: none;
padding: 2rem 3rem;
}
#vsAiView form {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
#vsAiView form input {
background-color: black;
color: white;
border-radius: 15px;
border: 1px solid white;
font-size: 1.5rem;
text-align: center;
padding: 0.5rem 2rem;
outline: none;
}
#vsAiView form input[type=submit] {
cursor: pointer;
font-size: 1rem;
transition: all 0.3s;
}
#vsAiView form input[type=submit]:hover {
background-color: white;
color: black;
}
#vsAiView select {
padding: 0.5rem 1rem;
padding: 0.5rem 2rem;
font-size: 1rem;
background-color: black;
border: solid 1px white;
color: white;
border-radius: 15px;
outline: none;
}

View File

@ -17,6 +17,7 @@
@media only screen and (max-width: 820px) {
#pvpCreateView .modes div {
max-width: 90vw;
height: 19rem;
padding: 2rem 1.5rem;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

View File

@ -22,18 +22,20 @@ class Battleships {
}
getField(x, y) {
console.log(x, y);
if (0 <= x && x < this.boardSize && 0 <= y && y <= this.boardSize) {
return $(`#board .row:nth-child(${y + 1}) .field:nth-child(${x + 1})`);
if (0 <= x && x < this.boardSize && 0 <= y && y < this.boardSize) {
x++;
y++;
return $(`#board .row:nth-child(${y}) .field:nth-child(${x})`);
} else {
throw new RangeError("getField position out of range.");
}
}
getFieldSecondary(x, y) {
console.log(x, y);
if (0 <= x && x < this.boardSize && 0 <= y && y <= this.boardSize) {
return $(`#secondaryBoard .row:nth-child(${y + 1}) .field:nth-child(${x + 1})`);
if (0 <= x && x < this.boardSize && 0 <= y && y < this.boardSize) {
x++;
y++;
return $(`#secondaryBoard .row:nth-child(${y}) .field:nth-child(${x})`);
} else {
throw new RangeError("getField position out of range.");
}

View File

@ -4,39 +4,37 @@ String.prototype.replaceAt = function (index, replacement) {
const socket = io();
// Temporarily commented out, as it causes huge graphical glitches
const charset = ["0", "1", "!", "@", "#", "$", "%", "&"];
// const charset = ["0", "1", "!", "@", "#", "$", "%", "&"];
const initialContent = $("#scrolldowntext").html();
// const initialContent = $("#scrolldowntext").html();
setInterval(() => {
var content = $("#scrolldowntext").html();
const len = content.length;
// setInterval(() => {
// var content = $("#scrolldowntext").html();
// const len = content.length;
for (let i = 0; i < len; i++) {
const duration = Math.random() * 20 + 40;
// for (let i = 0; i < len; i++) {
// const duration = Math.random() * 20 + 40;
setTimeout(() => {
let previousChar = content.charAt(i);
// setTimeout(() => {
// let previousChar = content.charAt(i);
let randomChar = charset[Math.floor(Math.random() * charset.length)];
content = content.replaceAt(i, randomChar);
// let randomChar = charset[Math.floor(Math.random() * charset.length)];
// content = content.replaceAt(i, randomChar);
$("#scrolldowntext").html(content);
// $("#scrolldowntext").html(content);
setTimeout(() => {
content = content.replaceAt(i, previousChar);
$("#scrolldowntext").html(content);
// setTimeout(() => {
// content = content.replaceAt(i, previousChar);
// $("#scrolldowntext").html(content);
// if (i == len - 1) {
// content = initialContent;
// $("#scrolldowntext").html(initialContent);
// }
// }, duration * len + duration * i);
// }, duration * i);
// }
// }, 5000);
if (i == len - 1) {
content = initialContent;
$("#scrolldowntext").html(initialContent);
}
}, duration * len + duration * i);
}, duration * i);
}
}, 5000);
document.addEventListener("wheel", (event) => {
if (event.deltaY > 0) {

View File

@ -1,4 +1,4 @@
const statki = "statki-by-maciejka-0.7.4";
const statki = "statki-by-maciejka-0.7.0";
const assets = [
"/favicon.ico",
"/assets/css/landing.css",
@ -23,4 +23,3 @@ self.addEventListener("install", installEvent => {
})
);
});

View File

@ -50,9 +50,11 @@ if ($(window).width() <= 820) {
}
$('#board .field').on('click', function () {
if (new Date().getTime() / 1000 - lastTimeClick > 0.3 && $(window).width() > 820 && !postPrep) {
socket.emit("place ship", selectedShip, $(this).data('pos-x'), $(this).data('pos-y'), shipRotation);
lastTimeClick = new Date().getTime() / 1000;
if (new Date().getTime() / 1000 - lastTimeClick > 0.3) {
if ($(window).width() > 820) {
socket.emit("place ship", selectedShip, $(this).data('pos-x'), $(this).data('pos-y'), shipRotation);
lastTimeClick = new Date().getTime() / 1000;
}
}
});
@ -64,9 +66,11 @@ function manualPlace(posX, posY) {
}
$('#secondaryBoard .field').on('click', function () {
if (new Date().getTime() / 1000 - lastTimeClick > 0.3 && $(window).width() > 820 && myTurn) {
socket.emit("shoot", $(this).data('pos-x'), $(this).data('pos-y'));
lastTimeClick = new Date().getTime() / 1000;
if (new Date().getTime() / 1000 - lastTimeClick > 0.3) {
if ($(window).width() > 820) {
socket.emit("shoot", $(this).data('pos-x'), $(this).data('pos-y'));
lastTimeClick = new Date().getTime() / 1000;
}
}
});
@ -174,7 +178,7 @@ socket.on("ship sunk", (victimIdx, ship) => {
break;
}
let l = ship.type + 1;
let l = !ship.type ? ship.type + 1 : ship.type + 2;
if (victimIdx === playerIdx) {
for (let i = 0; i < l; i++) {
setTimeout(() => {
@ -328,10 +332,10 @@ function getAccuracy() {
}
function updateShipsSunk() {
$("#singlemasted").html(4 - shipsSunk[0]);
$("#twomasted").html(3 - shipsSunk[1]);
$("#threemasted").html(2 - shipsSunk[2]);
$("#fourmasted").html(1 - shipsSunk[3]);
$("#singlemasted").html(shipsSunk[0]);
$("#twomasted").html(shipsSunk[1]);
$("#threemasted").html(shipsSunk[2]);
$("#fourmasted").html(shipsSunk[3]);
}
function readyUp() {

View File

@ -7,15 +7,16 @@ socket.on("joined", (nick) => {
returnLock = false;
lockUI(true);
$("#oppNameField").html(nick);
lockUI(false);
switchView("preparingGame");
lockUI(false);
console.log("Player joined the game:", nick);
});
socket.on("player left", () => {
lockUI(false);
lockUI(true);
switchView("mainMenuView");
lockUI(false);
console.log("Player left the game");
});
@ -61,12 +62,11 @@ $("#languages").on("change", function() {
socket.emit("my profile", (profile) => {
console.log("Received user data. UID:", profile.uid);
console.log("Profile data:", profile);
// General profile data
let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
$("#playerSince").html(new Date(profile.profile.account_creation).toLocaleDateString(undefined, options));
$(".nickname").html(profile.profile.nickname);
$("#nickname").html(profile.profile.nickname);
// Profile stats
$("#monthlyPlayed").html(profile.stats.monthly_matches);
@ -89,8 +89,7 @@ socket.emit("my profile", (profile) => {
const duration = `${minutes}:${seconds}`;
console.log(match);
matchHistoryDOM += `<div class="match" data-matchid="${match.match_id}"><div><h1 class="dynamic${match.won === 1 ? "" : " danger"}">${match.won === 1 ? window.locale["Victory"] : window.locale["Defeat"]}</h1><span> vs. ${match.match_type === "pvp" ? match.opponent : "<span class=\"important\">AI ("+match.ai_type+")</span>"}</span></div><h2 class="statsButton">${window.locale["Click to view match statistics"]}</h2><span>${date}</span><br><span>${duration}</span></div>`;
matchHistoryDOM += `<div class="match" data-matchid="${match.match_id}"><div><h1 class="dynamic${match.won === 1 ? "" : " danger"}">${match.won === 1 ? window.locale["Victory"] : window.locale["Defeat"]}</h1><span> vs. ${match.match_type === "pvp" ? match.opponent : "AI"}</span></div><h2 class="statsButton">${window.locale["Click to view match statistics"]}</h2><span>${date}</span><br><span>${duration}</span></div>`;
}
if (!matchHistoryDOM) {
@ -141,41 +140,25 @@ $("#leaveGameButton").on("click", function () {
window.location.reload();
});
$("#pvpMenuButton").on("click", function () {
switchView('pvpMenuView');
});
$("#logout").on("click", function() {
lockUI(true);
socket.emit("logout");
window.location.reload();
});
$("#pveDifficulty").on("change", function() {
switch (this.value) {
case 'simple':
$('#difficultyDescription').html(locale["Simple description"]);
break;
const form = document.getElementById('pvpJoinForm');
const input = document.getElementById('pvpJoinCode');
case 'smart':
$('#difficultyDescription').html(locale["Smart description"]);
break;
case 'overkill':
$('#difficultyDescription').html(locale["Overkill description"]);
break;
default:
$('#difficultyDescription').html('');
break;
}
});
const joinForm = document.getElementById('pvpJoinForm');
const joinCodeInput = document.getElementById('pvpJoinCode');
joinForm.addEventListener('submit', (e) => {
form.addEventListener('submit', (e) => {
e.preventDefault();
if (joinCodeInput.value && joinCodeInput.value.length === 6) {
if (input.value && input.value.length === 6) {
lockUI(true);
console.log("Joining a lobby with code:", joinCodeInput.value);
socket.emit("join lobby", joinCodeInput.value, (response) => {
console.log("Joining a lobby with code:", input.value);
socket.emit("join lobby", input.value, (response) => {
switch (response.status) {
case "ok":
console.log("Joined a lobby by:", response.oppNickname);
@ -191,41 +174,6 @@ joinForm.addEventListener('submit', (e) => {
break;
}
});
joinCodeInput.value = '';
input.value = '';
}
});
const pveForm = document.getElementById('pveCreateForm');
const pveDifficulty = document.getElementById('pveDifficulty').value;
pveForm.addEventListener('submit', (e) => {
e.preventDefault();
if (pveDifficulty) {
lockUI(true);
console.log("Creating a PvE game with difficulty:", pveDifficulty);
socket.emit("create pve", pveDifficulty, (response) => {
switch (response.status) {
case "ok":
console.log("Joined a PvE lobby: ", response.oppNickname);
$("#oppNameField").html(`AI (${pveDifficulty})`);
lockUI(false);
switchView("preparingGame");
break;
default:
alert(`${window.locale["Unknown error occured"]}\n${window.locale["Status:"]} ${response.status}`);
lockUI(false);
switchView("mainMenuView");
break;
}
});
joinCodeInput.value = '';
}
});
// const isInStandaloneMode = () =>
// (window.matchMedia('(display-mode: standalone)').matches) || (window.navigator.standalone) || document.referrer.includes('android-app://');
// if (isInStandaloneMode()) {
// alert("Thanks for using the PWA!");
// }

View File

@ -34,13 +34,15 @@ const initialURLParams = new URLSearchParams(window.location.search);
const initialPath = initialURLParams.get('path');
window.addEventListener("load", () => {
if (initialPath != null) {
let elem = document.querySelector(`.container[data-path="${initialPath}"]:not(.container[data-pathlock])`);
// if (initialPath != null) {
// let elem = document.querySelector(`.container[data-path="${initialPath}"]`);
if (elem != null) {
switchView(elem.id, true);
}
}
// if (elem != null) {
// switchView(elem.id, true);
// }
// } else {
// switchView("mainMenuView");
//}
});
addEventListener("popstate", (event) => {

View File

@ -1,7 +1,7 @@
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker
.register("/assets/js/service-worker.js")
.register("/serviceWorker.js")
.then(res => console.log("Service worker registered"))
.catch(err => console.log("Service worker not registered", err));
});

View File

@ -4,7 +4,7 @@
"start_url": "/",
"background_color": "black",
"theme_color": "black",
"orientation": "any",
"orientation": "landscape",
"icons": [
{
"src": "/assets/img/statki-logo-crop.png",
@ -50,27 +50,6 @@
"type": "image/png",
"form_factor": "wide",
"label": "Preparation phase"
},
{
"src": "/assets/img/screenshot_mainmenu_mobile.png",
"sizes": "1082x2402",
"type": "image/png",
"form_factor": "narrow",
"label": "Main menu screen"
},
{
"src": "/assets/img/screenshot_profile_mobile.png",
"sizes": "1082x2402",
"type": "image/png",
"form_factor": "narrow",
"label": "Profile view"
},
{
"src": "/assets/img/screenshot_create_mobile.png",
"sizes": "1082x2402",
"type": "image/png",
"form_factor": "narrow",
"label": "Create game screen"
}
],
"display": "standalone"

View File

@ -30,40 +30,24 @@ export class MailAuth {
}
async timer(tId, time, callback) {
let timerEnd = new Date().getTime() / 1000 + time;
await this.redis.set(`loginTimer:${tId}`, new Date().getTime() / 1000);
let localLastUpdate = await this.redis.get(`loginTimer:${tId}`);
await this.redis.set(`loginTimer:${tId}`, timerEnd);
let timeout = setTimeout(callback, time * 1000);
let interval = setInterval(async () => {
if (new Date().getTime() < timerEnd) {
if (timeout._destroyed) {
clearInterval(interval);
callback();
return;
}
let lastUpdate = await this.redis.get(`loginTimer:${tId}`);
if (timerEnd != lastUpdate) {
if (localLastUpdate != lastUpdate) {
clearTimeout(timeout);
clearInterval(interval);
return;
}
}, 1000);
// let timeout = setTimeout(callback, time * 1000);
// let interval = setInterval(async () => {
// if (timeout._destroyed) {
// clearInterval(interval);
// return;
// }
// let lastUpdate = await this.redis.get(`loginTimer:${tId}`);
// if (localLastUpdate != lastUpdate) {
// clearTimeout(timeout);
// clearInterval(interval);
// return;
// }
// }, 200);
}, 200);
}
async resetTimer(tId) {
@ -149,7 +133,7 @@ export class MailAuth {
await this.redis.set(`codeAuth:${authCode}`, row.user_id);
await this.timer(row.user_id, 600, async () => {
await this.redis.unlink(`codeAuth:${authCode}`);
await this.redis.json.del(`codeAuth:${authCode}`);
});
authCode = authCode.slice(0, 4) + " " + authCode.slice(4);
@ -189,7 +173,7 @@ export class MailAuth {
await this.redis.set(`codeAuth:${authCode}`, row.user_id);
await this.timer(row.user_id, 600, async () => {
await this.redis.unlink(`codeAuth:${authCode}`);
await this.redis.json.del(`codeAuth:${authCode}`);
});
authCode = authCode.slice(0, 4) + " " + authCode.slice(4);
@ -221,10 +205,10 @@ export class MailAuth {
});
}
saveMatch(matchId, duration, type, hostId, guestId, boards, winnerIdx, aitype = null) {
saveMatch(matchId, duration, type, hostId, guestId, boards, winnerIdx) {
return new Promise((resolve, reject) => {
const conn = mysql.createConnection(this.mysqlOptions);
conn.query(`INSERT INTO matches(match_id, match_type, host_id, guest_id, duration${aitype == null ? "" : ", ai_type"}) VALUES (${conn.escape(matchId)}, ${conn.escape(type)}, ${conn.escape(hostId)}, ${conn.escape(guestId)}, ${conn.escape(duration)}${aitype == null ? "" : ", " + conn.escape(aitype)})`, async (error) => {
conn.query(`INSERT INTO matches(match_id, match_type, host_id, guest_id, duration) VALUES (${conn.escape(matchId)}, ${conn.escape(type)}, ${conn.escape(hostId)}, ${conn.escape(guestId)}, ${conn.escape(duration)})`, async (error) => {
if (error) reject(error);
else conn.query(`INSERT INTO statistics(match_id, user_id, board, won) VALUES (${conn.escape(matchId)}, ${conn.escape(hostId)}, ${conn.escape(JSON.stringify(boards[0]))}, ${conn.escape(winnerIdx ? 1 : 0)}), (${conn.escape(matchId)}, ${conn.escape(guestId)}, ${conn.escape(JSON.stringify(boards[1]))}, ${conn.escape(winnerIdx ? 0 : 1)})`, async (error, response) => {
if (error) reject(error);
@ -239,7 +223,7 @@ export class MailAuth {
getProfile(userId) {
return new Promise((resolve, reject) => {
const conn = mysql.createConnection(this.mysqlOptions);
conn.query(`SELECT nickname, account_creation FROM accounts WHERE user_id = ${conn.escape(userId)}; SELECT ROUND((AVG(statistics.won)) * 100) AS winrate, COUNT(statistics.match_id) AS alltime_matches, COUNT(CASE WHEN (YEAR(matches.date) = YEAR(NOW()) AND MONTH(matches.date) = MONTH(NOW())) THEN matches.match_id END) AS monthly_matches FROM accounts NATURAL JOIN statistics NATURAL JOIN matches WHERE accounts.user_id = ${conn.escape(userId)}; SELECT statistics.match_id, accounts.nickname AS opponent, matches.match_type, statistics.won, matches.ai_type, matches.duration, matches.date FROM statistics JOIN matches ON matches.match_id = statistics.match_id JOIN accounts ON accounts.user_id = (CASE WHEN matches.host_id != statistics.user_id THEN matches.host_id ELSE matches.guest_id END) WHERE statistics.user_id = ${conn.escape(userId)} ORDER BY matches.date DESC LIMIT 10;`, async (error, response) => {
conn.query(`SELECT nickname, account_creation FROM accounts WHERE user_id = ${conn.escape(userId)}; SELECT ROUND((AVG(statistics.won)) * 100) AS winrate, COUNT(statistics.match_id) AS alltime_matches, COUNT(CASE WHEN (YEAR(matches.date) = YEAR(NOW()) AND MONTH(matches.date) = MONTH(NOW())) THEN matches.match_id END) AS monthly_matches FROM accounts NATURAL JOIN statistics NATURAL JOIN matches WHERE accounts.user_id = ${conn.escape(userId)}; SELECT statistics.match_id, accounts.nickname AS opponent, matches.match_type, statistics.won, matches.duration, matches.date FROM statistics JOIN matches ON matches.match_id = statistics.match_id JOIN accounts ON accounts.user_id = (CASE WHEN matches.host_id != statistics.user_id THEN matches.host_id ELSE matches.guest_id END) WHERE statistics.user_id = ${conn.escape(userId)} ORDER BY matches.date DESC LIMIT 10;`, async (error, response) => {
if (error) reject(error);
else {
if (response[0].length === 0 || response[1].length === 0) {
@ -262,7 +246,7 @@ export class MailAuth {
const rUid = await this.redis.get(`codeAuth:${authCode}`);
if (rUid != null && rUid === uid) {
this.resetTimer(rUid);
await this.redis.unlink(`codeAuth:${authCode}`);
await this.redis.del(`codeAuth:${authCode}`);
return true;
} else {
return false;

View File

@ -59,11 +59,9 @@ export class GameInfo {
return stats;
}
async incrStat(socket, statKey, by = 1, idx) {
if (!idx) {
const game = await this.redis.json.get(`game:${socket.session.activeGame}`);
idx = socket.request.session.userId === game.hostId ? 0 : 1;
}
async incrStat(socket, statKey, by = 1) {
const game = await this.redis.json.get(`game:${socket.session.activeGame}`);
const idx = socket.request.session.userId === game.hostId ? 0 : 1;
this.redis.json.numIncrBy(`game:${socket.session.activeGame}`, `.boards[${idx}].stats.${statKey}`, by);
}
@ -107,14 +105,12 @@ export class GameInfo {
await this.redis.json.arrAppend(key, `.boards[${playerIdx}].ships`, shipData);
}
async depleteShips(socket, playerIdx) {
async depleteShips(socket) {
const gameId = socket.session.activeGame;
const key = `game:${gameId}`;
const hostId = (await this.redis.json.get(key, { path: '.hostId' }));
if (!playerIdx) {
playerIdx = socket.request.session.userId === hostId ? 0 : 1;
}
const playerIdx = socket.request.session.userId === hostId ? 0 : 1;
var playerShips = (await this.redis.json.get(key, { path: `.boards[${playerIdx}].ships` }));
@ -241,9 +237,13 @@ export class GameInfo {
return deletedShip;
}
async shootShip(socket, enemyIdx, posX, posY) {
async shootShip(socket, posX, posY) {
const gameId = socket.session.activeGame;
const key = `game:${gameId}`;
const hostId = (await this.redis.json.get(key, { path: '.hostId' }));
const enemyIdx = socket.request.session.userId === hostId ? 1 : 0;
// const playerIdx = enemyIdx ? 0 : 1;
let playerBoard = await this.redis.json.get(key, { path: `.boards[${enemyIdx}]` });
@ -286,46 +286,7 @@ export class GameInfo {
return { status: 1, ship: shotShip };
}
async makeAIMove(socket, difficulty) {
difficulty = 0;
const gameId = socket.session.activeGame;
const key = `game:${gameId}`;
const boards = await this.redis.json.get(key, { path: `.boards` });
if (difficulty == 1) { // If difficulty mode is set to smart, check if there are any shot but not sunk ships
}
if (difficulty != 2) { // If difficulty mode is not set to Overkill
var foundAppropriateTarget = false;
var [posX, posY] = [Math.floor(Math.random() * 10), Math.floor(Math.random() * 10)]; // Randomise first set of coordinates
while (!foundAppropriateTarget) { // As long as no appropriate target was found
[posX, posY] = [Math.floor(Math.random() * 10), Math.floor(Math.random() * 10)]; // Randomise another set of coordinates
// let check = checkHit(boards[0].ships, posX, posY);
let shot = boards[0].shots.find((shot) => shot.posX === posX && shot.posY === posY);
// If shot == null then the field with coordinates posX and posY was not shot at yet
if (!shot) {
if (difficulty == 1) { // If difficulty mode is set to smart, check if the shot wasn't near any sunk ship
foundAppropriateTarget = true;
} else { // If difficulty mode is set to simple, just accept that field
foundAppropriateTarget = true;
}
}
}
return [posX, posY];
} else {
}
}
async setReady(socket) { // This makes the socket go ready in a match
async setReady(socket) {
const gameId = socket.session.activeGame;
const key = `game:${gameId}`;
const hostId = (await this.redis.json.get(key, { path: '.hostId' }));
@ -336,11 +297,11 @@ export class GameInfo {
}
}
export function isPlayerInRoom(socket) { // Returns true if the socket is in any socket.io room, otherwise false
export function isPlayerInRoom(socket) {
return !socket.rooms.size === 1;
}
export function getShipsAvailable(ships) { // Returns the amount ships left for each type from list of already placed ships (can be obtained from player's board object)
export function getShipsAvailable(ships) {
let shipsLeft = [4, 3, 2, 1];
ships.forEach(ship => {
@ -350,10 +311,9 @@ export function getShipsAvailable(ships) { // Returns the amount ships left for
return shipsLeft;
}
export function checkHit(ships, posX, posY) { // Checks if a shot at posX and posY is hit (ships is the opponent's ship list)
let boardRender = []; // Create a two-dimensional array that will contain a render of the entire enemy board
export function checkHit(ships, posX, posY) {
let boardRender = [];
// Fill the array with false values
for (let i = 0; i < 10; i++) {
var array = [];
for (let i = 0; i < 10; i++) {
@ -361,12 +321,11 @@ export function checkHit(ships, posX, posY) { // Checks if a shot at posX and po
}
boardRender.push(array);
}
// The array is now 10x10 filled with false values
ships.forEach(ship => {
let multips;
switch (ship.rot) { // Set up proper multipliers for each possible rotation
switch (ship.rot) {
case 0:
multips = [1, 0];
break;
@ -384,37 +343,24 @@ export function checkHit(ships, posX, posY) { // Checks if a shot at posX and po
break;
}
// If multips[0] == 1 then each ship's field will go further by one field from left to right
// If multips[0] == -1 then each ship's field will go further by one field from right to left
// If multips[1] == 1 then each ship's field will go further by one field from top to bottom
// If multips[1] == -1 then each ship's field will go further by one field from bottom to top
// Iterate through all ship's fields
for (let i = 0; i <= ship.type; i++) {
// Calculate the X and Y coordinates of the current field, clamp them in case they overflow the array
let x = clamp(ship.posX + multips[0] * i, 0, 9);
let y = clamp(ship.posY + multips[1] * i, 0, 9);
boardRender[x][y] = {fieldIdx: i, originPosX: ship.posX, originPosY: ship.posY}; // Set the field in the board render
boardRender[x][y] = {fieldIdx: i, originPosX: ship.posX, originPosY: ship.posY};
}
});
// The function returns false if no ship has been hit and an array including following keys if it does:
// fieldIdx, originPosX, originPosY
// where fieldIdx is the amount of fields from the originating point of the ship (in the direction appropriate to set rotation)
// and originPosX and originPosY are the coordinates of the originating point of the ship
// the originating point of the ship is essentialy the field on which a user clicked to place a ship
return boardRender[posX][posY];
}
export function validateShipPosition(ships, type, posX, posY, rot) { // This function checks whether a certain position of a new ship is valid. It returns true if it is and false otherwise
if (type == null || posX == null || posY == null || rot == null || type < 0 || type > 3 || rot < 0 || rot > 3 || posX < 0 || posY < 0 || posX > 9 || posY > 9) {
return false; // Return false when any of the values is incorrect
export function validateShipPosition(ships, type, posX, posY, rot) {
if (type < 0 || type > 3 || rot < 0 || rot > 3) {
return false;
}
let boardRender = []; // Create a two-dimensional array that will contain a render of the entire enemy board
let boardRender = [];
// Fill the array with false values
for (let i = 0; i < 10; i++) {
var array = [];
for (let i = 0; i < 10; i++) {
@ -422,13 +368,11 @@ export function validateShipPosition(ships, type, posX, posY, rot) { // This fun
}
boardRender.push(array);
}
// The array is now 10x10 filled with false values
// Iterate through all ships that are already placed, for rendering them on the boardRender array
ships.forEach(ship => {
let multips;
switch (ship.rot) { // Set up multipliers for each possible rotation, this basically defines the direction of the fields, depending on the rotation
switch (ship.rot) {
case 0:
multips = [1, 0];
break;
@ -446,19 +390,11 @@ export function validateShipPosition(ships, type, posX, posY, rot) { // This fun
break;
}
// If multips[0] == 1 then each ship's field will go further by one field from left to right
// If multips[0] == -1 then each ship's field will go further by one field from right to left
// If multips[1] == 1 then each ship's field will go further by one field from top to bottom
// If multips[1] == -1 then each ship's field will go further by one field from bottom to top
// Iterate through all ship's fields
for (let i = 0; i <= ship.type; i++) {
// Set the boardRender value under the field's coordinates to true
boardRender[ship.posX + multips[0] * i][ship.posY + multips[1] * i] = true;
}
});
// Set up multipliers again, this time for the ship to place
let multips;
switch (rot) {
@ -479,30 +415,21 @@ export function validateShipPosition(ships, type, posX, posY, rot) { // This fun
break;
}
// Iterate through each ship's field
for (let x = 0; x <= type; x++) {
if (posX + multips[0] * x > 9 || posX + multips[0] * x < 0 || posY + multips[1] * x > 9 || posY + multips[1] * x < 0) {
return false; // Return false if the ship's field exceeds the boards bounderies
return false;
}
// Set up subtrahents that we will use to calculate fields around the ship and check if they do not contain another ship to prevent ships from being placed next to each other
let subtrahents = [[0, 0], [0, 1], [1, 0], [0, -1], [-1, 0], [1, 1], [-1, -1], [1, -1], [-1, 1]];
// Iterate through each subtrahents set
let subtrahents = [[0, 0], [0, 1], [1, 0], [0, -1], [-1, 0], [1, 1], [-1, -1], [1, -1], [-1, 1]]; // Usuń cztery ostatnie elementy jeżeli chcesz by statki mogły się stykać rogami
for (let y = 0; y < subtrahents.length; y++) {
// Calculate the field's indexes
const idxX = posX - subtrahents[y][0] + multips[0] * x;
const idxY = posY - subtrahents[y][1] + multips[1] * x;
// If the field's index does not exceed the boards boundaries, check whether it's set as true in the boardRender
if (!(idxX < 0 || idxX > 9 || idxY < 0 || idxY > 9) && boardRender[idxX][idxY]) {
return false; // Return false if the ship is next to another
return false;
}
}
}
// If all the checks pass, return true
return true;
}
@ -515,7 +442,7 @@ export function checkTurn(data, playerId) {
}
}
function findEmptyFields(grid, len) { // Find all empty fields in the board
function findEmptyFields(grid, len) {
const shipPlacements = [];
// Helper function to check if a row can be placed horizontally at a given position

View File

@ -18,12 +18,12 @@
<h3>{{ t 'board.Available:' }} <span class="dynamic danger" id="shipsLeft">-</span></h3>
</div>
<div class="lateBoardInfo">
<h3>{{ t 'board.To sunk' }}</h3>
<h3>{{ t 'board.Sunk ships' }}</h3>
<p>
{{ t 'board.Single-mastedPlu' }} <span class="dynamic shipnote" id="singlemasted">4</span><br>
{{ t 'board.Two-mastedPlu' }} <span class="dynamic shipnote" id="twomasted">3</span><br>
{{ t 'board.Three-mastedPlu' }} <span class="dynamic shipnote" id="threemasted">2</span><br>
{{ t 'board.Four-mastedPlu' }} <span class="dynamic shipnote" id="fourmasted">1</span><br>
{{ t 'board.Single-mastedPlu' }} <span class="dynamic shipnote" id="singlemasted">0</span><br>
{{ t 'board.Two-mastedPlu' }} <span class="dynamic shipnote" id="twomasted">0</span><br>
{{ t 'board.Three-mastedPlu' }} <span class="dynamic shipnote" id="threemasted">0</span><br>
{{ t 'board.Four-mastedPlu' }} <span class="dynamic shipnote" id="fourmasted">0</span><br>
</p>
<h3>{{ t 'board.Your accuracy' }}</h3>
<h2 id="accuracy">-</h2>

View File

@ -4,35 +4,13 @@
<h2>{{ t 'menu.index.Select game mode' }}</h2>
<div class="modes">
<div onclick="switchView('pvpMenuView')">
<div id="pvpMenuButton">
<h2>{{ t 'menu.index.PvP' }}</h2>
<p>{{ t 'menu.index.Play against another player' }}</p>
</div>
<div onclick="switchView('vsAiView')">
<h2>{{ t 'menu.index.Vs AI' }}</h2>
<p>{{ t 'menu.index.Play against the computer' }}</p>
</div>
</div>
</div>
</div>
<div class="container" id="vsAiView" data-path="/pve">
<div>
<h2>{{ t 'menu.PvE.Create' }}</h2>
<h3>{{ t 'menu.PvE.Choose the difficulty mode' }}</h3>
<div class="modes">
<div>
<form action="#" id="pveCreateForm">
<select name="difficulty" id="pveDifficulty">
<option value="simple">Simple</option>
<option value="smart">Smart</option>
<option value="overkill">Overkill</option>
</select>
<p id="difficultyDescription">
{{ t 'menu.PvE.difficulty.Simple.description' }}
</p>
<input type="submit" value="{{ t 'menu.PvE.Begin' }}">
</form>
<h2 id="ai">{{ t 'menu.index.Vs AI' }}</h2>
<p>{{ t 'menu.index.Play against the computer' }}</p>
</div>
</div>
</div>
@ -54,12 +32,12 @@
</div>
</div>
<div class="container" id="pvpCreateView" data-path="/pvp/create" data-pathlock>
<div class="container" id="pvpCreateView" data-path="/pvp/create">
<div>
<h2>{{ t 'menu.PvP/Create.PvP / Create' }}</h2>
<div class="modes">
<div>
<h2>{{ t 'menu.PvP/Create.Room code:' }}</h2>
<h2>{{ t 'menu.PvP/Create.Room code' }}</h2>
<input type="text" maxlength="6" readonly value="-" id="createGameCode">
<h3>{{ t 'menu.PvP/Create.Waiting for an opponent' }}</h3>
<button id="leaveGameButton">{{ t 'menu.PvP/Create.Leave the room' }}</button>
@ -82,7 +60,7 @@
</div>
</div>
<div class="container" id="preparingGame" data-path="/pvp/prepairing" data-pathlock>
<div class="container" id="preparingGame" data-path="/pvp/prepairing">
<div>
<h2>{{ t 'menu.PvP/Loading.PvP / Loading' }}</h2>
<div class="modes">
@ -98,7 +76,7 @@
<div class="container" id="profileView" data-path="/profile">
<div class="profile">
<h1 class="nickname">{{ t 'menu.Profile.Loading' }}</h1>
<h1 id="nickname">{{ t 'menu.Profile.Loading' }}</h1>
<div>
<span>{{ t 'menu.Profile.Player since:' }} </span>
<span id="playerSince">-</span>
@ -122,12 +100,8 @@
<select name="language" id="languages">
</select>
<h2>{{ t 'menu.Settings.Account' }}</h2>
<h3>{{ t 'menu.Settings.Current nickname:' }} <span class="nickname dynamic">{{ t 'menu.Profile.Loading' }}</span></h3>
<button onclick="window.location.href = '/nickname'">{{ t 'menu.Settings.Change nickname' }}</button>
<h3><a href="/privacy" target="_blank">{{ t 'landing.Privacy policy' }}</a></h3>
<h3 id="logout">{{ t 'menu.Settings.Log out' }}</h3>
<p class="versionInfo">statki ver. {{ ver }}<br>© 2024 MCJK <a href="/privacy" target="_blank">{{ t 'landing.Privacy policy' }}</a></p>
</div>
</div>
@ -147,9 +121,6 @@
"Disconnected": "{{ t 'errors.Disconnected' }}",
"Try to refresh the page if this error reoccurs": "{{ t 'errors.Try to refresh the page if this error reoccurs' }}",
"Connection error": "{{ t 'errors.Connection error' }}",
"Simple description": "{{ t 'menu.PvE.difficulty.Simple.description' }}",
"Smart description": "{{ t 'menu.PvE.difficulty.Smart.description' }}",
"Overkill description": "{{ t 'menu.PvE.difficulty.Overkill.description' }}"
};
</script>
<script src="/assets/js/spa_lib.js"></script>

View File

@ -20,7 +20,7 @@
<script src="https://unpkg.com/tippy.js@6"></script>
<link rel="stylesheet" href="https://unpkg.com/tippy.js@6/animations/shift-toward-subtle.css" />
<link rel="stylesheet" href="https://unpkg.com/tippy.js@6/themes/translucent.css" />
<link rel="manifest" href="/app/manifest.json" />
<link rel="manifest" href="/pwa/manifest.json" />
<meta name="theme-color" content="#000000"/>
</head>
<body>