mancala/src/index.ts

102 lines
2.9 KiB
TypeScript

import express, { Request, Response } from "express";
import * as http from 'http';
import { decodeText, encodeText } from "./rtmt/byte_util";
import { RTMTWS } from "./rtmt/rtmt_websocket";
import cors from "cors"
import { generateKey } from "./key_factory";
import { MatchMaker } from "./matcmaker";
import { channel_game_move, channel_leave_game, channel_new_game, channel_on_game_crashed, channel_on_game_start, channel_on_game_update, channel_on_game_user_leave } from "./channel_names";
import { Bytes } from "./rtmt/rtmt";
import { createGame, Game, GameMove } from "./mancala";
import morgan from 'morgan';
const app = express();
app.use(cors());
app.use(morgan('dev'));
const server = http.createServer(app);
app.get("/", (req: Request, res: Response) => {
res.send("Server up and running!");
});
app.get("/register/", (req: Request, res: Response) => {
res.send(generateKey());
});
const port = process.env.PORT || 5000
server.listen(port, () => {
console.log(`Server started on port ${port}`);
})
const rtmt = new RTMTWS()
rtmt.initWebSocket(server, (userKey: string) => {
const game = gameStore.get(userKey)
if (game) {
rtmt.sendMessage(userKey, channel_on_game_update, game)
}
})
const matchmaker = new MatchMaker()
rtmt.listenMessage(channel_new_game, (userKey: string, message: Object) => {
matchmaker.find(userKey)
})
const gameStore = new Map<string, Game>()
matchmaker.onPlayersPaired = (userKey1: string, userKey2: string) => {
const game = createGame(userKey1, userKey2)
gameStore.set(userKey1, game)
gameStore.set(userKey2, game)
rtmt.sendMessage(userKey1, channel_on_game_start, game)
rtmt.sendMessage(userKey2, channel_on_game_start, game)
}
rtmt.listenMessage(channel_game_move, (userKey: string, message: Object) => {
const gameMove: GameMove = message as GameMove;
console.log(gameMove);
const game = gameStore.get(userKey)
if (game) {
try {
game.moveByIndex(gameMove.index, game.getPlayerNameByKey(userKey))
rtmt.sendMessage(game.player1, channel_on_game_update, game)
rtmt.sendMessage(game.player2, channel_on_game_update, game)
if (game.state == "ended") {
gameStore.delete(game.player1)
gameStore.delete(game.player2)
}
} catch (err : any) {
console.log(err);
deleteGame(game)
rtmt.sendMessage(game.player1, channel_on_game_crashed, err)
rtmt.sendMessage(game.player2, channel_on_game_crashed, err)
}
} else {
console.log("Game not found!");
}
})
rtmt.listenMessage(channel_leave_game, (userKey: string, message: Object) => {
const game = gameStore.get(userKey)
if (game) {
deleteGame(game)
rtmt.sendMessage(game.player1, channel_on_game_user_leave, userKey)
rtmt.sendMessage(game.player2, channel_on_game_user_leave, userKey)
}
})
const deleteGame = (game: Game) => {
if (game) {
gameStore.delete(game.player1)
gameStore.delete(game.player2)
}
}