122 lines
3.0 KiB
JavaScript
122 lines
3.0 KiB
JavaScript
import { Ball } from "./Ball.js";
|
|
import { GameConfig } from "./GameConfig.js"
|
|
import { Player } from "./Player.js";
|
|
|
|
class Game
|
|
{
|
|
/**
|
|
* @param {Client} client
|
|
*/
|
|
constructor(client, id)
|
|
{
|
|
/**
|
|
* @type {Client}
|
|
*/
|
|
this.client = client;
|
|
this.id = id;
|
|
}
|
|
|
|
async init()
|
|
{
|
|
let response = await this.client._get(`/api/games/${this.id}`);
|
|
|
|
if (response.status !== 200)
|
|
return response.status;
|
|
|
|
let response_data = await response.json();
|
|
|
|
this.players_id = response_data.players_id;
|
|
this.state = response_data.state;
|
|
this.started = response_data.started;
|
|
this.finished = response_data.finished;
|
|
this.winner_id = this.finished ? response_data.winner_id : undefined;
|
|
|
|
//TODO invert line
|
|
if (false)
|
|
//if (this.finished === true || this.started === false)
|
|
return 0;
|
|
|
|
this.config = new GameConfig(this.client);
|
|
|
|
let ret = await this.config.init();
|
|
if (ret !== 0)
|
|
return ret;
|
|
|
|
this.players = [];
|
|
response_data.players.forEach(player_data => {
|
|
let player = new Player(player_data.id, player_data.pos, player_data.nb_goal);
|
|
this.players.push(player);
|
|
});
|
|
|
|
this.ball = new Ball(response_data.ball_pos_x, response_data.ball_pos_y, response_data.ball_vel_x, response_data.ball_vel_y);
|
|
|
|
return 0;
|
|
}
|
|
|
|
_send(data)
|
|
{
|
|
this._socket.send(JSON.stringify(data));
|
|
}
|
|
|
|
_send_paddle()
|
|
{
|
|
this._send({"detail": "update_my_paddle_pos", "pos": this.players.find(player => player.id === this.client.me.id).pos});
|
|
}
|
|
|
|
_update_paddles(data)
|
|
{
|
|
data.forEach(player_data => {
|
|
let player = this.players.find(player_data2 => player_data2.id === player_data)
|
|
|
|
if (player === null)
|
|
{
|
|
console.error("error 1000: je ne comprends pas");
|
|
return;
|
|
}
|
|
|
|
player.pos = player_data.pos;
|
|
});
|
|
}
|
|
|
|
_update_ball(data)
|
|
{
|
|
this.ball.position_x = data.position_x;
|
|
this.ball.position_y = data.position_y;
|
|
this.ball.velocity_x = data.velocity_x;
|
|
this.ball.velocity_y = data.velocity_y;
|
|
}
|
|
|
|
_update(data)
|
|
{
|
|
if (data.detail === "update_paddles")
|
|
this._update_paddles(data);
|
|
else if (data.detail === "update_ball")
|
|
this._
|
|
}
|
|
|
|
join()
|
|
{
|
|
if (this.started !== true || this.finished === true)
|
|
{
|
|
console.error("The Game is not currently ongoing.");
|
|
return;
|
|
}
|
|
|
|
let url = `${window.location.protocol[4] === 's' ? 'wss' : 'ws'}://${window.location.host}/ws/games/${this.id}`;
|
|
|
|
this._socket = WebSocket(url);
|
|
|
|
this._socket.onmessage = (event) => {
|
|
const data = JSON.parse(event.data);
|
|
this._update(data);
|
|
};
|
|
}
|
|
|
|
leave()
|
|
{
|
|
this._socket.close();
|
|
this._socket = undefined;
|
|
}
|
|
}
|
|
|
|
export { Game } |