cla66ic/classes/Player.ts

83 lines
1.9 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 { config, log } from "../deps.ts";
2022-06-01 22:30:34 +00:00
import { Server } from "./Server.ts";
export class Player {
socket: Deno.Conn;
private server: Server;
username: string;
2022-07-10 14:30:26 +00:00
ip: string;
2022-06-03 12:17:16 +00:00
id: number;
world = config.main;
2022-06-01 22:30:34 +00:00
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-07-10 14:30:26 +00:00
this.ip = (this.socket.remoteAddr as Deno.NetAddr).hostname;
2022-07-10 14:30:26 +00:00
let id = Math.floor(Math.random() * server.maxUsers);
2022-06-03 12:17:16 +00:00
// reassigns ID until finds available one
2022-07-10 14:30:26 +00:00
2022-06-03 12:36:34 +00:00
while (server.players.find((e) => e.id == id)) {
2022-07-10 14:30:26 +00:00
id = Math.floor(Math.random() * server.maxUsers);
2022-06-03 12:36:34 +00:00
}
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(async (e) => {
2022-06-01 22:30:34 +00:00
log.critical(e);
2022-11-13 15:19:56 +00:00
await this.server.removeUser(
this.socket,
"Write failed" + e.message.split("\n")[0],
);
2022-06-01 22:30:34 +00:00
});
}
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(),
);
});
}
2022-07-10 14:30:26 +00:00
toWorld(world: World) {
2022-06-01 22:30:34 +00:00
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.");
}
}