game: online: recoded but collision not work

This commit is contained in:
2024-05-14 03:28:05 +02:00
parent 18bc8a0028
commit 7a0ff15cec
16 changed files with 518 additions and 653 deletions

View File

@ -2,6 +2,7 @@ import { AExchangeable } from "../AExchangable.js";
import { APlayer } from "./APlayer.js";
import { Client } from "../Client.js"
import { sleep } from "../../utils/sleep.js";
import { Profile } from "../Profile.js";
export class AGame extends AExchangeable
{
@ -44,9 +45,9 @@ export class AGame extends AExchangeable
this._disconntectHandler = disconntectHandler;
/**
* @type {Number}
* @type {Profile}
*/
this.winnerId;
this.winner;
/**
* @type {Number}

View File

@ -6,7 +6,6 @@ import { Client } from "../../Client.js";
import { PongBall } from "./PongBall.js";
import { sleep } from "../../../utils/sleep.js";
import { Wall } from "./Wall.js"
import { Point } from "./Point.js";
import { Position } from "./Position.js";
export class PongGame extends AGame
@ -16,9 +15,10 @@ export class PongGame extends AGame
* @param {CallableFunction} goal_handler
* @param {CallableFunction} finish_handler
* @param {CallableFunction} disconnect_handler
* @param {CallableFunction} startHandler
* @param {Number} id
*/
constructor(client, id, disconnectHandler, goalHandler, finishHandler)
constructor(client, id, disconnectHandler, goalHandler, startHandler, finishHandler)
{
super(client, id, undefined, disconnectHandler, "pong");
@ -28,6 +28,11 @@ export class PongGame extends AGame
* @type {CallableFunction}
*/
this._goalHandler = goalHandler;
/**
* @type {CallableFunction}
*/
this._startHandler = startHandler;
/**
* @type {CallableFunction}
@ -39,7 +44,6 @@ export class PongGame extends AGame
*/
this.time;
/**
* @type {Boolean}
*/
@ -53,7 +57,7 @@ export class PongGame extends AGame
/**
* @type {Ball}
*/
this.ball = new PongBall(this, undefined, new Position());
this.ball = new PongBall(this, undefined, new Position(), 0, 0);
/**
* @type {[Wall]}
@ -122,18 +126,14 @@ export class PongGame extends AGame
*/
render(ctx)
{
if(ctx instanceof CanvasRenderingContext2D)
ctx.clearRect(0, 0, this.config.MAP_SIZE_Y, this.config.MAP_SIZE_Y);
ctx.clearRect(0, 0, this.config.MAP_SIZE_Y, this.config.MAP_SIZE_Y);
this.drawSides(ctx);
this.ball.render(ctx);
if(ctx instanceof CanvasRenderingContext2D)
{
ctx.strokeStyle = "#000000";
ctx.lineWidth = this.config.STROKE_THICKNESS;
ctx.stroke();
}
ctx.strokeStyle = "#000000";
ctx.lineWidth = this.config.STROKE_THICKNESS;
ctx.stroke();
}
/**
@ -149,6 +149,8 @@ export class PongGame extends AGame
*/
async _receive(data)
{
console.log(data)
if (this._inited === false && data.detail === "init_game")
{
this._initGame(data);
@ -162,7 +164,23 @@ export class PongGame extends AGame
else if (data.detail === "goal")
await this._receiveGoal(data);
else if (data.detail === "finish")
await this._finishHandler(data);
await this._receiveFinish(data);
else if (data.detail === "start")
await this._receiveStart();
}
async _receiveFinish(data)
{
const winner = this.players.find(player => player.id === data.winner_id)
this.finished = true;
await this._finishHandler(winner);
}
async _receiveStart()
{
this.started = true;
await this._startHandler();
}
async _receiveGoal(data)
@ -176,6 +194,7 @@ export class PongGame extends AGame
}
player.score.push(data.timestamp)
console.log(player)
await this._goalHandler(player);
}
@ -192,26 +211,6 @@ export class PongGame extends AGame
this.ball.import(data);
}
async _updateGoal(data)
{
/**
* @type { Player }
*/
let player_found;
this.players.forEach(player => {
if (data.player_id === player.id)
{
player_found = player;
return;
}
});
player_found.score.push(data.timestamp);
await this._goalHandler(player_found);
}
_initGame(data)
{
data.walls.forEach((wall_data) => {

View File

@ -4,7 +4,7 @@ import { Segment } from "./Segment.js";
import { PongGame } from "./PongGame.js";
import { Position } from "./Position.js";
export class MyPlayer extends PongPlayer
export class PongMyPlayer extends PongPlayer
{
/**
* @param {Client} client

View File

@ -17,8 +17,9 @@ export class PongPlayer extends APlayer
* @param {String} username
* @param {String} avatar
* @param {Client} client
* @param {Boolean} isEliminated
*/
constructor(client, game, id, username, avatar, score = [], rail = new Segment(game), position = new Position(0.5), isConnected)
constructor(client, game, id, username, avatar, score = [], rail = new Segment(game), position = new Position(0.5), isConnected, isEliminated)
{
super(client, game, id, username, avatar, isConnected)
@ -41,6 +42,11 @@ export class PongPlayer extends APlayer
* @type {PongPlayer}
*/
this.game = game;
/**
* @type {Boolean}
*/
this.isEliminated = isEliminated;
}
/**
@ -57,13 +63,10 @@ export class PongPlayer extends APlayer
*/
draw(ctx)
{
if (this.isConnected === false)
if (this.isConnected === false || this.isEliminated === true)
{
if(ctx instanceof CanvasRenderingContext2D)
{
ctx.moveTo(this.rail.start.x, this.rail.start.y);
ctx.lineTo(this.rail.stop.x, this.rail.stop.y);
}
ctx.moveTo(this.rail.start.x, this.rail.start.y);
ctx.lineTo(this.rail.stop.x, this.rail.stop.y);
return;
}

View File

@ -4,7 +4,7 @@ import Search from "./views/Search.js";
import HomeView from "./views/HomeView.js";
import LogoutView from "./views/accounts/LogoutView.js";
import { PongOnlineView } from "./views/PongOnlineView.js"
import PongOnlineView from "./views/PongOnlineView.js"
import { PongOfflineView } from "./views/PongOfflineView.js"
import { TicTacToeOnlineView } from "./views/TicTacToeOnlineView.js"

View File

@ -1,214 +1,95 @@
import { client, reloadView, lang } from "../index.js";
import { initShaderProgram, shaderInfos } from "../3D/shaders.js"
import { initBuffers } from "../3D/buffers.js"
import "../3D/maths/gl-matrix-min.js"
import "../chartjs/chart.umd.min.js";
import { get_labels, transformData } from "../utils/graph.js";
import { sleep } from "../utils/sleep.js";
import AbstractAuthenticatedView from "./abstracts/AbstractAuthenticatedView.js";
import { client, reloadView } from "../index.js";
import { PongGame } from "../api/game/pong/PongGame.js";
import { MyPlayer } from "../api/game/pong/PongMyPlayer.js";
import { PongPlayer } from "../api/game/pong/PongPlayer.js";
import AbstractAuthenticatedView from "./abstracts/AbstractAuthenticatedView.js";
import { Profile } from "../api/Profile.js";
import { PongMyPlayer } from "../api/game/pong/PongMyPlayer.js";
export class PongOnlineView extends AbstractAuthenticatedView
export default class PongOnlineView extends AbstractAuthenticatedView
{
constructor(params)
{
super(params, "Game");
this.game_id = params.id;
this.ctx = null;
this.shader_prog = null;
this.buffers = null;
this.cam_pos = [0, 400, 0];
this.cam_target = [0, 0, 0];
this.cam_up = [0, 0, -1];
this.game_mode = 1; // 1 is 2D, 2 is 3D
super(params, 'Pong');
/**
* @type {MyPlayer}
* @type {Number}
*/
this.myPlayer;
}
this.game_id = params.id;
/**
* @type {PongGame}
*/
this.game;
initWebGL()
{
let canva = document.createElement("canvas");
canva.height = this.game.config.MAP_SIZE_X;
canva.width = this.game.config.MAP_SIZE_Y;
canva.id = "canva";
document.getElementById("app").appendChild(canva);
/**
* @type {HTMLCanvasElement}
*/
this.canva;
this.ctx = canva.getContext("webgl");
/**
* @type {CanvasRenderingContext2D}
*/
this.gameboard;
if(this.ctx === null)
{
alert("Unable to initialize WebGL. Your browser or machine may not support it. You may also be a bozo");
return;
}
/**
* @type {HTMLElement}
*/
this.gamestate;
this.shader_prog = initShaderProgram(this.ctx);
this.buffers = initBuffers(this.ctx);
/**
* @type {HTMLTableElement}
*/
this.scoreboard;
this.ctx.enable(this.ctx.CULL_FACE);
this.ctx.cullFace(this.ctx.BACK);
/**
* @type {HTMLElement}
*/
this.app = document.getElementById("app");
/**
* @type {[]}
*/
this.keysPressed
}
init2D()
createMyPlayer()
{
let canva = document.createElement("canvas");
canva.height = this.game.config.MAP_SIZE_X;
canva.width = this.game.config.MAP_SIZE_Y;
canva.id = "canva";
document.getElementById("app").appendChild(canva);
let index = this.game.players.findIndex((player) => player.id === client.me.id);
this.ctx = canva.getContext('2d');
if (index === -1)
return;
let myPlayer = this.game.players[index];
if (myPlayer.isEliminated)
return;
this.keysPressed = [];
this.myPlayer = new PongMyPlayer(client,
this.game,
myPlayer.score,
myPlayer.rail,
myPlayer.position,
);
myPlayer = this.myPlayer;
this.registerKey();
}
keyReleaseHandler(event)
{
const idx = this.keys_pressed.indexOf(event.key);
const idx = this.keysPressed.indexOf(event.key);
if (idx != -1)
this.keys_pressed.splice(idx, 1);
this.keysPressed.splice(idx, 1);
}
keyPressHandler(event)
{
if (!this.keys_pressed.includes(event.key))
this.keys_pressed.push(event.key);
}
setNormalAttribute()
{
const numComponents = 3;
const type = this.ctx.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
this.ctx.bindBuffer(this.ctx.ARRAY_BUFFER, this.buffers.normal);
this.ctx.vertexAttribPointer(
shaderInfos.attribLocations.vertexNormal,
numComponents,
type,
normalize,
stride,
offset,
);
this.ctx.enableVertexAttribArray(shaderInfos.attribLocations.vertexNormal);
}
setPositionAttribute()
{
const numComponents = 3;
const type = this.ctx.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
this.ctx.bindBuffer(this.ctx.ARRAY_BUFFER, this.buffers.vertex);
this.ctx.bindBuffer(this.ctx.ELEMENT_ARRAY_BUFFER, this.buffers.index);
this.ctx.vertexAttribPointer(
shaderInfos.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset
);
this.ctx.enableVertexAttribArray(shaderInfos.attribLocations.vertexPosition);
}
renderGame()
{
const canva = document.getElementById('canva');
if (canva === null)
return 1;
if(this.ctx instanceof CanvasRenderingContext2D)
{
this.ctx.beginPath();
this.game.render(this.ctx);
this.ctx.strokeStyle = "#000000";
this.ctx.lineWidth = 1;
this.ctx.stroke();
}
else if(this.ctx instanceof WebGLRenderingContext)
{
this.ctx.clearColor(0.1, 0.1, 0.1, 1.0);
this.ctx.clearDepth(1.0);
this.ctx.enable(this.ctx.DEPTH_TEST);
this.ctx.depthFunc(this.ctx.LEQUAL);
this.ctx.clear(this.ctx.COLOR_BUFFER_BIT | this.ctx.DEPTH_BUFFER_BIT);
const projectionMatrix = mat4.create();
const viewMatrix = mat4.create();
mat4.perspective(projectionMatrix, (90 * Math.PI) / 180, this.ctx.canvas.clientWidth / this.ctx.canvas.clientHeight, 0.1, 10000000.0);
mat4.lookAt(viewMatrix, this.cam_pos, this.cam_target, this.cam_up);
this.setPositionAttribute();
this.setNormalAttribute();
this.ctx.useProgram(shaderInfos.program);
this.ctx.uniformMatrix4fv(shaderInfos.uniformLocations.projectionMatrix, false, projectionMatrix);
this.ctx.uniformMatrix4fv(shaderInfos.uniformLocations.viewMatrix, false, viewMatrix);
this.game.render(this.ctx);
}
else
{
alert('Unknown rendering context type');
}
}
/**
* @param {PongPlayer} player
* @returns { Promise }
*/
async onGoal(player)
{
document.getElementById(`goal-${player.id}`).innerText = player.score.length;
}
/**
* @param {*} data
* @returns { Promise }
*/
async onFinish(data /* unused */)
{
await reloadView();
}
render()
{
let loop_id = setInterval(() => {
if (this.game === undefined)
clearInterval(loop_id);
this.myPlayer?.updatePaddle(this.keys_pressed);
this.renderGame();
this.game?.time?.new_frame();
//clearInterval(loop_id);
// 1 sec fps
}, 1000 / 60);
}
async toggleGameMode()
{
if(this.game_mode === 1) // 3D
{
this.game_mode = 2;
document.getElementById("game-mode").value = "Switch to 2D";
}
else if(this.game_mode === 2) // 2D
{
this.game_mode = 1;
document.getElementById("game-mode").value = "Switch to 3D";
}
const canva = document.getElementById('canva');
if (canva === null)
return;
document.getElementById("app").removeChild(canva);
this.createGameBoard(this.game_mode);
console.log("bozo")
if (!this.keysPressed.includes(event.key))
this.keysPressed.push(event.key);
}
registerKey()
@ -226,187 +107,155 @@ export class PongOnlineView extends AbstractAuthenticatedView
}
/**
* @param {int} game_mode
* @returns { Cramptex }
* @param {PongPlayer} player
*/
createGameBoard(game_mode)
async onGoal(player)
{
if(game_mode === 1)
this.init2D();
else if(game_mode === 2)
this.initWebGL();
document.getElementById(`score-${player.id}`).innerText = player.score.length;
}
createMyPlayer()
async onStart()
{
let index = this.game.players.findIndex((player) => player.id === client.me.id);
if (index !== -1)
{
let myPlayer = this.game.players[index];
this.myPlayer = new MyPlayer(client,
this.game,
myPlayer.score,
myPlayer.rail,
myPlayer.position,
);
this.game.players[index] = this.myPlayer;
}
this.gamestate.innerHTML = this.game.getState();
}
async joinGame()
/**
* @param {PongPlayer} winner
*/
async onFinish(winner)
{
document.getElementById("game-mode").onclick = this.toggleGameMode.bind(this);
await this.game.join();
await this.game.waitInit();
this.createGameBoard(1); // create the board for 2D game by default. Can switch to 3D with a toggle
this.createMyPlayer();
this.displayPlayersList();
this.registerKey();
this.render();
}
async updateGameState()
{
document.getElementById("game-state").innerText = this.game.state;
if (this.game.finished === false)
await this.joinGame();
else
{
this.createGraph();
let toggle = document.getElementById("game-mode");
if(toggle !== null)
toggle.remove();
}
}
createGraph()
{
let players = this.game.players;
if (players === undefined)
return;
let graph = document.createElement("canvas");
graph.height = 450;
graph.width = 800;
graph.id = "graph";
document.getElementById("app").appendChild(graph);
if (graph === null)
return;
let datasets = [];
players.forEach(player => {
let data = transformData(player.score);
data = [{x: 0, y: 0}, ...data];
data.push({x: Math.round((this.game.stop_timestamp - this.game.start_timestamp) / 1000),
y: data[data.length - 1].y});
datasets.push({
data: data,
label: player.username,
borderColor: `#${Math.floor(Math.random() * 16777215).toString(16)}`,
fill: false,
});
});
this.chart = new Chart(graph, {
type: "line",
data: {
labels: get_labels(datasets),
datasets: datasets,
}
});
}
displayPlayersList()
{
let table = document.createElement("table"),
thead = document.createElement("thead"),
tr = document.createElement("tr"),
usernameTitle = document.createElement("th"),
goalTitle = document.createElement("th"),
playersList = document.createElement("tbody")
;
usernameTitle.innerText = lang.get("gamePlayersListName");
goalTitle.innerText = lang.get("gameGoalTaken");
tr.appendChild(usernameTitle);
tr.appendChild(goalTitle);
table.appendChild(thead);
table.appendChild(playersList);
document.getElementById("app").appendChild(table);
this.game.players.forEach(player => {
let tr = document.createElement("tr");
let name = document.createElement("td");
let goal = document.createElement("td");
name.id = `username-${player.id}`;
name.innerText = player.username;
goal.id = `goal-${player.id}`;
goal.innerText = player.score.length;
tr.appendChild(name);
tr.appendChild(goal);
playersList.appendChild(tr);
});
this.gamestate.innerHTML = this.game.getState();
this.destroyGameboard();
this.displayWinner(winner)
}
async onDisconnect()
{
sleep(500);
await reloadView();
}
createScoreboard()
{
this.scoreboard = document.createElement("table");
this.app.appendChild(this.scoreboard);
let row = document.createElement("tr");
this.game.players.forEach(player => {
let th = document.createElement("th");
th.innerText = player.username;
row.appendChild(th);
});
this.scoreboard.appendChild(row);
row = document.createElement("tr");
this.game.players.forEach(player => {
let th = document.createElement("th");
th.id = `score-${player.id}`;
th.innerText = player.score.length;
this.scoreboard.appendChild(th);
});
this.scoreboard.appendChild(row);
}
createGameboard()
{
this.canva = document.createElement("canvas");
this.app.appendChild(this.canva)
this.canva.height = this.game.config.MAP_SIZE_Y
this.canva.width = this.game.config.MAP_SIZE_X
this.gameboard = this.canva.getContext('2d');
}
destroyGameboard()
{
this.app.removeChild(this.canva);
}
/**
*
* @param {Profile} winner
*/
displayWinner(winner)
{
const winnerStand = document.createElement("h1");
document.getElementById("app").appendChild(winnerStand);
winnerStand.innerText = `winner: ${winner.username}`;
}
async connect()
{
await this.game.join();
await this.game.waitInit();
}
async postInit()
{
this.game = new PongGame(client, this.game_id, this.onDisconnect, this.onGoal, this.onFinish);
this.keys_pressed = [];
this.gamestate = document.getElementById("gamestate");
this.game = new PongGame(client, this.game_id, this.onStart.bind(this), this.onGoal.bind(this), this.onStart.bind(this), this.onFinish.bind(this));
let error_code = await this.game.init();
const errorCode = await this.game.init();
if (errorCode)
return errorCode;
if (error_code)
return error_code;
this.gamestate.innerHTML = this.game.getState();
await this.updateGameState();
if (this.game.finished)
{
this.displayWinner(this.game.winner);
}
else
{
await this.connect();
this.createScoreboard();
this.createGameboard();
this.createMyPlayer();
this.render();
}
}
async leavePage()
render()
{
if (this.game.finished === false)
{
this.game.leave();
this.game = undefined;
}
this.game = undefined;
this.unregisterKey();
let loop_id = setInterval(() => {
if (this.game === undefined)
clearInterval(loop_id);
this.myPlayer?.updatePaddle(this.keysPressed);
this.renderGame();
this.game?.time?.new_frame();
//clearInterval(loop_id);
// 1 sec fps
}, 1000 / 60);
}
renderGame()
{
this.gameboard.beginPath();
this.game.render(this.gameboard);
this.gameboard.strokeStyle = "#000000";
this.gameboard.lineWidth = 1;
this.gameboard.stroke();
}
async getHtml()
{
return /* HTML */ `
<link rel="stylesheet" href="/static/css/game.css">
<h2 id="game-state"></h2>
<input type="button" value="Switch to 3D" id="game-mode">
<h1 id='gamestate'></h1>
`;
}
}
async leavePage()
{
this.unregisterKey();
this.game.leave()
}
}