pong-game/PongGame/wwwroot/js/pong.js
Michael Chen f728240db9
Added crude client rendering with pixi.js
Added keyboard controlling
Added fixed ball reflections on right paddle
added reflections on screen borders
Added goal (miss the paddle) detection
2022-11-04 04:05:20 +01:00

169 lines
4.7 KiB
JavaScript

"use strict";
const connection = new signalR.HubConnectionBuilder()
.withUrl("/pong/hub")
.withAutomaticReconnect()
.withHubProtocol(new signalR.protocols.msgpack.MessagePackHubProtocol())
.build();
function getElement(id) {
return document.getElementById(id) ?? console.error(`Element #${id} not found!`)
}
const connectionStatus = getElement("connection");
const createlobby = getElement("createlobby");
const roomidinput = getElement("roomid");
const joinroom = getElement("joinroom");
const usernameinput = getElement("username");
const setusername = getElement("setusername");
const leavelobby = getElement("leavelobby");
connection.onclose(function (error) {
if (error) {
connectionStatus.textContent = "Unexpected error!";
return console.error(`Connection aborted: ${error.message}`);
}
console.info("Disconnected!");
connectionStatus.textContent = "Closed!";
});
connection.onreconnecting(function (error) {
if (error) {
connectionStatus.textContent = "Reconnecting!";
return console.error(`Connection reconnecting: ${error.message}`);
}
console.info("Reconnecting!");
connectionStatus.textContent = "Reconnecting!";
});
connection.onreconnected(function (connectionId) {
console.info(`Connected as ${connectionId}!`);
connectionStatus.textContent = "Connected!";
});
createlobby.addEventListener("click", function (event) {
connection.invoke("CreateRoom").then(function (roomId) {
roomidinput.value = roomId;
console.info(`Joined room [${roomId}]`);
}).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
connection.on("GameStateChanged", function (state) {
console.info(`Game is now in state ${state}`);
});
connection.on("UsernameChanged", function (username) {
console.info(`Username is now ${username}`);
usernameinput.value = username;
});
joinroom.addEventListener("click", function (event) {
connection.invoke("JoinRoom", roomidinput.value).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
setusername.addEventListener("click", function (event) {
connection.invoke("RequestUsernameChange", usernameinput.value).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
leavelobby.addEventListener("click", function (event) {
connection.invoke("LeaveRoom").catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
function movePaddle(direction) {
connection.invoke("MovePaddle", direction).catch(function (err) {
return console.error(err.toString());
});
}
function moveUp() { return movePaddle(-1); }
function stopPaddle() { return movePaddle(0); }
function moveDown() { return movePaddle(1); }
// Create the application helper and add its render target to the page
let app = new PIXI.Application({ width: 1000, height: 500 });
getElement('canvas-container').appendChild(app.view);
let graphics = new PIXI.Graphics();
app.stage.addChild(graphics);
function renderPaddle(graphics, state, xMid) {
var xLeft = xMid - 5;
graphics.beginFill(0x00FFFF);
graphics.drawRect(xLeft, state.Height - 25, 10, 50);
graphics.endFill();
}
function renderBall(graphics, state) {
graphics.beginFill(0xFF00FF);
graphics.drawCircle(state.Pos.X, state.Pos.Y, 4);
graphics.endFill();
}
function renderGameState(graphics, state) {
graphics.clear();
renderPaddle(graphics, state.Paddle1, 50);
renderPaddle(graphics, state.Paddle2, 1000 - 50);
renderBall(graphics, state.BallState);
}
connection.on("ReceiveGameState", function (state) {
renderGameState(graphics, state);
});
const keyEvent = (function () {
var upPressed = false;
var downPressed = false;
function moveUpdated() {
if (upPressed == downPressed) stopPaddle();
else if (upPressed) moveUp();
else if (downPressed) moveDown();
else console.error("unknown move!");
}
function handler(event) {
if (event.repeat) return;
if (event.path.indexOf(document.body) != 0) return; // only use key if it was pressed on empty space
var pressed = event.type == "keyup";
// W Key is 87, Up arrow is 87
// S Key is 83, Down arrow is 40
switch (event.keyCode) {
case 87:
case 38:
upPressed = pressed;
break;
case 83:
case 40:
downPressed = pressed;
break;
default: return;
}
event.preventDefault();
moveUpdated();
}
return handler;
})();
document.addEventListener('keydown', keyEvent);
document.addEventListener('keyup', keyEvent);
connection.start().then(function () {
console.info(`Connected!`);
connectionStatus.textContent = "Connected!";
}).catch(function (err) {
connectionStatus.textContent = "Connection failed!";
return console.error(err.toString());
});