Skip to content

Commit

Permalink
Merge pull request #22 from i3ene/backend-game-logic
Browse files Browse the repository at this point in the history
Backend game logic
  • Loading branch information
i3ene authored Jun 14, 2023
2 parents 07ff26e + 4974916 commit a1fb2a2
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 31 deletions.
6 changes: 3 additions & 3 deletions api/src/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export namespace AuthController {

console.log('User', req.user.name, 'logged in.');
res.status(200).send(JSON.stringify(token));
});
})(req, res);
}

export function resetPassword(req: Request, res: Response) {
Expand All @@ -36,7 +36,7 @@ export namespace AuthController {
});

res.status(200).send({message: 'Password successfully reset!'});
});
})(req, res);
}

export function signup(req: Request, res: Response) {
Expand All @@ -54,7 +54,7 @@ export namespace AuthController {
if (!mail) return res.status(500).send({message: "Mail sending failed!"});

res.status(200).send({message: `Registration send to ${register.mail}! Please also check your Spam folder.`})
});
})(req, res);
}

export async function validationToken(io: Server, socket: Socket, type: string) {
Expand Down
13 changes: 6 additions & 7 deletions api/src/middleware/auth.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export namespace AuthMiddleware {

req.user = user;
next();
});
})(req, res, next);
}

export function verifyPassword(req: Request, res: Response, next: NextFunction) {
Expand All @@ -32,13 +32,12 @@ export namespace AuthMiddleware {
if (!valid) return res.status(401).send({ message: 'Password is incorrect!' });

next();
});
})(req, res, next);
}

export function verifyToken(req: Request, res: Response, next: NextFunction) {
return Handler.Async(async () => {
var token = req.headers[Config.Auth.HEADER] as string;
console.log(token);
if (token == null) return res.status(401).send({ message: 'No token provided!' });

jwt.verify(token, Config.Auth.SECRET, (err: any, decoded: any) => {
Expand All @@ -50,7 +49,7 @@ export namespace AuthMiddleware {
return res.status(401).send({ message: 'Token invalid!' });
}
});
});
})(req, res, next);
}

export function checkDuplicateName(req: Request, res: Response, next: NextFunction) {
Expand All @@ -65,7 +64,7 @@ export namespace AuthMiddleware {
if (user != undefined) return res.status(404).send({ message: 'Username already exists!' });

next();
});
})(req, res, next);
}

export function checkDuplicateMail(req: Request, res: Response, next: NextFunction) {
Expand All @@ -80,7 +79,7 @@ export namespace AuthMiddleware {
if (user != undefined) return res.status(404).send({ message: 'Mail already exists!' });

next();
});
})(req, res, next);
}

export function checkPassword(req: Request, res: Response, next: NextFunction): any {
Expand All @@ -95,7 +94,7 @@ export namespace AuthMiddleware {
if (req.user.id != Config.Auth.ADMIN_ID) return res.status(401).send({ message: 'Restricted to Admin!' });

next();
});
})(req, res, next);
}

