76 lines
2.4 KiB
TypeScript
76 lines
2.4 KiB
TypeScript
import axios from "axios";
|
|
import { Message, MessageType } from "../models/Message";
|
|
import { Answer } from "../models/Answer";
|
|
|
|
const webProt = "http://";
|
|
const baseURL = "localhost:8000";
|
|
|
|
export const axios_api = axios.create({
|
|
baseURL: webProt + baseURL,
|
|
headers: {
|
|
"Accept": "application/json",
|
|
"Content-Type": "application/json",
|
|
},
|
|
});
|
|
|
|
export class Game {
|
|
public uuid!: string;
|
|
public owner!: boolean;
|
|
public you!: number;
|
|
private pub: WebSocket;
|
|
private sub: WebSocket;
|
|
|
|
constructor(code: string, name: string, message_callback: (message: Message) => void) {
|
|
this.pub = new WebSocket(`ws://${baseURL}/ws/room/${code}/pub`);
|
|
this.sub = new WebSocket(`ws://${baseURL}/ws/room/${code}/sub`);
|
|
|
|
this.pub.addEventListener("open", (event) => {
|
|
console.info("pub-ws connected");
|
|
const join = new Message(MessageType.JOIN, name);
|
|
this.pub.send(JSON.stringify(join));
|
|
});
|
|
|
|
this.pub.addEventListener("message", (event) => {
|
|
const msg: Message = JSON.parse(event.data);
|
|
if (msg.msgtype === MessageType.JOIN) {
|
|
this.uuid = msg.data.uuid;
|
|
this.owner = msg.data.owner;
|
|
this.you = msg.data.you;
|
|
} else {
|
|
message_callback(msg);
|
|
}
|
|
});
|
|
|
|
this.sub.addEventListener("open", (event) => {
|
|
console.info("sub-ws connected");
|
|
});
|
|
|
|
this.sub.addEventListener("message", (event) => {
|
|
if (event.data === "1") {
|
|
console.info("Hyperadvanced one way websocket connection established");
|
|
return;
|
|
}
|
|
console.log(event.data);
|
|
const msg: Message = JSON.parse(event.data);
|
|
message_callback(msg);
|
|
});
|
|
}
|
|
|
|
public start_game() {
|
|
const msg = new Message(MessageType.START, this.uuid);
|
|
this.pub.send(JSON.stringify(msg));
|
|
}
|
|
|
|
public send_answer(text: string[]) {
|
|
const answers = new Answer(text, this.uuid);
|
|
const msg = new Message(MessageType.ANSWER, JSON.stringify(answers));
|
|
this.pub.send(JSON.stringify(msg));
|
|
}
|
|
|
|
public pick_answer(answer: Answer) {
|
|
answer.uuid = this.uuid;
|
|
const msg = new Message(MessageType.PICK, JSON.stringify(answer));
|
|
this.pub.send(JSON.stringify(msg));
|
|
}
|
|
}
|