2021-07-06 17:13:08 +02:00
|
|
|
import { writable } from "svelte/store";
|
2021-07-07 11:24:51 +02:00
|
|
|
import type { PlayerInterface } from "../Phaser/Game/PlayerInterface";
|
|
|
|
import type { RoomConnection } from "../Connexion/RoomConnection";
|
2021-07-07 18:07:58 +02:00
|
|
|
import { getRandomColor } from "../WebRtc/ColorGenerator";
|
2021-07-06 17:13:08 +02:00
|
|
|
|
2021-07-15 19:12:19 +02:00
|
|
|
let idCount = 0;
|
|
|
|
|
2021-07-06 17:13:08 +02:00
|
|
|
/**
|
|
|
|
* A store that contains the list of players currently known.
|
|
|
|
*/
|
|
|
|
function createPlayersStore() {
|
|
|
|
let players = new Map<number, PlayerInterface>();
|
|
|
|
|
|
|
|
const { subscribe, set, update } = writable(players);
|
|
|
|
|
|
|
|
return {
|
|
|
|
subscribe,
|
|
|
|
connectToRoomConnection: (roomConnection: RoomConnection) => {
|
|
|
|
players = new Map<number, PlayerInterface>();
|
|
|
|
set(players);
|
|
|
|
roomConnection.onUserJoins((message) => {
|
|
|
|
update((users) => {
|
|
|
|
users.set(message.userId, {
|
|
|
|
userId: message.userId,
|
|
|
|
name: message.name,
|
|
|
|
characterLayers: message.characterLayers,
|
|
|
|
visitCardUrl: message.visitCardUrl,
|
|
|
|
companion: message.companion,
|
2021-07-07 11:24:51 +02:00
|
|
|
userUuid: message.userUuid,
|
2021-07-07 18:07:58 +02:00
|
|
|
color: getRandomColor(),
|
2021-07-06 17:13:08 +02:00
|
|
|
});
|
|
|
|
return users;
|
|
|
|
});
|
|
|
|
});
|
|
|
|
roomConnection.onUserLeft((userId) => {
|
|
|
|
update((users) => {
|
|
|
|
users.delete(userId);
|
|
|
|
return users;
|
|
|
|
});
|
|
|
|
});
|
|
|
|
},
|
2021-07-07 11:24:51 +02:00
|
|
|
getPlayerById(userId: number): PlayerInterface | undefined {
|
2021-07-06 17:13:08 +02:00
|
|
|
return players.get(userId);
|
2021-07-07 11:24:51 +02:00
|
|
|
},
|
2021-07-15 19:12:19 +02:00
|
|
|
addFacticePlayer(name: string): number {
|
|
|
|
let userId: number | null = null;
|
|
|
|
players.forEach((p) => {
|
|
|
|
if (p.name === name) userId = p.userId;
|
|
|
|
});
|
|
|
|
if (userId) return userId;
|
|
|
|
const newUserId = idCount--;
|
|
|
|
update((users) => {
|
|
|
|
users.set(newUserId, {
|
|
|
|
userId: newUserId,
|
|
|
|
name,
|
|
|
|
characterLayers: [],
|
|
|
|
visitCardUrl: null,
|
|
|
|
companion: null,
|
|
|
|
userUuid: "dummy",
|
|
|
|
color: getRandomColor(),
|
|
|
|
});
|
|
|
|
return users;
|
|
|
|
});
|
|
|
|
return newUserId;
|
|
|
|
},
|
2021-07-06 17:13:08 +02:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export const playersStore = createPlayersStore();
|