export function getSelf(key: string | any, scopes: any[] = []) {
Expand Down
17 changes: 8 additions & 9 deletions api/src/models/object/game.model.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import EventEmitter from 'events';
import {Socket} from 'socket.io';
import {Card} from '../data/card.model';
import {Deck} from '../data/deck.model';
import {User} from '../data/user.model';
import {Game} from './game.object';
import {BackendAction, FrontendAction, SocketAction} from './socket.model';
import { _Object } from '../data/object.model';
import { SubInventory } from '../data/subInventory.model';
import {SubInventory} from '../data/subInventory.model';

export enum GameEvent {
START = 'start',
Expand Down Expand Up @@ -190,7 +188,7 @@ export class GamePlayer {
this.emit(BackendAction.ERROR, {message: `Deck cannot not be changed when ready!`});
return false;
}
const deck: SubInventory | null = await SubInventory.scope("cardObjects").findOne({ where: { objectHash: deckHash } });
const deck: SubInventory | null = await SubInventory.scope("cardObjects").findOne({where: {objectHash: deckHash}});
if (!deck || !deck.objects || !deck.objects.length) {
this.emit(BackendAction.ERROR, {message: `Deck ${deckHash} could not be selected or was empty!`});
return false;
Expand All @@ -216,7 +214,7 @@ export class GamePlayer {
// Move it to the result set
cards.push(card);
// Emit drawn card
this.emit(BackendAction.CARD_DRAWN, { card: card }, {card: {}});
this.emit(BackendAction.CARD_DRAWN, {card: card}, {card: {}});
}
// Add cards to hand
this.cards.push(...cards);
Expand Down Expand Up @@ -271,11 +269,12 @@ export class GamePlayer {
// Get card from field at fieldIndex
const card = this.field.get(fieldIndex);
// Check for empty card
if (!card) {
if (!card || card.health <= 0) {
// Attack player
this.playerHealth(amount);
return;
};
}
;
// Add up amount to health
card.health += amount;
// Emit change of health
Expand All @@ -287,8 +286,8 @@ export class GamePlayer {

playerHealth(amount: number): void {
this.health += amount;
const event = { health: this.health };
this.emit(BackendAction.CARD_HEALTH_CHANGED, event, event);
const event = {health: this.health};
this.emit(BackendAction.PLAYER_HEALTH_CHANGED, event, event);
}

/**
Expand Down
8 changes: 7 additions & 1 deletion api/src/models/object/game.object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,13 @@ export class Game {

atEnd(event: any): void {
console.log('AtEnd');
this.room.emit(SocketAction.FRONTEND_EVENT, {event: GameEvent.END, state: GameState.AT});
const winner = [...this.players.map.values()].reduce((a, b) => a.health > b.health ? a : b);
winner.user.increment({coins: 100});
this.room.emit(SocketAction.FRONTEND_EVENT, {
event: GameEvent.END,
state: GameState.AT,
message: `Player ${winner.user.name} won! Congratulations👏`
});
this.events[GameEvent.END].emit(GameState.AFTER, null);
}

Expand Down
29 changes: 18 additions & 11 deletions api/src/routes/user.routes.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,31 @@
import { Router } from "express";
import { AuthMiddleware as auth } from "../middleware/auth.middleware";
import { RequestMiddleware as middleware } from "../middleware/request.middleware";
import { RequestController as controller } from "../controllers/request.controller";
import { User } from "../models/data/user.model";
import {Router} from "express";
import {AuthMiddleware as auth} from "../middleware/auth.middleware";
import {RequestMiddleware as middleware} from "../middleware/request.middleware";
import {RequestController as controller} from "../controllers/request.controller";
import {User} from "../models/data/user.model";

export const UserRoutes = Router();

UserRoutes.get(["/all", "/all/:page"], [middleware.findAll({ model: User, scopes: ["inventory"], page: { size: 100, key: "page" } })], controller.result(User));
UserRoutes.get(["/all", "/all/:page"], [middleware.findAll({
model: User,
scopes: ["inventory"],
page: {size: 100, key: "page"}
})], controller.result(User));

UserRoutes.post("/", [auth.isAdmin, middleware.add({ model: User })], controller.result(User));
UserRoutes.post("/", [auth.isAdmin, middleware.add({model: User})], controller.result(User));


export const UserIdRoutes = Router();

UserRoutes.use("/:id", [middleware.get({ model: User, body: { key: 'id' } })], UserIdRoutes);
UserRoutes.use("/:id", [middleware.get({model: User, body: {key: 'id'}})], UserIdRoutes);

UserIdRoutes.get("/", controller.result(User));

UserIdRoutes.put("/", [auth.isAdmin, middleware.edit({ model: User })], controller.result(User));
UserIdRoutes.put("/", [auth.isAdmin, middleware.edit({model: User})], controller.result(User));

UserIdRoutes.delete("/", [auth.isAdmin, middleware.remove({ model: User })], controller.message("last"));
UserIdRoutes.delete("/", [auth.isAdmin, middleware.remove({model: User})], controller.message("last"));

UserIdRoutes.get("/friend", [middleware.getAssociation({ model: User, association: { name: "friend" } })], controller.result([User, "friends"]));
UserIdRoutes.get("/friend", [
middleware.getAssociation({model: User, association: {name: "invites"}}),
middleware.getAssociation({model: User, association: {name: "requests"}})
], controller.result([User, "friendAccepted"]));

0 comments on commit a1fb2a2

Please sign in to comment.