merge with master

This commit is contained in:
simplonco
2023-01-16 07:22:51 +01:00
17 changed files with 384 additions and 327 deletions

View File

@@ -279,7 +279,8 @@ export class GameSession {
gc.scoreRight = 0; gc.scoreRight = 0;
} }
} }
await fetch(c.addressBackEnd + "/game/gameserver/updategame",
fetch(`${c.addressBackEnd}/game/gameserver/updategame`,
{ {
method: "POST", method: "POST",
headers: { headers: {
@@ -290,6 +291,14 @@ export class GameSession {
playerOneUsernameResult: gc.scoreLeft, playerOneUsernameResult: gc.scoreLeft,
playerTwoUsernameResult: gc.scoreRight, playerTwoUsernameResult: gc.scoreRight,
}) })
})
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
})
.catch((error) => {
console.log("catch /game/gameserver/updategame: ", error);
}); });
setTimeout(this.destroy, 15000, this); setTimeout(this.destroy, 15000, this);

View File

@@ -89,7 +89,8 @@ async function clientAnnounceListener(this: WebSocket, data: string)
if (announce.privateMatch) { if (announce.privateMatch) {
body.playerTwoUsername = announce.playerTwoUsername; body.playerTwoUsername = announce.playerTwoUsername;
} }
const response = await fetch(c.addressBackEnd + "/game/gameserver/validate",
fetch(`${c.addressBackEnd}/game/gameserver/validate`,
{ {
method: "POST", method: "POST",
headers: { headers: {
@@ -97,17 +98,18 @@ async function clientAnnounceListener(this: WebSocket, data: string)
}, },
body: JSON.stringify(body) body: JSON.stringify(body)
}) })
.catch(error => console.log("ERROR : " + error)); .then((response) => {
if (!response || !response.ok) if (!response.ok) {
{ throw new Error("HTTP " + response.status);
let errMessage = "validate token error";
if (response) {
errMessage = (await response.json()).message;
} }
this.send(JSON.stringify( new ev.EventError(errMessage) )); })
.catch((error) => {
console.log("catch /game/gameserver/validate: ", error);
this.send(JSON.stringify( new ev.EventError("validate token error") ));
clientTerminate(clientsMap.get(this.id)); clientTerminate(clientsMap.get(this.id));
return; return;
} });
player.matchOptions = announce.matchOptions; player.matchOptions = announce.matchOptions;
player.token = announce.token; player.token = announce.token;
player.username = announce.username; player.username = announce.username;
@@ -232,14 +234,26 @@ function privateMatchmaking(player: ClientPlayer)
if (player.socket.OPEN) { if (player.socket.OPEN) {
player.socket.send(JSON.stringify( new ev.EventMatchAbort() )); player.socket.send(JSON.stringify( new ev.EventMatchAbort() ));
} }
const response = await fetch(c.addressBackEnd + "/game/gameserver/destroysession",{
fetch(`${c.addressBackEnd}/game/gameserver/destroysession`,
{
method: "POST", method: "POST",
headers : {"Content-Type": "application/json"}, headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ body: JSON.stringify({
token : player.token token : player.token
}) })
}) })
.catch(error => console.log("ERROR : " + error)); .then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
})
.catch((error) => {
console.log("catch /game/gameserver/destroysession: ", error);
});
clientTerminate(player); clientTerminate(player);
} }
}, 60000); }, 60000);
@@ -315,16 +329,22 @@ async function playerReadyConfirmationListener(this: WebSocket, data: string)
playerOneUsernameResult : 0, playerOneUsernameResult : 0,
playerTwoUsernameResult : 0 playerTwoUsernameResult : 0
}; };
const response = await fetch(c.addressBackEnd + "/game/gameserver/creategame",
fetch(`${c.addressBackEnd}/game/gameserver/creategame`,
{ {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify(body) body: JSON.stringify(body)
}); })
if (!response.ok) .then((response) => {
{ if (!response.ok) {
throw new Error("HTTP " + response.status);
}
})
.catch((error) => {
console.log("catch /game/gameserver/creategame: ", error);
gameSessionsMap.delete(gameSession.id); gameSessionsMap.delete(gameSession.id);
gameSession.playersMap.forEach((client) => { gameSession.playersMap.forEach((client) => {
client.socket.send(JSON.stringify( new ev.EventMatchAbort() )); client.socket.send(JSON.stringify( new ev.EventMatchAbort() ));
@@ -332,7 +352,7 @@ async function playerReadyConfirmationListener(this: WebSocket, data: string)
clientTerminate(client); clientTerminate(client);
}); });
return; return;
} });
gameSession.playersMap.forEach( (client) => { gameSession.playersMap.forEach( (client) => {
client.socket.send(JSON.stringify( new ev.ServerEvent(en.EventTypes.matchStart) )); client.socket.send(JSON.stringify( new ev.ServerEvent(en.EventTypes.matchStart) ));
@@ -445,18 +465,22 @@ export async function clientTerminate(client: Client)
if (client.role === en.ClientRole.player) if (client.role === en.ClientRole.player)
{ {
const player = client as ClientPlayer; const player = client as ClientPlayer;
console.log("/resetuserstatus " + player.username); fetch(`${c.addressBackEnd}/game/gameserver/resetuserstatus`,
const response = await fetch(c.addressBackEnd + "/game/gameserver/resetuserstatus",
{ {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify({username: player.username}) body: JSON.stringify({username: player.username})
}); })
.then((response) => {
if (!response.ok) { if (!response.ok) {
console.log("/resetuserstatus " + player.username + " failed"); throw new Error("HTTP " + response.status);
} }
})
.catch((error) => {
console.log("catch /game/gameserver/resetuserstatus: ", error);
});
} }
} }

View File

@@ -15,8 +15,6 @@ export class TokenGame {
isGameIsWithInvitation : boolean isGameIsWithInvitation : boolean
@Column({default: 0, nullable: true}) @Column({default: 0, nullable: true})
numberOfRegisteredUser : number numberOfRegisteredUser : number
@Column({default : false})
isSecondUserAcceptedRequest : boolean
@Column() @Column()
token : string token : string
} }

View File

@@ -72,10 +72,11 @@ export class GameService {
return encryptedTextToReturn return encryptedTextToReturn
} }
async deleteToken(user : User){ async deletePublicTokens(user : User){
const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame') const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame')
.where('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username}) .where('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username})
.orWhere('tokengame.playerOneUsername = :playerOneUsername', {playerOneUsername : user.username}) .orWhere('tokengame.playerOneUsername = :playerOneUsername', {playerOneUsername : user.username})
.where('tokengame.isGameIsWithInvitation = :isGameIsWithInvitation', {isGameIsWithInvitation : false})
.getMany(); .getMany();
if (tokenGame) if (tokenGame)
return this.tokenGameRepository.remove(tokenGame); return this.tokenGameRepository.remove(tokenGame);
@@ -86,7 +87,7 @@ export class GameService {
console.log(user.status); console.log(user.status);
if (user.status === STATUS.IN_POOL || user.status === STATUS.IN_GAME) if (user.status === STATUS.IN_POOL || user.status === STATUS.IN_GAME)
{ {
await this.deleteToken(user); await this.deletePublicTokens(user);
if (user.status === STATUS.IN_POOL) { if (user.status === STATUS.IN_POOL) {
user.status = STATUS.CONNECTED; user.status = STATUS.CONNECTED;
} }
@@ -106,7 +107,6 @@ export class GameService {
const encryptedTextToReturn = await this.encryptToken(user.username + '_' + secondUser.username + '_' const encryptedTextToReturn = await this.encryptToken(user.username + '_' + secondUser.username + '_'
+ grantTicketDto.gameOptions + '_' + grantTicketDto.isGameIsWithInvitation + '_' + new Date()) + grantTicketDto.gameOptions + '_' + grantTicketDto.isGameIsWithInvitation + '_' + new Date())
const tok = this.tokenGameRepository.create(grantTicketDto); const tok = this.tokenGameRepository.create(grantTicketDto);
tok.isSecondUserAcceptedRequest = false;
tok.numberOfRegisteredUser = 0; tok.numberOfRegisteredUser = 0;
tok.token = encryptedTextToReturn; tok.token = encryptedTextToReturn;
this.tokenGameRepository.save(tok); this.tokenGameRepository.save(tok);
@@ -130,34 +130,30 @@ export class GameService {
async validateToken(validateTicketDto : ValidateTicketDto) { async validateToken(validateTicketDto : ValidateTicketDto) {
if (validateTicketDto.isGameIsWithInvitation === true) if (validateTicketDto.isGameIsWithInvitation === true)
{ {
console.log("validateToken() PRIVATE");
const tokenGame : TokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame') const tokenGame : TokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame')
.where('tokengame.playerOneUsername = :playerOneUsername', {playerOneUsername : validateTicketDto.playerOneUsername}) .where('tokengame.playerOneUsername = :playerOneUsername', {playerOneUsername : validateTicketDto.playerOneUsername})
.andWhere('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : validateTicketDto.playerTwoUsername}) .andWhere('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : validateTicketDto.playerTwoUsername})
.andWhere('tokengame.gameOptions = :gameOption', {gameOption : validateTicketDto.gameOptions}) .andWhere('tokengame.gameOptions = :gameOption', {gameOption : validateTicketDto.gameOptions})
.andWhere('tokengame.isGameIsWithInvitation = :isGameIsWithInvitation', {isGameIsWithInvitation: true}) .andWhere('tokengame.isGameIsWithInvitation = :isGameIsWithInvitation', {isGameIsWithInvitation: true})
.andWhere('tokengame.isSecondUserAcceptedRequest = :choice', {choice : true})
.andWhere('tokengame.token = :token', {token : validateTicketDto.token}) .andWhere('tokengame.token = :token', {token : validateTicketDto.token})
.getOne(); .getOne();
if (tokenGame) if (tokenGame)
{ {
console.log("playerOneUsername: " + tokenGame.playerOneUsername + "| playerTwoUsername: " + tokenGame.playerTwoUsername);
tokenGame.numberOfRegisteredUser++; tokenGame.numberOfRegisteredUser++;
this.tokenGameRepository.save(tokenGame);
if (tokenGame.numberOfRegisteredUser === 2) if (tokenGame.numberOfRegisteredUser === 2)
{ {
this.tokenGameRepository.remove(tokenGame) this.tokenGameRepository.remove(tokenGame)
const userOne : User = await this.userRepository.createQueryBuilder('user')
.where("user.username = :username", {username : tokenGame.playerOneUsername})
.getOne();
const userTwo : User = await this.userRepository.createQueryBuilder('user')
.where("user.username = :username", {username : tokenGame.playerTwoUsername})
.getOne();
this.deleteToken(userOne)
this.deleteToken(userTwo)
} }
return true; return true;
} }
} }
else if (validateTicketDto.isGameIsWithInvitation === false) else if (validateTicketDto.isGameIsWithInvitation === false)
{ {
console.log("validateToken() PUBLIC");
const tokenGame : TokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame') const tokenGame : TokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame')
.where('tokengame.playerOneUsername = :playerOneUsername', {playerOneUsername : validateTicketDto.playerOneUsername}) .where('tokengame.playerOneUsername = :playerOneUsername', {playerOneUsername : validateTicketDto.playerOneUsername})
.andWhere('tokengame.gameOptions = :gameOption', {gameOption : validateTicketDto.gameOptions}) .andWhere('tokengame.gameOptions = :gameOption', {gameOption : validateTicketDto.gameOptions})
@@ -168,10 +164,6 @@ export class GameService {
{ {
this.tokenGameRepository.remove(tokenGame) this.tokenGameRepository.remove(tokenGame)
console.log("USERNAME : " + tokenGame.playerOneUsername) console.log("USERNAME : " + tokenGame.playerOneUsername)
const user : User = await this.userRepository.createQueryBuilder('user')
.where("user.username = :username", {username : tokenGame.playerOneUsername})
.getOne();
this.deleteToken(user)
return true; return true;
} }
} }
@@ -181,8 +173,8 @@ export class GameService {
async findInvitations(user : User, @Res() res : Response) { async findInvitations(user : User, @Res() res : Response) {
const game = await this.tokenGameRepository.createQueryBuilder('tokengame') const game = await this.tokenGameRepository.createQueryBuilder('tokengame')
.where('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username}) .where('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username})
.orWhere('tokengame.playerOneUsername = :playerOneUsername', {playerOneUsername : user.username})
.andWhere('tokengame.isGameIsWithInvitation = :invit', {invit : true}) .andWhere('tokengame.isGameIsWithInvitation = :invit', {invit : true})
.andWhere('tokengame.isSecondUserAcceptedRequest = :choice', {choice : false})
.getMany(); .getMany();
if (!game) if (!game)
return res.status(HttpStatus.NOT_FOUND).send({message : "No invitation found"}); return res.status(HttpStatus.NOT_FOUND).send({message : "No invitation found"});
@@ -200,14 +192,9 @@ export class GameService {
async declineInvitation(user : User, token : string, @Res() res : Response) async declineInvitation(user : User, token : string, @Res() res : Response)
{ {
/* Luke: le check de user.status n'est pas fonctionnel avec l'implémentation des invitations dans le front.
Ça me semble dispensable, je désactive donc pour le moment plutôt que de refaire l'implémentation front. */
// if (user.status !== STATUS.CONNECTED)
// return res.status(HttpStatus.FORBIDDEN).json({message : "You must not be in game to decline an invitation"});
console.log("On décline l'invitation") console.log("On décline l'invitation")
const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame') const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame')
.andWhere('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username}) .where('tokengame.token = :token', {token : token})
.andWhere('tokengame.token = :token', {token : token})
.getOne(); .getOne();
if (tokenGame) if (tokenGame)
{ {
@@ -238,17 +225,11 @@ export class GameService {
async acceptInvitation(user : User, token : string, @Res() res : Response) async acceptInvitation(user : User, token : string, @Res() res : Response)
{ {
/* Luke: le check de user.status n'est pas fonctionnel avec l'implémentation des invitations dans le front.
Ça me semble dispensable, je désactive donc pour le moment plutôt que de refaire l'implémentation front. */
// if (user.status !== STATUS.CONNECTED)
// return res.status(HttpStatus.FORBIDDEN).send("")
const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokenGame') const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokenGame')
.andWhere('tokenGame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username}) .where('tokenGame.token = :token', {token : token})
.andWhere('tokenGame.token = :token', {token : token})
.getOne(); .getOne();
if (tokenGame) if (tokenGame)
{ {
tokenGame.isSecondUserAcceptedRequest = true;
this.tokenGameRepository.save(tokenGame) this.tokenGameRepository.save(tokenGame)
return res.status(HttpStatus.OK).json({message : "Invitation accepted."}); return res.status(HttpStatus.OK).json({message : "Invitation accepted."});
} }

View File

@@ -12,11 +12,23 @@ body {
box-sizing: border-box; box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
/* tmp? */ /* tmp? */
background: bisque; background-color: #333;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
@font-face {
font-family: "Bit5x3";
src:
url("./fonts/Bit5x3.woff2") format("woff2"),
local("Bit5x3"),
url("./fonts/Bit5x3.woff") format("woff");
font-weight: normal;
font-style: normal;
font-display: swap;
}
a { a {
color: rgb(0,100,200); color: rgb(0,100,200);
text-decoration: none; text-decoration: none;
@@ -30,6 +42,13 @@ a:visited {
color: rgb(0,80,160); color: rgb(0,80,160);
} }
.background-pages {
background-color: #333;
font-family: "Bit5x3";
font-size: 2vw;
color: white;
}
label { label {
display: block; display: block;
} }

View File

@@ -1,7 +1,9 @@
<script lang="ts"> <script lang="ts">
import Router, { replace } from "svelte-spa-router"; import Router, { replace } from "svelte-spa-router";
import { primaryRoutes } from "./routes/primaryRoutes.js"; import { primaryRoutes } from "./routes/primaryRoutes.js";
import { location } from 'svelte-spa-router';
import Chat from './pieces/chat/Chat.svelte'; import Chat from './pieces/chat/Chat.svelte';
import Header from './pieces/Header.svelte';
const conditionsFailed = (event) => { const conditionsFailed = (event) => {
console.error('conditionsFailed event', event.detail); console.error('conditionsFailed event', event.detail);
@@ -13,6 +15,10 @@
</script> </script>
{#if ($location !== '/')}
<Header/>
{/if}
<Chat /> <Chat />
<Router routes={primaryRoutes} on:conditionsFailed={conditionsFailed}/> <Router routes={primaryRoutes} on:conditionsFailed={conditionsFailed}/>

View File

@@ -2,9 +2,24 @@
import { link } from "svelte-spa-router"; import { link } from "svelte-spa-router";
</script> </script>
<div class="background-pages">
<div class="content">
<h1>We are sorry!</h1> <h1>We are sorry!</h1>
<p>This isn't a url that we use.</p> <p>This isn't a url that we use.</p>
<p>Go home you're drunk.</p> <p>Go home you're drunk.</p>
<a href="/" use:link> </div>
<h2>Take me home →</h2> </div>
</a>
<style>
.content {
left: 50%;
position: absolute;
-ms-transform: translateX(-50%);
transform: translateX(-50%);
}
</style>

View File

@@ -42,16 +42,6 @@
</div> </div>
<style> <style>
@font-face {
font-family: "Bit5x3";
src:
url("/fonts/Bit5x3.woff2") format("woff2"),
local("Bit5x3"),
url("/fonts/Bit5x3.woff") format("woff");
font-weight: normal;
font-style: normal;
font-display: swap;
}
.container { .container {
height: 100%; height: 100%;
@@ -78,8 +68,8 @@
.button-in { .button-in {
background-color: #8c0000; background-color: #8c0000;
border-color: black; border-color: #071013;
border-width: 4px; border-width: 2px;
color: white; color: white;
font-family: "Bit5x3"; font-family: "Bit5x3";
font-size: x-large; font-size: x-large;
@@ -88,8 +78,8 @@
.button-out { .button-out {
background-color: #008c8c; background-color: #008c8c;
border-color: black; border-color: #071013;
border-width: 4px; border-width: 2px;
color: white; color: white;
font-family: "Bit5x3"; font-family: "Bit5x3";
font-size: x-large; font-size: x-large;

View File

@@ -3,7 +3,6 @@
import { onMount, onDestroy } from "svelte"; import { onMount, onDestroy } from "svelte";
import { fade, fly } from 'svelte/transition'; import { fade, fly } from 'svelte/transition';
import Header from '../../pieces/Header.svelte';
import { fetchUser, fetchAllUsers, fetchAvatar } from "../../pieces/utils"; import { fetchUser, fetchAllUsers, fetchAvatar } from "../../pieces/utils";
import * as pong from "./client/pong"; import * as pong from "./client/pong";
@@ -24,7 +23,6 @@
//boolean for html page //boolean for html page
let hiddenGame = true; let hiddenGame = true;
let optionsAreNotSet = true;
let showGameOptions = true; let showGameOptions = true;
let showInvitations = false; let showInvitations = false;
let showError = false; let showError = false;
@@ -36,14 +34,15 @@
const watchGameStateIntervalRate = 142; const watchGameStateIntervalRate = 142;
let watchMatchStartInterval; let watchMatchStartInterval;
const watchMatchStartIntervalRate = 111; const watchMatchStartIntervalRate = 111;
let timeoutArr = [];
onMount( async() => { onMount( async() => {
user = await fetchUser(); user = await fetchUser();
allUsers = await fetchAllUsers(); allUsers = await fetchAllUsers();
if (!user) { if (!user) {
showError = true;
errorMessage = "User load failed"; errorMessage = "User load failed";
showError = true;
return; return;
} }
@@ -58,12 +57,14 @@
onDestroy( async() => { onDestroy( async() => {
clearInterval(watchMatchStartInterval); clearInterval(watchMatchStartInterval);
clearInterval(watchGameStateInterval); clearInterval(watchGameStateInterval);
timeoutArr.forEach((value) => {
clearTimeout(value);
});
pong.destroy(); pong.destroy();
}) })
function resetPage() { function resetPage() {
hiddenGame = true; setHiddenGame(true);
optionsAreNotSet = true;
showGameOptions = true; showGameOptions = true;
showInvitations = false; showInvitations = false;
showError = false; showError = false;
@@ -74,11 +75,10 @@
const initGame = async() => const initGame = async() =>
{ {
optionsAreNotSet = false;
showWaitPage = true; showWaitPage = true;
const matchOptions = pong.computeMatchOptions(options); const matchOptions = pong.computeMatchOptions(options);
try { fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/ticket`, {
const response = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/ticket`, {
method : "POST", method : "POST",
headers : {'Content-Type': 'application/json'}, headers : {'Content-Type': 'application/json'},
body : JSON.stringify({ body : JSON.stringify({
@@ -87,39 +87,47 @@
gameOptions : matchOptions, gameOptions : matchOptions,
isGameIsWithInvitation : options.isSomeoneIsInvited isGameIsWithInvitation : options.isSomeoneIsInvited
}) })
}); })
console.log("status : " + response.status); .then((response) => {
const responseBody = await response.json(); if (!response.ok) {
const token : string = responseBody.token; throw new Error(`HTTP ${response.status}`);
showWaitPage = false; }
if (response.ok && token) return response.json();
})
.then((body) => {
if (body.token)
{ {
if (options.isSomeoneIsInvited) {
options.reset(user.username);
fetchInvitations();
}
else {
watchMatchStartInterval = setInterval(watchMatchStart, watchMatchStartIntervalRate); watchMatchStartInterval = setInterval(watchMatchStart, watchMatchStartIntervalRate);
watchGameStateInterval = setInterval(watchGameState, watchGameStateIntervalRate); watchGameStateInterval = setInterval(watchGameState, watchGameStateIntervalRate);
pong.init(matchOptions, options, gameAreaId, token); pong.init(matchOptions, options, gameAreaId, body.token);
hiddenGame = false; setHiddenGame(false);
} }
else }
{ else {
console.log(responseBody); throw new Error(`body.token undefined`);
console.log("On refuse le ticket"); }
errorMessage = responseBody.message; })
.catch((error) => {
console.log("catch initGame: ", error);
errorMessage = "Get ticket error";
showError = true; showError = true;
options.reset(user.username); options.reset(user.username);
setTimeout(() => { const timeout = setTimeout(() => {
optionsAreNotSet = true;
showError = false; showError = false;
errorMessage = "";
}, 5000); }, 5000);
} timeoutArr = timeoutArr.concat([timeout]);
} catch (e) { });
console.log(e);
} showWaitPage = false;
} }
const initGameForInvitedPlayer = async(invitation : any) => const initInvitationGame = async(invitation : any) =>
{ {
optionsAreNotSet = false;
showWaitPage = true; showWaitPage = true;
console.log("invitation : "); console.log("invitation : ");
console.log(invitation); console.log(invitation);
@@ -130,10 +138,12 @@
options.playerOneUsername = invitation.playerOneUsername; options.playerOneUsername = invitation.playerOneUsername;
options.playerTwoUsername = invitation.playerTwoUsername; options.playerTwoUsername = invitation.playerTwoUsername;
options.isSomeoneIsInvited = true; options.isSomeoneIsInvited = true;
if (user.username === invitation.playerTwoUsername) {
options.isInvitedPerson = true; options.isInvitedPerson = true;
}
pong.init(invitation.gameOptions, options, gameAreaId, invitation.token); pong.init(invitation.gameOptions, options, gameAreaId, invitation.token);
showWaitPage = false; showWaitPage = false;
hiddenGame = false; setHiddenGame(false);
} }
} }
@@ -156,10 +166,11 @@
gameState.matchEnded = gameState.matchEnded; // trigger Svelte reactivity gameState.matchEnded = gameState.matchEnded; // trigger Svelte reactivity
gameState.matchAborted = gameState.matchAborted; // trigger Svelte reactivity gameState.matchAborted = gameState.matchAborted; // trigger Svelte reactivity
console.log("watchGameState, end"); console.log("watchGameState, end");
setTimeout(() => { const timeout = setTimeout(() => {
resetPage(); resetPage();
console.log("watchGameState : setTimeout"); console.log("watchGameState : setTimeout");
}, 5000); }, 5000);
timeoutArr = timeoutArr.concat([timeout]);
} }
} }
@@ -169,38 +180,63 @@
} }
const fetchInvitations = async() => { const fetchInvitations = async() => {
console.log("fetchInvitations");
invitations = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/invitations`)
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.json();
})
.catch((error) => {
console.log("catch fetchInvitations: ", error);
return [];
});
showGameOptions = false; showGameOptions = false;
showInvitations = true; showInvitations = true;
invitations = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/invitations`)
.then(x => x.json());
} }
const rejectInvitation = async(invitation) => { const rejectInvitation = async(invitation) =>
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/decline`, { {
fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/decline`, {
method: "POST", method: "POST",
headers: { 'Content-Type': 'application/json'}, headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({ body: JSON.stringify({
token : invitation.token token : invitation.token
}) })
}) })
.then(x => x.json()) .then((response) => {
.catch(error => console.log(error)); if (!response.ok) {
throw new Error("HTTP " + response.status);
}
})
.catch((error) => {
console.log("catch rejectInvitation: ", error);
});
fetchInvitations(); fetchInvitations();
} }
const acceptInvitation = async(invitation : any) => const acceptInvitation = async(invitation : any) =>
{ {
const res = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/accept`, { fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/accept`, {
method: "POST", method: "POST",
headers: { 'Content-Type': 'application/json'}, headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({ body: JSON.stringify({
token : invitation.token token : invitation.token
}) })
}).catch(error => console.log(error)); })
.then((response) => {
if (res && res.ok) { if (!response.ok) {
initGameForInvitedPlayer(invitation); throw new Error("HTTP " + response.status);
} }
initInvitationGame(invitation);
})
.catch((error) => {
console.log("catch rejectInvitation: ", error);
fetchInvitations();
});
} }
function leaveMatch() { function leaveMatch() {
@@ -209,12 +245,23 @@
resetPage(); resetPage();
}; };
let game_page_class = "";
function setHiddenGame(value: boolean)
{
if (value) {
game_page_class = "";
}
else {
game_page_class = "dim_background";
}
hiddenGame = value;
}
</script> </script>
<Header />
<!-- <div id="game_page"> Replacement for <body>. <!-- <div id="game_page"> Replacement for <body>.
Might become useless after CSS rework. --> Might become useless after CSS rework. -->
<div id="game_page"> <div id="game_page" class={game_page_class}>
{#if showError} {#if showError}
<div class="div_game" in:fly="{{ y: 10, duration: 1000 }}"> <div class="div_game" in:fly="{{ y: 10, duration: 1000 }}">
@@ -273,10 +320,9 @@
<!-- --> <!-- -->
{#if optionsAreNotSet} {#if hiddenGame}
{#if showGameOptions} {#if showGameOptions}
<div id="game_option"> <div class="div_game" id="game_options">
<div class="div_game">
<button class="pong_button" on:click={fetchInvitations}>Show invitations</button> <button class="pong_button" on:click={fetchInvitations}>Show invitations</button>
<fieldset in:fly="{{ y: 10, duration: 1000 }}"> <fieldset in:fly="{{ y: 10, duration: 1000 }}">
<legend>game options</legend> <legend>game options</legend>
@@ -305,7 +351,7 @@
<label for="invitation_checkbox"> <label for="invitation_checkbox">
<input type="checkbox" id="invitation_checkbox" bind:checked={options.isSomeoneIsInvited}> <input type="checkbox" id="invitation_checkbox" bind:checked={options.isSomeoneIsInvited}>
Invite a friend Invite a player
</label> </label>
{#if options.isSomeoneIsInvited} {#if options.isSomeoneIsInvited}
@@ -320,11 +366,10 @@
</div> </div>
</fieldset> </fieldset>
</div> </div>
</div>
{/if} {/if}
{#if showInvitations} {#if showInvitations}
<div class="div_game"> <div class="div_game" id="game_invitations">
<button class="pong_button" on:click={switchToGameOptions}>Play a Game</button> <button class="pong_button" on:click={switchToGameOptions}>Play a Game</button>
<fieldset in:fly="{{ y: 10, duration: 1000 }}"> <fieldset in:fly="{{ y: 10, duration: 1000 }}">
<legend>invitations</legend> <legend>invitations</legend>
@@ -332,7 +377,7 @@
{#if invitations.length !== 0} {#if invitations.length !== 0}
{#each invitations as invitation} {#each invitations as invitation}
<div> <div>
{invitation.playerOneUsername} has invited you to play a pong ! {invitation.playerOneUsername} VS {invitation.playerTwoUsername}
<button class="pong_button" on:click={() => acceptInvitation(invitation)}>V</button> <button class="pong_button" on:click={() => acceptInvitation(invitation)}>V</button>
<button class="pong_button" on:click={() => rejectInvitation(invitation)}>X</button> <button class="pong_button" on:click={() => rejectInvitation(invitation)}>X</button>
</div> </div>
@@ -348,19 +393,13 @@
</div> <!-- div "game_page" --> </div> <!-- div "game_page" -->
<style> <style>
@font-face {
font-family: "Bit5x3"; .dim_background {
src: background-color: #222;
url("/fonts/Bit5x3.woff2") format("woff2"),
local("Bit5x3"),
url("/fonts/Bit5x3.woff") format("woff");
font-weight: normal;
font-style: normal;
font-display: swap;
} }
#game_page { #game_page {
margin: 0; margin: 0;
background-color: #222425;
position: relative; position: relative;
width: 100%; width: 100%;
height: auto; height: auto;
@@ -368,9 +407,11 @@
flex-direction: column; flex-direction: column;
flex-grow: 1; flex-grow: 1;
} }
#game_option {
#game_options, #game_invitations {
margin-top: 20px; margin-top: 20px;
} }
#canvas_container { #canvas_container {
margin-top: 20px; margin-top: 20px;
text-align: center; text-align: center;
@@ -380,7 +421,7 @@
} }
canvas { canvas {
/* background-color: #ff0000; */ /* background-color: #ff0000; */
background-color: #333333; background-color: #333;
max-width: 75vw; max-width: 75vw;
/* max-height: 100vh; */ /* max-height: 100vh; */
width: 80%; width: 80%;

View File

@@ -3,7 +3,6 @@
import { onMount, onDestroy } from "svelte"; import { onMount, onDestroy } from "svelte";
import { fade, fly } from 'svelte/transition'; import { fade, fly } from 'svelte/transition';
import Header from '../../pieces/Header.svelte';
import MatchListElem from "../../pieces/MatchListElem.svelte"; import MatchListElem from "../../pieces/MatchListElem.svelte";
import type { Match } from "../../pieces/Match"; import type { Match } from "../../pieces/Match";
import { fetchUser, fetchAllUsers, fetchAvatar } from "../../pieces/utils"; import { fetchUser, fetchAllUsers, fetchAvatar } from "../../pieces/utils";
@@ -24,6 +23,7 @@
let matchList: Match[] = []; let matchList: Match[] = [];
let watchGameStateInterval; let watchGameStateInterval;
const watchGameStateIntervalRate = 142; const watchGameStateIntervalRate = 142;
let timeoutArr = [];
onMount( async() => { onMount( async() => {
matchList = await fetchMatchList(); matchList = await fetchMatchList();
@@ -31,6 +31,9 @@
onDestroy( async() => { onDestroy( async() => {
clearInterval(watchGameStateInterval); clearInterval(watchGameStateInterval);
timeoutArr.forEach((value) => {
clearTimeout(value);
});
pongSpectator.destroy(); pongSpectator.destroy();
}) })
@@ -45,7 +48,7 @@
playerOneAvatar = await fetchAvatar(gameState.playerOneUsername); playerOneAvatar = await fetchAvatar(gameState.playerOneUsername);
playerTwoAvatar = await fetchAvatar(gameState.playerTwoUsername); playerTwoAvatar = await fetchAvatar(gameState.playerTwoUsername);
hiddenGame = false; setHiddenGame(false);
}; };
const watchGameState = () => { const watchGameState = () => {
@@ -57,10 +60,11 @@
gameState.matchAborted = gameState.matchAborted; // trigger Svelte reactivity gameState.matchAborted = gameState.matchAborted; // trigger Svelte reactivity
clearInterval(watchGameStateInterval); clearInterval(watchGameStateInterval);
console.log("watchGameState, end") console.log("watchGameState, end")
setTimeout(() => { const timeout = setTimeout(() => {
resetPage(); resetPage();
console.log("watchGameState : setTimeout") console.log("watchGameState : setTimeout")
}, 5000); }, 5000);
timeoutArr = timeoutArr.concat([timeout]);
} }
} }
@@ -70,7 +74,7 @@
}; };
async function resetPage() { async function resetPage() {
hiddenGame = true; setHiddenGame(true);
pongSpectator.destroy(); pongSpectator.destroy();
matchList = await fetchMatchList(); matchList = await fetchMatchList();
}; };
@@ -93,13 +97,24 @@
}); });
}; };
let game_page_class = "";
function setHiddenGame(value: boolean)
{
if (value) {
game_page_class = "";
}
else {
game_page_class = "dim_background";
}
hiddenGame = value;
}
</script> </script>
<!-- --> <!-- -->
<Header />
<!-- <div id="game_page"> Replacement for <body>. <!-- <div id="game_page"> Replacement for <body>.
Might become useless after CSS rework. --> Might become useless after CSS rework. -->
<div id="game_page"> <div id="game_page" class={game_page_class}>
{#if !hiddenGame} {#if !hiddenGame}
{#if gameState.matchEnded} {#if gameState.matchEnded}
@@ -164,21 +179,14 @@
<!-- --> <!-- -->
<style> <style>
@font-face {
font-family: "Bit5x3"; .dim_background {
src: background-color: #222;
url("/fonts/Bit5x3.woff2") format("woff2"),
local("Bit5x3"),
url("/fonts/Bit5x3.woff") format("woff");
font-weight: normal;
font-style: normal;
font-display: swap;
} }
#game_page { #game_page {
margin: 0; margin: 0;
padding: 20px; padding: 20px;
background-color: #222425;
position: relative; position: relative;
width: 100%; width: 100%;
height: 100%; height: 100%;

View File

@@ -1,7 +1,6 @@
<script lang="ts"> <script lang="ts">
import { onMount, onDestroy } from "svelte"; import { onMount, onDestroy } from "svelte";
import Header from "../../pieces/Header.svelte";
//user's stuff //user's stuff
@@ -26,9 +25,9 @@
.then( x => allUsers = x ); .then( x => allUsers = x );
} }
</script> </script>
<Header />
<br />
<br />
<div class="background-pages">
<div class="principal-div"> <div class="principal-div">
<table class="stats-table"> <table class="stats-table">
<thead> <thead>
@@ -46,7 +45,7 @@
<tr> <tr>
<th>{i + 1}</th> <th>{i + 1}</th>
{#if user.username === currentUser.username} {#if user.username === currentUser.username}
<td><b>You ({user.username})</b></td> <td><b>{user.username} [You]</b></td>
{:else} {:else}
<td>{user.username}</td> <td>{user.username}</td>
{/if} {/if}
@@ -59,6 +58,7 @@
</tbody> </tbody>
</table> </table>
</div> </div>
</div>
<style> <style>
@@ -71,7 +71,6 @@
margin-left: auto; margin-left: auto;
margin-right: auto; margin-right: auto;
font-size: 0.9em; font-size: 0.9em;
font-family: sans-serif;
min-width: 400px; min-width: 400px;
} }
@@ -90,15 +89,10 @@
} }
.stats-table tbody tr:nth-of-type(even) { .stats-table tbody tr:nth-of-type(even) {
background-color: #f3f3f3; background-color: #555;
} }
.stats-table tbody tr:last-of-type { .stats-table tbody tr:last-of-type {
border-bottom: 2px solid #618174; border-bottom: 2px solid #618174;
} }
.stats-table tbody tr.active-row {
font-weight: bold;
color: #618174;
}
</style> </style>

View File

@@ -15,6 +15,7 @@
</script> </script>
<div class="background-pages">
<div class="outer"> <div class="outer">
{#if user !== undefined} {#if user !== undefined}
<GenerateUserDisplay user={user}/> <GenerateUserDisplay user={user}/>
@@ -24,13 +25,14 @@
<div>Failed to load current</div> <div>Failed to load current</div>
{/if} {/if}
</div> </div>
</div>
<style> <style>
div.outer{ div.outer{
max-width: 960px; max-width: 100%;
margin: 40px auto;
text-align: center; text-align: center;
padding-bottom: 10px;
} }
</style> </style>

View File

@@ -24,22 +24,10 @@
onMount( async() => { onMount( async() => {
// DO I ACTUALLY NEED TO ON MOUNT ALL THIS STUFF?
// ALSO I COULD JUST USE THE FUNCITONS I MADE...
// yea no idea what
// i mean do i fetch user? i will for now
user = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user`) user = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user`)
.then( (x) => x.json() ); .then( (x) => x.json() );
fetchAll(); fetchAll();
// ok this shit works!
// const interval = setInterval(() => {
// fetchAll();
// }, 1000);
// return () => clearInterval(interval);
}); });
const fetchAll = async() => { const fetchAll = async() => {
@@ -234,6 +222,7 @@
</script> </script>
<div class="background-pages">
<!-- svelte-ignore a11y-click-events-have-key-events --> <!-- svelte-ignore a11y-click-events-have-key-events -->
<div class="top-grid"> <div class="top-grid">
@@ -353,7 +342,7 @@
</div> </div>
</div> </div>
</div>
<style> <style>
/* ok so i want a 12 column grid with a sidebar */ /* ok so i want a 12 column grid with a sidebar */
@@ -368,7 +357,14 @@
div.sidebar-list{ div.sidebar-list{
grid-column: 1 / span 2; grid-column: 1 / span 2;
background: white; background: #FB8B24;
padding: 1vw;
max-width: 100%;
max-height: 100%;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
border-right: 4px solid #071013;
} }
div.sidebar-item{ div.sidebar-item{
@@ -393,7 +389,7 @@
} }
div.placeholder{ div.placeholder{
color: darkgray; color: white;
text-align: center; text-align: center;
} }
@@ -402,7 +398,7 @@
} }
div.tip{ div.tip{
color: darkgray; color: white;
font-size: 0.8em; font-size: 0.8em;
font-weight: bold; font-weight: bold;
} }

View File

@@ -1,11 +1,9 @@
<script lang="ts"> <script lang="ts">
import Header from "../../pieces/Header.svelte";
import Router from "svelte-spa-router"; import Router from "svelte-spa-router";
import { profileRoutes, prefix } from "../../routes/profileRoutes.js"; import { profileRoutes, prefix } from "../../routes/profileRoutes.js";
</script> </script>
<Header />
<div> <div>
<Router routes={profileRoutes} {prefix} /> <Router routes={profileRoutes} {prefix} />

View File

@@ -106,6 +106,7 @@
<main> <main>
<div class="background-pages">
<h2>Look! You can change stuff</h2> <h2>Look! You can change stuff</h2>
<div class="cards"> <div class="cards">
<Card> <Card>
@@ -114,7 +115,7 @@
<div class="label">New Username</div> <div class="label">New Username</div>
<!-- it really hates {user.username} and ${user.username} --> <!-- it really hates {user.username} and ${user.username} -->
<!-- <input type="text" placeholder="current username: ${user.username}" bind:value={set.username}> --> <!-- <input type="text" placeholder="current username: ${user.username}" bind:value={set.username}> -->
<input type="text" placeholder="current username: {nameTmp}" bind:value={set.username}> <input type="text" placeholder="{nameTmp}" bind:value={set.username}>
<div class="success">{success.username}</div> <div class="success">{success.username}</div>
<div class="error">{errors.username}</div> <div class="error">{errors.username}</div>
</div> </div>
@@ -144,7 +145,7 @@
</form> </form>
</Card> </Card>
</div> </div>
</div>
</main> </main>
@@ -158,6 +159,8 @@
grid-gap: 20px; */ grid-gap: 20px; */
} }
div.cards{ div.cards{
display: grid; display: grid;
grid-template-columns: 1fr 1fr; grid-template-columns: 1fr 1fr;
@@ -190,6 +193,7 @@
.inline-check{ .inline-check{
display: inline; display: inline;
color: #333;
} }

View File

@@ -21,101 +21,73 @@
<!-- svelte-ignore a11y-click-events-have-key-events --> <!-- svelte-ignore a11y-click-events-have-key-events -->
<header> <div class="header">
<img src="/img/potato_logo.png" alt="Potato Pong Logo" on:click={() => (push('/'))}> <img src="/img/logo_potato.png" alt="Potato Pong Logo" on:click={() => (push('/'))}>
<h1>Potato Pong</h1> <div class="center">
<nav>
<button class:selected="{current === '/game'}" on:click={() => (push('/game'))}>Play</button> <button class:selected="{current === '/game'}" on:click={() => (push('/game'))}>Play</button>
<button class:selected="{current === '/spectator'}" on:click={() => (push('/spectator'))}>Spectate</button> <button class:selected="{current === '/spectator'}" on:click={() => (push('/spectator'))}>Spectate</button>
<button class:selected="{current === '/ranking'}" on:click={() => (push('/ranking'))}>Ranking</button> <button class:selected="{current === '/ranking'}" on:click={() => (push('/ranking'))}>Ranking</button>
<button class:selected="{current === '/profile'}" on:click={() => (push('/profile'))}>My Profile</button> <button class:selected="{current === '/profile'}" on:click={() => (push('/profile'))}>My Profile</button>
<!-- <button class:selected="{current === '/profile/settings'}" on:click={() => (push('/profile/settings'))}>Settings</button> -->
<button class:selected="{current === '/profile/friends'}" on:click={() => (push('/profile/friends'))}>Friends</button> <button class:selected="{current === '/profile/friends'}" on:click={() => (push('/profile/friends'))}>Friends</button>
<button on:click={handleClickLogout}>Log Out</button> </div>
</nav> <button class="logout" on:click={handleClickLogout}>Log Out</button>
</header> </div>
<style> <style>
/* See "possible_fonts.css" for more font options... */ .header div.center button.selected {
@font-face {
font-family: 'Bondi';
src:url('/fonts/Bondi.ttf.woff') format('woff'),
url('/fonts/Bondi.ttf.svg#Bondi') format('svg'),
url('/fonts/Bondi.ttf.eot'),
url('/fonts/Bondi.ttf.eot?#iefix') format('embedded-opentype');
font-weight: normal;
font-style: normal;
}
.selected {
background-color: chocolate;
text-decoration: underline; text-decoration: underline;
/* TMP so it's obvious but we need to pick good colors */ background-color: #8c0000;
}
.header div.center button {
background-color: #444;
border-color: #071013;
color: white;
font-family: "Bit5x3";
border-width: 2px;
font-size: 2vw;
} }
/* There is a bunch of unncessary shit in here... why so many flex grids, why is everything the same class? just seemed easier but... */ .header button.logout {
background-color: #008c8c;
border-color: #071013;
header{ color: white;
/* background: #f7f7f7; */ font-family: "Bit5x3";
background: #618174; border-width: 2px;
/* padding: 20px; */ font-size: 2vw;
margin: 0;
/* does nothing so far... */
/* display: flex; */
} }
header{ .header {
/* for some reason this doesn't do shit! */ resize: vertical;
position: sticky; overflow: hidden;
/* position: absolute; */ background: #FB8B24;
display: grid; box-sizing: border-box;
grid-template-columns: 1fr 1fr 1fr; -moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
border-bottom: 4px solid #071013;
position: relative;
display: block;
padding: 10px;
} }
/* Headers */ .header div.center {
h1{ width: fit-content;
font-family: 'Bondi';
}
h1{
margin: 0;
text-align: left;
/* max-width: 40px; */
/* this helped with the weird extra space under the image... */
display: flex;
justify-self: center; justify-self: center;
align-self: center; position: absolute;
left: 50%;
display: inline-block;
-ms-transform: translateX(-50%);
transform: translateX(-50%);
} }
/* Images */ .header button.logout {
float: right;
}
img{ .header img{
cursor: pointer; cursor: pointer;
max-width: 40px; max-width: 10%;
padding: 7px 20px; float: left;
justify-self: left;
} }
nav{
display: flex;
justify-content: right;
}
nav button{
margin: 7px 20px;
/* padding: 5px; */
border-radius: 4px;
}
/* .none{
} */
</style> </style>

View File

@@ -4,7 +4,7 @@ export async function fetchAvatar(username: string)
return fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user/avatar?username=${username}`) return fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user/avatar?username=${username}`)
.then((response) => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error("Avatar not retrieved"); throw new Error("HTTP " + response.status);
} }
return response.blob(); return response.blob();
}) })
@@ -22,7 +22,7 @@ export async function fetchUser()
return fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user`) return fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user`)
.then((response) => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error("User not retrieved"); throw new Error("HTTP " + response.status);
} }
return response.json(); return response.json();
}) })
@@ -40,7 +40,7 @@ export async function fetchAllUsers()
return fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user/all`) return fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user/all`)
.then((response) => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error("All Users not retrieved"); throw new Error("HTTP " + response.status);
} }
return response.json(); return response.json();
}) })