workadventure/back/src/Model/Group.ts

96 lines
2.3 KiB
TypeScript
Raw Normal View History

import { World, ConnectCallback, DisconnectCallback } from "./World";
2020-09-16 16:06:43 +02:00
import { User } from "./User";
import {PositionInterface} from "_Model/PositionInterface";
import {uuid} from "uuidv4";
2020-09-16 16:06:43 +02:00
import {Movable} from "_Model/Movable";
2020-09-16 16:06:43 +02:00
export class Group implements Movable {
2020-04-07 10:08:04 +02:00
static readonly MAX_PER_GROUP = 4;
private static nextId: number = 1;
private id: number;
2020-09-16 16:06:43 +02:00
private users: Set<User>;
private connectCallback: ConnectCallback;
private disconnectCallback: DisconnectCallback;
2020-04-07 10:08:04 +02:00
2020-09-16 16:06:43 +02:00
constructor(users: User[], connectCallback: ConnectCallback, disconnectCallback: DisconnectCallback) {
this.users = new Set<User>();
this.connectCallback = connectCallback;
this.disconnectCallback = disconnectCallback;
this.id = Group.nextId;
Group.nextId++;
2020-09-16 16:06:43 +02:00
users.forEach((user: User) => {
this.join(user);
});
2020-04-07 10:08:04 +02:00
}
2020-09-16 16:06:43 +02:00
getUsers(): User[] {
return Array.from(this.users.values());
2020-04-07 10:08:04 +02:00
}
getId() : number {
return this.id;
}
/**
* Returns the barycenter of all users (i.e. the center of the group)
*/
getPosition(): PositionInterface {
let x = 0;
let y = 0;
// Let's compute the barycenter of all users.
2020-09-16 16:06:43 +02:00
this.users.forEach((user: User) => {
x += user.position.x;
y += user.position.y;
});
x /= this.users.size;
y /= this.users.size;
return {
x,
y
};
}
2020-04-07 10:08:04 +02:00
isFull(): boolean {
return this.users.size >= Group.MAX_PER_GROUP;
2020-04-07 10:08:04 +02:00
}
2020-04-08 20:40:44 +02:00
isEmpty(): boolean {
return this.users.size <= 1;
}
2020-09-16 16:06:43 +02:00
join(user: User): void
{
// Broadcast on the right event
this.connectCallback(user.id, this);
this.users.add(user);
user.group = this;
}
2020-09-16 16:06:43 +02:00
leave(user: User): void
{
2020-06-29 22:13:07 +02:00
const success = this.users.delete(user);
if (success === false) {
throw new Error("Could not find user "+user.id+" in the group "+this.id);
}
user.group = undefined;
// Broadcast on the right event
this.disconnectCallback(user.id, this);
}
/**
* Let's kick everybody out.
* Usually used when there is only one user left.
*/
destroy(): void
{
2020-06-29 22:13:07 +02:00
for (const user of this.users) {
this.leave(user);
}
2020-04-08 20:40:44 +02:00
}
}