Skip to content

Commit

Permalink
#22 convert server side to typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
edumudu committed Jul 27, 2020
1 parent fa166bc commit cf154d4
Show file tree
Hide file tree
Showing 9 changed files with 211 additions and 28 deletions.
4 changes: 4 additions & 0 deletions client/src/js/Game/Scoreboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,13 @@ class Scoreboard {

public initValues() : void {
const { scoreboard, myHits, enemyHits } = this.els;
const { enemy, my } = this.hits;

myHits.classList.add('hits', 'my-hits');
enemyHits.classList.add('hits', 'enemy-hits');

this.myHits = my;
this.enemyHits = enemy;

scoreboard.append(myHits, enemyHits);
}
Expand Down
9 changes: 9 additions & 0 deletions server/@types/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export interface CardJSON {
id: string;
order: number;
icon: string;
}

export interface CardAPI {
icon: string;
}
23 changes: 13 additions & 10 deletions server/app.js → server/app.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
const Express = require('express')();
const Http = require('http').Server(Express);
const io = require('socket.io')(Http);
import Express from 'express';
import Http from 'http';
import socket, { Packet } from 'socket.io';

const cards = require('./src/data/cards');
const Board = require('./src/Board');
const app = new Http.Server(Express());
const io = socket(app);

const games = {};
import cards from './src/data/cards';
import Board from './src/Board';

const games : Record<string, Board> = {};

io.on('connection', socket => {
let userRoom;
let userRoom : string;

socket.on('room', room => {
const rooms = io.sockets.adapter.rooms;
Expand Down Expand Up @@ -60,7 +63,7 @@ io.on('connection', socket => {
const winner = game.checkIfFinish();

if(winner) {
io.in(room).clients((error, clients) => {
io.in(room).clients((error : Packet, clients : string[]) => {
if(error) throw error;

clients.map(socketId => io.sockets.sockets[socketId])
Expand All @@ -83,12 +86,12 @@ io.on('connection', socket => {
io.sockets.in(userRoom).emit('enemy-left');
delete games[userRoom];

io.in(userRoom).clients((error, clients) => {
io.in(userRoom).clients((error : Packet, clients : string[]) => {
if(error) throw error;

clients.forEach(socketId => io.sockets.sockets[socketId].leave(userRoom));
})
}
});

Http.listen(process.env.PORT || 3000);
app.listen(process.env.PORT || 3000);
9 changes: 7 additions & 2 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@
"main": "index.js",
"license": "MIT",
"scripts": {
"dev": "nodemon app.js",
"dev": "nodemon --watch '*.ts' --exec 'ts-node' app.ts",
"start": "node app.js"
},
"dependencies": {
"express": "^4.17.1",
"socket.io": "^2.3.0"
},
"devDependencies": {
"nodemon": "^2.0.4"
"@types/express": "^4.17.7",
"@types/node": "^14.0.26",
"@types/socket.io": "^2.1.10",
"nodemon": "^2.0.4",
"ts-node": "^8.10.2",
"typescript": "^3.9.7"
}
}
46 changes: 32 additions & 14 deletions server/src/Board.js → server/src/Board.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import { CardJSON, CardAPI } from "../@types";

interface ScoreBoard extends Record<string, number>{
total : number;
}

class Board {
constructor (cards, players) {
private elapsedTime : number;
private cards : CardJSON[];
private players : string[];
private activesCards : CardJSON[];
private matches : CardJSON[];
public scoreboard : ScoreBoard;
public rematchRequests : number;
public playerOfTheTime : string;

constructor (cards : CardAPI[], players : string[]) {
this.elapsedTime = 0;
this.cards = this.shuffle([...cards, ...cards].map(card => ({ ...card })));
this.players = players;
Expand All @@ -11,17 +26,20 @@ class Board {
this.playerOfTheTime = players[Math.floor(Math.random() * 2)];
}

shuffle (cards) {
return cards.map(card => {
private shuffle (cards : CardAPI[]) : CardJSON[] {
return cards.map(({ icon }) => {
const randomNumber = Math.floor(Math.random() * cards.length);
card.order = randomNumber;
card.id = `_${Math.random().toString(36).substr(2, 9)}`;

const card : CardJSON = {
icon,
order: randomNumber,
id: `_${Math.random().toString(36).substr(2, 9)}`
};

return card;
});
}

click (id) {
public click (id : string) : CardJSON[] {
const card = this.cards.find(card => card.id === id);

if(!card || !this.checkIfCanFlip(id) || this.activesCards.length >= 2) return this.activesCards;
Expand All @@ -31,7 +49,7 @@ class Board {
return this.activesCards;
}

checkIfMatch () {
public checkIfMatch () : boolean {
const [first, second] = this.activesCards;
const isMatch = first.icon === second.icon;

Expand All @@ -41,30 +59,30 @@ class Board {
return isMatch;
}

checkIfCanFlip (id) {
public checkIfCanFlip (id : string) : boolean {
const containInActives = this.activesCards.some(card => card.id === id);
const containInMatches = this.matches.some(card => card.id === id);

return !(containInActives || containInMatches)
}

checkIfFinish () {
public checkIfFinish () : boolean | string {
if(this.scoreboard.total === this.cards.length / 2) {
return this.players.reduce((winner, client) => this.scoreboard[client] > this.scoreboard[winner] ? client : winner);
}

return false;
}

incrementHits () {
public incrementHits () : void {
const score = this.scoreboard[this.playerOfTheTime]
this.scoreboard[this.playerOfTheTime] = (score || 0) + 1;
this.scoreboard.total++;
}

togglePlayer () {
this.playerOfTheTime = this.players.find(player => player !== this.playerOfTheTime);
public togglePlayer () : void {
this.playerOfTheTime = this.players.find(player => player !== this.playerOfTheTime) || '';
}
}

module.exports = Board;
export default Board;
Empty file removed server/src/Card.js
Empty file.
4 changes: 2 additions & 2 deletions server/src/data/cards.js → server/src/data/cards.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Simulate a API request

module.exports = [
export default [
{ icon: 'fas spider' },
{ icon: 'fas otter' },
{ icon: 'fas hippo' },
Expand All @@ -12,4 +12,4 @@ module.exports = [
{ icon: 'fas dove' },
{ icon: 'fas cat' },
{ icon: 'fas crow' },
]
];
13 changes: 13 additions & 0 deletions server/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */

"strict": true, /* Enable all strict type-checking options. */

"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */

"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
Loading

0 comments on commit cf154d4

Please sign in to comment.