refactor MatchMaker

This commit is contained in:
Halit Aksoy 2022-07-15 21:42:02 +03:00
parent 90d55d4063
commit d97ae80c67
3 changed files with 32 additions and 22 deletions

View File

@ -0,0 +1,6 @@
export type OnPlayersPaired = (player1Id: string, player2Id: string)=> void;
export interface MatchMaker {
join(playerId : string): void;
listenOnPlayersPaired(onPlayersPaired: OnPlayersPaired ) : void;
}

View File

@ -0,0 +1,26 @@
import { MatchMaker, OnPlayersPaired } from "./MatchMaker";
export class MatchMakerImpl implements MatchMaker {
private waitingUserKey : string | undefined
private onPlayersPaired: OnPlayersPaired | undefined = undefined;
private fireOnPlayerPaired(player1Id: string, player2Id: string) : void {
this.onPlayersPaired?.(player1Id, player2Id)
}
public join(playerId : string): void {
if(this.waitingUserKey === playerId) return;
if(this.waitingUserKey){
const user1 = this.waitingUserKey as string
this.waitingUserKey = undefined
this.fireOnPlayerPaired(user1, playerId)
}else{
this.waitingUserKey = playerId
}
}
public listenOnPlayersPaired(onPlayersPaired: OnPlayersPaired ) : void {
this.onPlayersPaired = onPlayersPaired;
}
}

View File

@ -1,22 +0,0 @@
// todo : use queue
export class MatchMaker {
private waitingUserKey : string | undefined
public onPlayersPaired!: (userKey1: string, userKey2: string) => void
public find(userKey : string) : void{
if(this.waitingUserKey === userKey) return;
if(this.waitingUserKey){
const user1 = this.waitingUserKey as string
this.waitingUserKey = undefined
this.fireOnPlayerPaired(user1, userKey)
}else{
this.waitingUserKey = userKey
}
}
private fireOnPlayerPaired(userKey1 : string, userKey2 : string) : void {
this.onPlayersPaired!!(userKey1, userKey2)
}
}