cla66ic/classes/Player.ts

81 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-06-01 22:30:34 +00:00
import { Position, Rotation, World } from "./classes.ts";
import { PacketDefinitions, PacketWriter } from "./Packets.ts";
import { log } from "../deps.ts";
import { Server } from "./Server.ts";
export class Player {
socket: Deno.Conn;
private server: Server;
username: string;
2022-06-03 12:17:16 +00:00
id: number;
2022-06-01 22:30:34 +00:00
world = "main";
position: Position;
rotation: Rotation = { yaw: 0, pitch: 0 };
constructor(
socket: Deno.Conn,
username: string,
position: Position,
server: Server,
) {
this.socket = socket;
this.username = username;
this.position = position;
this.server = server;
2022-06-03 12:17:16 +00:00
let id = Math.floor(Math.random() * 255);
// reassigns ID until finds available one
// if we reach 255 players this will loop forever
2022-06-03 12:36:34 +00:00
while (server.players.find((e) => e.id == id)) {
id = Math.floor(Math.random() * 255);
}
2022-06-03 12:17:16 +00:00
this.id = id;
2022-06-01 22:30:34 +00:00
}
async writeToSocket(ar: Uint8Array) {
await this.socket.write(ar).catch((e) => {
log.critical(e);
this.server.removeUser(this.socket);
});
}
message(text: string, id = 0) {
text.replaceAll("%", "&").match(/.{1,64}/g)?.forEach(async (pic) => {
await this.writeToSocket(
new PacketWriter()
.writeByte(0x0d)
.writeSByte(id)
.writeString(pic)
.toPacket(),
);
});
}
async toWorld(world: World) {
this.server.broadcastPacket(
2022-06-03 12:17:16 +00:00
(e) => PacketDefinitions.despawn(this.id, e),
2022-06-01 22:30:34 +00:00
this,
);
this.world = world.name;
PacketDefinitions.sendPackets(this, world);
this.server.broadcastPacket(
2022-06-03 12:36:34 +00:00
(e) => PacketDefinitions.spawn(this, this.id, e),
2022-06-01 22:30:34 +00:00
this,
);
this.server.broadcastPacket(
2022-06-03 12:17:16 +00:00
(e) => PacketDefinitions.spawn(e, e.id, this),
2022-06-01 22:30:34 +00:00
this,
);
this.message("You have been moved.");
await world.save();
}
}