Merge pull request #1 from jhalitaksoy/feature/use-mancala-js

Feature/use mancala js
This commit is contained in:
Halit Aksoy 2022-05-04 23:25:09 +03:00 committed by GitHub
commit d05253bbf1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 6649 additions and 1231 deletions

7522
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -20,6 +20,7 @@
"@types/ws": "^7.4.5", "@types/ws": "^7.4.5",
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.17.1", "express": "^4.17.1",
"mancala.js": "^0.0.1",
"morgan": "^1.10.0", "morgan": "^1.10.0",
"uuid": "^8.3.2", "uuid": "^8.3.2",
"ws": "^7.5.0" "ws": "^7.5.0"

View File

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

View File

@ -1,254 +0,0 @@
export class Game {
player1: string
player2: string
board: Board
turn: "player1" | "player2"
state: "playing" | "ended"
constructor(player1: string, player2: string, board: Board, turn: "player1" | "player2", state: "playing" | "ended") {
this.player1 = player1
this.player2 = player2
this.board = board
this.turn = turn
this.state = state
}
public moveByIndex(holeIndex: number, player: "player1" | "player2") {
let hole = this.board.player1Holes[holeIndex]
if (player == "player2") {
hole = this.board.player2Holes[holeIndex]
}
return this.move(hole, player)
}
public move(hole: Hole, player: "player1" | "player2") {
if (this.turn != player) return
if (hole.ballCount == 0) return
let holeIndex = -1
let circle: Array<Hole>
if (player == "player1") {
holeIndex = this.board.player1Holes.indexOf(hole)
circle = this.board.player1Circle()
} else {
holeIndex = this.board.player2Holes.indexOf(hole)
circle = this.board.player2Circle()
}
// if can't find hole in own list
if (holeIndex < 0) {
return
}
const circleSize = circle.length
const stepCount = hole.ballCount
let startIndex = holeIndex
let holeEndBallCount = 1
if (hole.ballCount == 1) {
startIndex = holeIndex + 1
holeEndBallCount = 0
}
let stopIndex = startIndex + stepCount - 1
stopIndex += (stopIndex / circleSize) | 0 // add the number of jump over opponent store
const stopHole = circle[stopIndex % circle.length]
iterateHoles(circle, startIndex, stopIndex, (eachHole: Hole, index: number) => {
if (!checkIsOpponentStore(index, circleSize)) {
eachHole.ballCount++
}
})
hole.ballCount = holeEndBallCount
console.log((stopIndex));
console.log(checkIsOwnHole(stopIndex, circleSize));
if (checkIsOwnHole(stopIndex, circleSize)) {
//check if it was 0 before
if (stopHole.ballCount == 1) {
const ownStore = getOwnStore(circle)
const opponentHole = getOpponentHoleByIndex(stopIndex%16, circle)
if (opponentHole.ballCount > 0) {
ownStore.ballCount++
stopHole.ballCount = 0;
ownStore.ballCount += opponentHole.ballCount
opponentHole.ballCount = 0
}
}
}
if (!checkIsOwnStore(stopIndex, circleSize)) {
this.changeTurn()
}
const ownHoles = circle.slice(0, circle.length / 2 - 1)
let sumBallCount = 0;
for (const hole of ownHoles) sumBallCount += hole.ballCount
if (sumBallCount == 0) {
const opppentHoles = circle.slice(circle.length / 2, circle.length - 1)
let sumOppenentBallCount = 0;
for (const hole of opppentHoles) {
sumOppenentBallCount += hole.ballCount
hole.ballCount = 0
}
getOwnStore(circle).ballCount += sumOppenentBallCount
this.state = "ended"
}
}
public changeTurn() {
if (this.turn == "player1") {
this.turn = "player2"
} else {
this.turn = "player1"
}
}
public clone() { return new Game(this.player1, this.player2, this.board, this.turn, this.state) }
//todo throw expection
public getPlayerNameByKey(key: string): "player1" | "player2" {
if (this.player1 == key) {
return "player1"
} else {
return "player2"
}
}
//todo throw expection
public getPlayerKeyByName(key: "player1" | "player2"): string {
if (this.player1 == key) {
return "player1"
} else {
return "player2"
}
}
public checkGameTurn(user: string): boolean {
return this.getPlayerNameByKey(user) == this.turn
}
public getWonPlayer() : string | undefined {
const player1BallCount = this.board.player1Store.ballCount
const player2BallCount = this.board.player2Store.ballCount
if(player1BallCount < player2BallCount){
return this.getPlayerKeyByName("player2")
}else if(player1BallCount > player2BallCount) {
return this.getPlayerKeyByName("player1")
}else{
return undefined
}
}
}
export function createGame(player1: string, player2: string) {
// const board = new Board(
// [new Hole(0), new Hole(1), new Hole(2), new Hole(3), new Hole(4), new Hole(5)],
// [new Hole(0), new Hole(1), new Hole(2), new Hole(3), new Hole(4), new Hole(5)],
// new Store(0), new Store(0))
const board = new Board(
[new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(4)],
[new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(4)],
new Store(0), new Store(0))
// const board = new Board(
// [new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(1)],
// [new Hole(1), new Hole(0), new Hole(0), new Hole(0), new Hole(1), new Hole(0)],
// new Store(0), new Store(0))
// const board = new Board(
// [new Hole(1), new Hole(1), new Hole(1), new Hole(1), new Hole(1), new Hole(1)],
// [new Hole(1), new Hole(1), new Hole(1), new Hole(1), new Hole(1), new Hole(1)],
// new Store(0), new Store(0))
return new Game(player1, player2, board, "player1", "playing")
}
export class Hole {
public ballCount: number
constructor(ballCount: number) {
this.ballCount = ballCount
}
}
export class Store extends Hole {
constructor(ballCount: number) {
super(ballCount)
}
}
export class Board {
public player1Holes: Array<Hole>
public player2Holes: Array<Hole>
public player1Store: Store
public player2Store: Store
constructor(player1Holes: Array<Hole>, player2Holes: Array<Hole>, player1Store: Store, player2Store: Store) {
this.player1Holes = player1Holes
this.player2Holes = player2Holes
this.player1Store = player1Store
this.player2Store = player2Store
}
// array.reverse didn't work
public player1Circle(): Array<Hole> {
return [...this.player1Holes, this.player1Store, ...this.player2Holes, this.player2Store]
}
// array.reverse didn't work
public player2Circle(): Array<Hole> {
return [...this.player2Holes, this.player2Store, ...this.player1Holes, this.player1Store]
}
public getBallCount(holes : Array<Hole> ) : number {
let ballCount = 0
for (let hole of holes) {
ballCount += hole.ballCount;
}
return ballCount
}
}
function iterateHoles(holes: Array<Hole>, start: number, stop: number, callback: (hole: Hole, index: number) => void) {
for (let index = start; index <= stop; index++) {
callback(holes[index % holes.length], index)
}
}
function reverse(holes: Array<Hole>) {
const array = new Array<Hole>()
for (let index = holes.length - 1; index > -1; index--) {
array.push(holes[index])
}
return array
}
function checkIsOpponentStore(index: number, size: number) { return (index % size) === size - 1 }
function checkIsOpponentHole(index: number, size: number) { return (index % size) >= size / 2 }
function checkIsOwnHole(index: number, size: number) { return (index % size) < size / 2 - 1 }
function checkIsOwnStore(index: number, size: number) { return (index % size) == size / 2 - 1 }
function getOwnStore(circle: Array<Hole>) {
return circle[circle.length / 2 - 1]
}
function getOpponentHoleByIndex(index: number, circle: Array<Hole>) {
return circle[circle.length - 2 - index]
}
export interface GameMove {
index: number,
}

3
src/models/GameMove.ts Normal file
View File

@ -0,0 +1,3 @@
export interface GameMove {
index: number;
}