aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMaks Jopek <maksymilian.jopek@prym-soft.pl>2021-05-01 00:20:33 +0200
committerMaks Jopek <maksymilian.jopek@prym-soft.pl>2021-05-01 00:20:33 +0200
commitc813dfadd4b673080695ef3ade37a44e37036c07 (patch)
tree4d6348ecad8c65780323ccb823063f335c5c9e7f
parent040d5372c1033bb7c0580ad2c9b6b32f974a20c8 (diff)
downloadfia-c813dfadd4b673080695ef3ade37a44e37036c07.tar.gz
fia-c813dfadd4b673080695ef3ade37a44e37036c07.tar.zst
fia-c813dfadd4b673080695ef3ade37a44e37036c07.zip
Version 1.1
-rw-r--r--backend/ts/api/getCurrentGameState.ts4
-rw-r--r--backend/ts/api/login.ts1
-rw-r--r--backend/ts/api/reset.ts7
-rw-r--r--backend/ts/api/won.ts14
-rw-r--r--backend/ts/index.ts4
-rw-r--r--frontend/ts/logic.ts90
-rw-r--r--frontend/ts/login.ts21
-rw-r--r--frontend/ts/startGame.ts53
-rw-r--r--helpers/helpers.ts5
-rw-r--r--helpers/helpersBack.ts10
-rw-r--r--package.json3
-rw-r--r--public/index.html6
12 files changed, 139 insertions, 79 deletions
diff --git a/backend/ts/api/getCurrentGameState.ts b/backend/ts/api/getCurrentGameState.ts
index 28522e1..896ccb4 100644
--- a/backend/ts/api/getCurrentGameState.ts
+++ b/backend/ts/api/getCurrentGameState.ts
@@ -8,8 +8,8 @@ export default async function getCurrentGameState(req: Request, res: Response) {
return;
}
- let dbRes: { gameBoard: GameBoard, currentPlayer: number, started: number, data: Data, timeTillTurnEnd: number }
- = (await makeQuery("SELECT `gameBoard`, `currentPlayer`, `started`, `data`, `timeTillTurnEnd`"
+ let dbRes: { gameBoard: GameBoard, currentPlayer: number, started: number, data: Data, timeTillTurnEnd: number, winner: null | number }
+ = (await makeQuery("SELECT `gameBoard`, `currentPlayer`, `started`, `data`, `timeTillTurnEnd`, `winner`"
+ " FROM `fia` WHERE `id` = ?",
[req.session.gid]))[0];
diff --git a/backend/ts/api/login.ts b/backend/ts/api/login.ts
index a957760..c01ef75 100644
--- a/backend/ts/api/login.ts
+++ b/backend/ts/api/login.ts
@@ -32,6 +32,7 @@ export default async function apiLogin(req: Request, res: Response) {
}];
req.session.color = color;
+ req.session.index = 0;
await makeQuery('INSERT INTO `fia`(`data`) VALUES (?)', [row.data]);
req.session.gid = (await makeQuery('SELECT `id` FROM `fia` WHERE `data`= ?', [row.data]))[0].id;
diff --git a/backend/ts/api/reset.ts b/backend/ts/api/reset.ts
new file mode 100644
index 0000000..c6c4bd5
--- /dev/null
+++ b/backend/ts/api/reset.ts
@@ -0,0 +1,7 @@
+import { Request, Response } from "express";
+import { API_RES } from "../../../helpers/helpersBack";
+
+export default function reset(req: Request, res: Response) {
+ req.session?.destroy(() => true);
+ res.send(API_RES.success);
+} \ No newline at end of file
diff --git a/backend/ts/api/won.ts b/backend/ts/api/won.ts
new file mode 100644
index 0000000..1e8287c
--- /dev/null
+++ b/backend/ts/api/won.ts
@@ -0,0 +1,14 @@
+import { Request, Response } from "express";
+import { API_RES, makeQuery } from "../../../helpers/helpersBack";
+
+export default async function won(req: Request, res: Response) {
+ if (req.session === undefined || req.session.gid === undefined || req.session.index === undefined) {
+ console.log(JSON.stringify(req));
+ res.status(400);
+ res.send(API_RES.failure);
+ return;
+ }
+ await makeQuery("UPDATE `fia` SET `winner` = ? WHERE `id` = ?", [req.session.index, req.session.gid]);
+
+ res.send(API_RES.success);
+} \ No newline at end of file
diff --git a/backend/ts/index.ts b/backend/ts/index.ts
index dcaac7e..90c1683 100644
--- a/backend/ts/index.ts
+++ b/backend/ts/index.ts
@@ -7,6 +7,8 @@ import startPoint from "./api/startPoint";
import readyStateToggle from "./api/readyStateToggle";
import getCurrentGameState from "./api/getCurrentGameState";
import saveGameBoard from "./api/saveGameBoard";
+import won from "./api/won";
+import reset from "./api/reset";
export const global = { stop: false };
@@ -36,6 +38,8 @@ app.post("/login", login);
app.post("/readyStateToggle", readyStateToggle);
app.post("/getCurrentGameState", getCurrentGameState);
app.post("/saveGameBoard", saveGameBoard);
+app.post("/won", won);
+app.post("/reset", reset);
app.listen(PORT, () => {
console.log(`[server]: Server is running at https://localhost:${PORT}`);
diff --git a/frontend/ts/logic.ts b/frontend/ts/logic.ts
index 015226e..c5d4fb9 100644
--- a/frontend/ts/logic.ts
+++ b/frontend/ts/logic.ts
@@ -31,7 +31,7 @@ export default class Logic {
if (square.chequers.length > 0 && square.chequers[0].color === color) {
for (let chequer of square.chequers) {
let x: number | undefined, y: number | undefined, coords: Coordinates | undefined, inMap: boolean,
- homeIndex: number | undefined, befStart: number | undefined;
+ homeIndex: number | undefined, befStart: number | undefined, normalTurn = true;
if (color !== Helpers.Color.red) {
gameBoard.map.forEach((square, i) => {
@@ -45,25 +45,41 @@ export default class Logic {
throw new Error("before start doesnt exist");
let range = (start: number, end: number) => Array.from(Array(end + 1).keys()).slice(start);
- // if(i >= befStart && i + number <= befStart) {
+ // if(i >= befStart && i + number <= befStart) {
+ inMap = true;
if (range(i, i + number).includes(befStart)) {
homeIndex = number - befStart + i - 1;
inMap = false;
- if (homeIndex < gameBoard.homes[0].length) {
- x = gameBoard.homes[color as keyof HomesOrBases][homeIndex].x;
- y = gameBoard.homes[color as keyof HomesOrBases][homeIndex].y;
+ if (homeIndex !== -1) {
+ normalTurn = false;
+
+ if (homeIndex < gameBoard.homes[0].length) {
+ x = gameBoard.homes[color as keyof HomesOrBases][homeIndex].x;
+ y = gameBoard.homes[color as keyof HomesOrBases][homeIndex].y;
+ let homeSquare = gameBoard.homes[color as keyof HomesOrBases][homeIndex];
+ if (homeSquare.chequer >= 0) { x = y = homeIndex = undefined; }
+ }
+ else {
+ x = y = undefined;
+ }
}
- else {
- x = y = undefined;
+ }
+ if (normalTurn === true) {
+ if (homeIndex === -1) {
+ x = gameBoard.map[befStart].x;
+ y = gameBoard.map[befStart].y;
+ inMap = true;
+ homeIndex = undefined;
}
- } else {
- if (i + number >= gameBoard.map.length)
- number += i - gameBoard.map.length - i; //* -$i 'cause adding $i on 62 && 63
+ else {
+ if (i + number >= gameBoard.map.length)
+ number += i - gameBoard.map.length - i; //* -$i 'cause adding $i on 62 && 63
- x = gameBoard.map[i + number].x;
- y = gameBoard.map[i + number].y;
- inMap = true;
+ x = gameBoard.map[i + number].x;
+ y = gameBoard.map[i + number].y;
+ inMap = true;
+ }
}
if (x === undefined || y === undefined)
@@ -71,14 +87,24 @@ export default class Logic {
else
coords = { x, y };
- chequer.ghost = {
- where: {
- from: "map", oldIndex: i,
- to: (inMap === true ? "map" : "home"),
- newIndex: homeIndex || i + number
- },
- color: color,
- coords,
+ let newIndex: number;
+ if (homeIndex !== undefined)
+ newIndex = homeIndex;
+ else
+ newIndex = i + number;
+
+ if (coords !== undefined) {
+ chequer.ghost = {
+ where: {
+ from: "map", oldIndex: i,
+ to: (inMap === true ? "map" : "home"),
+ newIndex: newIndex
+ },
+ color: color,
+ coords,
+ }
+ } else {
+ chequer.ghost = undefined;
}
}
}
@@ -91,7 +117,7 @@ export default class Logic {
home.forEach((chequer, i) => {
if (chequer.chequer > -1) {
let x: number | undefined, y: number | undefined, coords: Coordinates | undefined;
- if (home[i + number] !== undefined) {
+ if (home[i + number] !== undefined && home[i + number].chequer < 0) {
x = home[i + number].x;
y = home[i + number].y;
} else {
@@ -103,14 +129,18 @@ export default class Logic {
else
coords = { x, y };
- chequer.ghost = {
- where: {
- from: "home", oldIndex: i,
- to: "home", newIndex: i + number
- },
- color: color,
- coords,
- };
+ if (coords !== undefined) {
+ chequer.ghost = {
+ where: {
+ from: "home", oldIndex: i,
+ to: "home", newIndex: i + number
+ },
+ color: color,
+ coords,
+ };
+ } else {
+ chequer.ghost = undefined;
+ }
}
});
diff --git a/frontend/ts/login.ts b/frontend/ts/login.ts
index c02aafd..658110d 100644
--- a/frontend/ts/login.ts
+++ b/frontend/ts/login.ts
@@ -12,29 +12,30 @@ class Login {
static clicked = false;
static async start() {
- let res = await (await fetch("/startPoint")).json();
+ let res = await (await fetch("/fia/startPoint")).json();
if (res.status === true) {
new StartGame({ data: res.data.data, uid: res.uid });
} else {
document.body.innerHTML = Login.html;
document.getElementsByTagName("button")[0].onclick = () => Login.login();
-
- // !!
- // document.getElementsByTagName("input")[0].value = "maks " + Helpers.getRandomInt(1, 100);
- // document.title = document.getElementsByTagName("input")[0].value;
- // document.getElementsByTagName("button")[0].click();
}
}
static async login(username = "") {
- if(Login.clicked === true)
+ if (Login.clicked === true)
return;
-
- Login.clicked = true;
+
if (username === "")
username = document.getElementsByTagName("input")[0].value;
- let res = await Helpers.mFetch("/login", { name: username });
+ if (username.length > 15) {
+ alert("Ditt namn är för långt!");
+ return;
+ }
+
+ Login.clicked = true;
+
+ let res = await Helpers.mFetch("/fia/login", { name: username });
new StartGame(res);
}
}
diff --git a/frontend/ts/startGame.ts b/frontend/ts/startGame.ts
index 883d648..7da81d4 100644
--- a/frontend/ts/startGame.ts
+++ b/frontend/ts/startGame.ts
@@ -40,7 +40,7 @@ export default class StartGame {
}
async init(data: { data: Data, uid: string }) {
- document.body.innerHTML = await (await fetch("/map.html")).text();
+ document.body.innerHTML = await (await fetch("/fia/map.html")).text();
if (speechSynthesis.onvoiceschanged !== undefined)
speechSynthesis.onvoiceschanged = () => this.voices = speechSynthesis.getVoices();
@@ -99,7 +99,7 @@ export default class StartGame {
return;
}
this.toggleStop = true;
- let res = await Helpers.mFetch("/readyStateToggle", {
+ let res = await Helpers.mFetch("/fia/readyStateToggle", {
state: this.inpStateToggle.checked
});
if (res.started === true)
@@ -118,10 +118,7 @@ export default class StartGame {
rollDice = async (e: MouseEvent): Promise<void> => {
this.btnRollDice.style.display = "none";
let number = Helpers.getRandomInt(1, 7);
-
- if((window as any).number !== undefined)
- number = (window as any).number;
-
+
this.say(number.toString());
this.diceHash;
this.divDice.classList.add(`dice-${number}`);
@@ -144,7 +141,7 @@ export default class StartGame {
}
if (voice === undefined)
voice = this.voices.find(el => el.default === true);
-
+
if (voice === undefined) {
// console.log("Client does not have any voices in SpeechSynthesis");
return;
@@ -169,7 +166,7 @@ export default class StartGame {
ghost.allBlink(this.gameBoard, this.color);
}
- doTurn(chequer: Chequer | HoBSquare): void {
+ async doTurn(chequer: Chequer | HoBSquare): Promise<void> {
if (chequer.ghost === undefined || chequer.ghost.coords === undefined) {
return;
}
@@ -191,7 +188,7 @@ export default class StartGame {
square = this.gameBoard.map[where.newIndex];
for (let i = 0, j = 0; i < square.chequers.length; i++, j = 0) {
- while(enemyBase[j].chequer >= 0)
+ while (enemyBase[j].chequer >= 0)
j++;
enemyBase[j].chequer = enemyColor;
}
@@ -204,16 +201,22 @@ export default class StartGame {
this.gameBoard.homes[this.color as keyof HomesOrBases][where.newIndex].chequer = this.color;
}
- (window as any).clicked = true;
+ chequer.ghost = undefined;
let won = this.gameHasBeenWon();
- if (won === true) {
- alert("WON!WON!WON!WON!WON!WON!");
- throw new Error("WON!WON!WON!WON!WON!WON!");
- }
ghost.allStopBlink();
ghost.removeGhosts(this.gameBoard, this.color);
gameBoardClass.drawGameBoard(this.gameBoard, this.drawChequer);
+ if (won === true) {
+ clearInterval(this.interval);
+ this.btnRollDice.style.display = "none";
+ this.timer.stop();
+ await this.sendGameBoard(false);
+ await Helpers.mFetch("/fia/won", { index: this.index });
+ await Helpers.mFetch("/fia/reset", {});
+ alert("Du vann spelet !!!");
+ return;
+ }
this.sendGameBoard(false);
}
async hideDice(wait: boolean) {
@@ -239,7 +242,7 @@ export default class StartGame {
this.timer.stop();
this.gameWasStopped = true;
this.hideDice(diceWait);
- await Helpers.mFetch("/saveGameBoard", { gameBoard: this.gameBoard });
+ await Helpers.mFetch("/fia/saveGameBoard", { gameBoard: this.gameBoard });
}
drawChequer = (coords: Coordinates, color: tColors, chequer: Chequer | HoBSquare): void => {
@@ -267,9 +270,21 @@ export default class StartGame {
}
async getData() {
- let data: { gameBoard: GameBoard, currentPlayer: number, started: number, data: Data, timeTillTurnEnd: number }
- = await Helpers.mFetch("/getCurrentGameState", {});
-
+ let data: { gameBoard: GameBoard, currentPlayer: number, started: number, data: Data, timeTillTurnEnd: number, winner: null | number }
+ = await Helpers.mFetch("/fia/getCurrentGameState", {});
+ console.log("Data fetched");
+
+ if (data.started === 1 && data.winner !== null) {
+ clearInterval(this.interval);
+ this.btnRollDice.style.display = "none";
+ this.timer.stop();
+ let winnerName = this.data.filter(el => el.index === data.winner)[0].name;
+ gameBoardClass.drawGameBoard(data.gameBoard, this.drawChequer);
+ alert(`Spelaren ${winnerName} vann spelet!!!`);
+ await Helpers.mFetch("/fia/reset", {});
+ return;
+ }
+
if (data.started === 1) {
this.gameStarted = true;
if (this.oldIndex !== data.currentPlayer) {
@@ -290,7 +305,5 @@ export default class StartGame {
this.data = data.data;
this.setOpponents(this.data, false);
}
-
- // TODO: Check gameHasBeenWon()
}
}
diff --git a/helpers/helpers.ts b/helpers/helpers.ts
index 9cd15cc..1f9aa06 100644
--- a/helpers/helpers.ts
+++ b/helpers/helpers.ts
@@ -18,15 +18,11 @@ export default class Helpers {
})
})
).json();
- // console.log(t);
- // return JSON.parse(t);
return t;
}
static dbResToFiaTable(dbRes: dbRes): fiaTable {
if (typeof dbRes.data === "string") {
- console.log("dbRes.data: ", dbRes.data);
- console.log("dbRes.data as string: ", JSON.stringify(dbRes.data));
dbRes.data = JSON.parse(dbRes.data);
}
else
@@ -40,7 +36,6 @@ export default class Helpers {
if (res.success === false) {
if (Object.keys(nRes).length === 0) {
// @ts-ignore - here error is because backend tsc is checking this file, where lib: DOM is not present
- // alert("API Error!");
throw new Error("API Error!");
} else {
nRes.status(500);
diff --git a/helpers/helpersBack.ts b/helpers/helpersBack.ts
index b0e9a6d..3d2f0a1 100644
--- a/helpers/helpersBack.ts
+++ b/helpers/helpersBack.ts
@@ -9,11 +9,6 @@ export const API_RES = {
failure: '{"success": false}',
};
export async function makeQuery(query: string, params: Array<any>): Promise<Array<any>> {
- // console.log("params are ", JSON.stringify({
- // apiKey: process.env.API_KEY,
- // query: query,
- // params: params
- // }));
let t: any = await (
await fetch("https://jopek.eu/maks/szkola/apkKli/fiaFiles/fia.php", {
method: "POST",
@@ -47,7 +42,6 @@ export async function getData(gid: number): Promise<Data> {
data = JSON.parse(data) as Data;
return data;
} else {
- console.log(data);
throw new Error("Data is not a object");
}
}
@@ -125,7 +119,7 @@ export interface OldTd {
}
export interface Chequer {
color: tColors;
- ghost?: Ghost; // number; // 1 | 2 | 3 | 4 | 5 | 6;
+ ghost?: Ghost;
};
export interface Coordinates {
x: number; //0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11;
@@ -137,7 +131,7 @@ export interface Square extends Coordinates {
}
export interface HoBSquare extends Coordinates {
chequer: tColors;
- ghost?: Ghost; // number; // 1 | 2 | 3 | 4 | 5 | 6;
+ ghost?: Ghost;
}
export interface HomesOrBases {
0: Array<HoBSquare>;
diff --git a/package.json b/package.json
index 7836d62..d65ab07 100644
--- a/package.json
+++ b/package.json
@@ -10,7 +10,8 @@
"start:build-front": "tsc -p ./frontend/tsconfig.json -w",
"start:build-back": "tsc -p ./backend/tsconfig.json -w",
"start:start": "nodemon ./backend/js/backend/ts/index.js",
- "start": "concurrently yarn:start:*"
+ "start-dev": "concurrently yarn:start:*",
+ "start-prod": "node ./backend/js/backend/ts/index.js"
},
"dependencies": {
"dotenv": "^8.2.0",
diff --git a/public/index.html b/public/index.html
index 617de91..9cc5532 100644
--- a/public/index.html
+++ b/public/index.html
@@ -5,8 +5,8 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fia</title>
- <link rel="stylesheet" href="css/bootstrap.min.css" />
- <link rel="stylesheet" href="css/fia.css" />
+ <link rel="stylesheet" href="fia/css/bootstrap.min.css" />
+ <link rel="stylesheet" href="fia/css/fia.css" />
</head>
<body class="bg-dark text-white">
<noscript>
@@ -14,6 +14,6 @@
Tyvärr, men för att spela Fia måste du aktivera skript
</div>
</noscript>
- <script src="js/frontend/ts/login.js" type="module"></script>
+ <script src="fia/js/frontend/ts/login.js" type="module"></script>
</body>
</html>