From dd66b8ad239d5ceae219746a702963645259b784 Mon Sep 17 00:00:00 2001 From: Maks Jopek Date: Sat, 10 Apr 2021 01:06:09 +0200 Subject: Added joining rooms and logic to start game by votes --- TODO | 2 ++ backend/ts/api/login.ts | 73 +++++++++++++++++--------------------- backend/ts/api/readyStateToggle.ts | 11 ++++++ backend/ts/api/startPoint.ts | 20 +++++++++++ backend/ts/index.ts | 25 +++++++------ frontend/ts/login.ts | 39 ++++++++++++-------- frontend/ts/startGame.ts | 42 ++++++++++++++++------ frontend/tsconfig.json | 4 +-- helpers/helpers.ts | 54 ++++++++++++++++++++++++---- helpers/tsconfig.json | 12 +++++++ package.json | 8 ++--- public/index.html | 19 +++++----- public/map.html | 65 +++++++++++++-------------------- 13 files changed, 237 insertions(+), 137 deletions(-) create mode 100644 TODO create mode 100644 backend/ts/api/readyStateToggle.ts create mode 100644 backend/ts/api/startPoint.ts create mode 100644 helpers/tsconfig.json diff --git a/TODO b/TODO new file mode 100644 index 0000000..2388448 --- /dev/null +++ b/TODO @@ -0,0 +1,2 @@ +Classes +Starting game diff --git a/backend/ts/api/login.ts b/backend/ts/api/login.ts index 5b38c62..d5393ef 100644 --- a/backend/ts/api/login.ts +++ b/backend/ts/api/login.ts @@ -1,49 +1,42 @@ import { Request, Response } from "express"; -import { makeQuery } from "../helpers"; +import { makeQuery, fiaTable, dbRes, dbResToFiaTable, Color, Colors } from "../../../helpers/helpers"; -interface Colors { - blue: number; - red: number; - green: number; - yellow: number; - 0: number; - 1: number; - 2: number; - 3: number; -} - -interface fiaTable { - id: number; - data: Array; - started: boolean; -} - -const Color: Colors = { - blue: 0, - red: 1, - green: 2, - yellow: 3, - 0: 0, 1: 1, 2: 2, 3: 3 -} - -export default async function apiLogin(req: Request, res: Response) { +// export default async function apiLogin(req: Request, res: Response) { +export default async function (req: Request, res: Response) { if (req.session === undefined) { - res.send(/* html */``); + res.send(/* html */ ``); return; } req.session.uid = req.session.id; - let c = await makeQuery("SELECT * FROM `fia` WHERE `started`= false LIMIT 1", []), + req.session.name = req.body.name; + + let dbRes = (await makeQuery("SELECT * FROM `fia` WHERE `started`= 0 LIMIT 1", [])) as Array, row: fiaTable; - if (c === "") { - let data = { id: req.session.uid, color: Color.blue }; - makeQuery("INSERT INTO `fia`(`data`, `started`) VALUES (?, ?)", [JSON.stringify(data), "0"]); - } - else { - row = JSON.parse(c); - row.data.push({ id: req.session.uid, color: Color[row.data.length as keyof Colors] }); - makeQuery("UPDATE `fia` SET `data`=? WHERE `id`=?", [JSON.stringify(row.data), row.id.toString()]); - if(row.data.length === 4) - makeQuery("UPDATE `fia` SET `started` = 1 WHERE `id`=?", [row.id.toString()]); + if (dbRes.length === 0) { + row = {} as fiaTable; + row.data = [{ id: req.session.uid, color: Color.blue, name: req.body.name }]; + req.session.color = Color.blue; + + await makeQuery('INSERT INTO `fia`(`data`, `started`) VALUES (?, ?)', [JSON.stringify(row.data), 0]); + req.session.gid = (await makeQuery('SELECT `id` FROM `fia` WHERE `data`=?', [JSON.stringify(row.data)]) as any)[0].id; + } else { + row = dbResToFiaTable(dbRes[0]); + let color = Color[row.data.length as keyof Colors]; + row.data.push({ + id: req.session.uid, + color: Color.blue, + name: req.body.name + }); + + req.session.gid = row.id; + req.session.color = color; + makeQuery('UPDATE `fia` SET `data`=? WHERE `id`=?', [JSON.stringify(row.data), row.id]); + + if (row.data.length === 4) { + makeQuery("UPDATE `fia` SET `started` = 1 WHERE `id`=?", [row.id]); + // TODO: Start game from backend + } } - res.send("[1, 2, 3]"); + makeQuery("UPDATE `fia` SET `playersCount`=`playersCount`+1 WHERE `id`=?", [req.session.gid]); + res.send(JSON.stringify(row.data)); } diff --git a/backend/ts/api/readyStateToggle.ts b/backend/ts/api/readyStateToggle.ts new file mode 100644 index 0000000..f6269bc --- /dev/null +++ b/backend/ts/api/readyStateToggle.ts @@ -0,0 +1,11 @@ +import { Request, Response } from "express"; +import { makeQuery, checkApiRes } from "../../../helpers/helpers"; + +export default async function (req: Request, res: Response) { + if (req.session === undefined || req.body.state == undefined) { + res.send(/* html */ ``); + return; + } + makeQuery("UPDATE `fia` SET `playersAreReady`=`playersAreReady`+" + (req.body.state ? 1 : 0) + + " WHERE `id`=" + req.session.gid, []).then(dbRes => checkApiRes(dbRes, res)); +} diff --git a/backend/ts/api/startPoint.ts b/backend/ts/api/startPoint.ts new file mode 100644 index 0000000..0fa79e5 --- /dev/null +++ b/backend/ts/api/startPoint.ts @@ -0,0 +1,20 @@ +import { Request, Response } from "express"; +import { makeQuery } from "../../../helpers/helpers"; + +export default async function (req: Request, res: Response) { + if (req.session === undefined) { + res.send(/* html */ ``); + return; + } + console.log("uid:", req.session.uid, "gid:", req.session.gid); + if (req.session.uid !== undefined) { + let data = await makeQuery('SELECT `data` FROM `fia` WHERE `id`=?', [req.session.gid]); + console.log("data: ", data); + res.send(JSON.stringify({ + status: true, + data: data + })) + } + else + res.send(JSON.stringify({ status: false })); +} \ No newline at end of file diff --git a/backend/ts/index.ts b/backend/ts/index.ts index ead29f2..6b12571 100644 --- a/backend/ts/index.ts +++ b/backend/ts/index.ts @@ -1,24 +1,29 @@ import express from "express"; -import login from "./api/login"; import session from "express-session"; import * as dotenv from "dotenv"; +import login from "./api/login"; +import startPoint from "./api/startPoint"; +import readyStateToggle from "./api/readyStateToggle"; + dotenv.config(); const app = express(); const PORT = 8000; -if (!process.env.SESSION_KEY) process.env.SESSION_KEY = "ouh2981w1pjd9"; -// throw Error("SESSION_KEY is undefined"); +if (!process.env.SESSION_KEY) + throw Error("SESSION_KEY is undefined"); -app.use( - session({ secret: process.env.SESSION_KEY, cookie: { maxAge: 60000 } }) -); +app.use(session({ secret: process.env.SESSION_KEY, cookie: { maxAge: 60000 } })); +app.use(express.json()); app.use("/", express.static("./public")); -app.get("/favicon.ico", (req, res) => - res.redirect("https://lukesmith.xyz/favicon.ico") -); -app.post("/login", (req, res) => login(req, res)); +app.get("/favicon.ico", (req, res) => res.redirect("https://lukesmith.xyz/favicon.ico")); + +app.get("/startPoint", startPoint) + +app.post("/login", login); +app.post("/readyStateToggle", readyStateToggle); + app.listen(PORT, () => { console.log(`[server]: Server is running at https://localhost:${PORT}`); diff --git a/frontend/ts/login.ts b/frontend/ts/login.ts index 4ef46ab..5b09e89 100644 --- a/frontend/ts/login.ts +++ b/frontend/ts/login.ts @@ -1,26 +1,35 @@ +import { json } from "express"; import startGame from "./startGame.js"; +// import { Data, Color } from "../../helpers/helpers.js"; let html = /* html */ `
- +
`; -async function login() { - let username = document.getElementsByTagName("input")[0].innerHTML, - res = await fetch("/login", { - method: "POST", - headers: { - Accept: "application/json", - "Content-Type": "application/json" - }, - body: JSON.stringify({ username: username }) - }); - res = await res.json(); - startGame(res); +async function login(username = "") { + if (username === "") + username = document.getElementsByTagName("input")[0].value; + let res = await fetch("/login", { + method: "POST", + headers: { + Accept: "application/json", + "Content-Type": "application/json" + }, + body: JSON.stringify({ name: username }) + }); + startGame(await res.json()); } -document.body.innerHTML = html; -document.getElementsByTagName("button")[0].onclick = login; +(async () => { + let res = await (await fetch("/startPoint")).json(); + if (res.status === true) { + startGame(JSON.parse(res.data[0].data)); + } else { + document.body.innerHTML = html; + document.getElementsByTagName("button")[0].onclick = () => login(); + } +})() \ No newline at end of file diff --git a/frontend/ts/startGame.ts b/frontend/ts/startGame.ts index 50ef068..a14742f 100644 --- a/frontend/ts/startGame.ts +++ b/frontend/ts/startGame.ts @@ -1,23 +1,45 @@ +import { Data, checkApiRes, mFetch } from "../../helpers/helpers"; + function getCanvasAndCtx(): [HTMLCanvasElement, CanvasRenderingContext2D] { let canvas = document.getElementsByTagName("canvas")[0], ctx = canvas.getContext("2d"); if (ctx === null) { document.write("ur muther is fat, stop using IE"); - throw new Error("PLayer is using browser older that his mom"); + throw new Error("Player is using browser older that his mom"); } else return [canvas, ctx]; } -function setOpponents(data: object, body: string) { - let a = [ - { - id: 1, - color: "red", + +function setOpponents(data: Data) { + // Start game + console.log("startGame.ts: data: ", data) + let tds = document.getElementsByClassName("player-name"), + colors = ["primary", "danger", "success", "warning"], + replacement = { name: "", color: "" }; + for (let i = 0; i < 4; i++) { + if (data[i] !== undefined) { + replacement.name = data[i].name; + replacement.color = colors[i]; + } else { + replacement.name = "?"; + replacement.color = "secondary"; } - ] - document.body.innerHTML = body; + tds[i].innerHTML = replacement.name; + tds[i].classList.add("bg-" + replacement.color); + } +} + +function readyStateToggle(e: MouseEvent) { + mFetch("/readyStateToggle", { state: (e.target as any).checked }); } -export default async function startGame (data: object) { + +export default async function (data: Data) { + console.log(data); let body = await (await fetch("/map.html")).text(); - setOpponents(data, body); + document.body.innerHTML = body; + + setOpponents(data); + document.getElementsByTagName("input")[0].onclick = readyStateToggle; + let [canvas, ctx] = getCanvasAndCtx(); let img = new Image(600, 600); img.width = 600; diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json index 0d131bd..1b796a0 100644 --- a/frontend/tsconfig.json +++ b/frontend/tsconfig.json @@ -1,11 +1,11 @@ { "extends": "../tsconfig.json", "compilerOptions": { - "module": "ES2020", + "module": "esnext", "lib": [ "DOM" ], - "outDir": "../public/js" + "outDir": "../public/js", }, "include": [ "ts/**/*" diff --git a/helpers/helpers.ts b/helpers/helpers.ts index 3a16d18..de6744f 100644 --- a/helpers/helpers.ts +++ b/helpers/helpers.ts @@ -1,11 +1,8 @@ import fetch from "node-fetch"; +import { Response } from "express"; -export async function makeQuery( - query: string, - params: Array -): Promise { - console.log("makeQuery"); - return await ( +export async function makeQuery(query: string, params: Array): Promise { + let t = await ( await fetch("https://jopek.eu/maks/szkola/apkKli/fiaFiles/fia.php", { method: "POST", headers: { @@ -14,11 +11,49 @@ export async function makeQuery( }, body: JSON.stringify({ apiKey: process.env.API_KEY, - stmt: query, + query: query, params: params }) }) ).text(); + // console.log(t); + return JSON.parse(t); +} + +export function dbResToFiaTable(dbRes: dbRes): fiaTable { + if (typeof dbRes.data === "string") + dbRes.data = JSON.parse(dbRes.data); + else + throw new Error("dbResToFiaTable : wrong $1 type; "); + + // @ts-ignore + return dbRes; +} + +export function checkApiRes(res: any, nRes = {} as Response): void { + if (res.api === false) { + if (Object.keys(nRes).length === 0) { + alert("API Error!"); + throw new Error("API Error!"); + } else { + nRes.status(500); + res.send(""); + } + } + if (Object.keys(nRes).length !== 0) + nRes.status(200); + return res; +} + +export async function mFetch(url: string, body: object) /* : Promise */ { + return fetch(url, { + method: "POST", + headers: { + Accept: "application/json", + "Content-Type": "application/json" + }, + body: JSON.stringify(body) + }).then(checkApiRes); } export interface Colors { @@ -50,3 +85,8 @@ export interface fiaTable { data: Data; started: boolean; } +export interface dbRes { + id: number; + data: string | Data; + started: boolean; +} diff --git a/helpers/tsconfig.json b/helpers/tsconfig.json new file mode 100644 index 0000000..21a1541 --- /dev/null +++ b/helpers/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "module": "esnext", + "lib": [ + "DOM" + ], + }, + "include": [ + "*" + ] +} \ No newline at end of file diff --git a/package.json b/package.json index c11425e..eb707c4 100644 --- a/package.json +++ b/package.json @@ -7,9 +7,9 @@ "main": "./backend/js/index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", - "start:build-front": "tsc -p ./frontend/tsconfig.json --watch", - "start:build-back": "tsc -p ./backend/tsconfig.json --watch", - "start:run": "nodemon ./backend/js/index.js", + "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:*\"" }, "dependencies": { @@ -31,4 +31,4 @@ }, "keywords": [], "description": "" -} \ No newline at end of file +} diff --git a/public/index.html b/public/index.html index 8d35181..d7ea523 100644 --- a/public/index.html +++ b/public/index.html @@ -2,17 +2,20 @@ - - - - Fia - + + + + Fia + - - - + + \ No newline at end of file diff --git a/public/map.html b/public/map.html index d38a015..c23ccfd 100644 --- a/public/map.html +++ b/public/map.html @@ -1,43 +1,26 @@
- - - - - - - - - - - - - - -
- {{ player.name }} - - {{ player.name }} - - {{ player.name }} - - {{ player.name }} - -
- - -
-
-
- - Din webbläsare stöder inte canvas, vilket betyder att du inte kan spela - fia -
+ + + + + + + + + + + + + + +
+ + +
+
+ + Din webbläsare stöder inte canvas, vilket betyder att du inte kan spela + fia +
- \ No newline at end of file +
-- cgit v1.3.1