fetch() in Game.svelte

+ fix .dim_background
+ Header in App,svelte
This commit is contained in:
LuckyLaszlo
2023-01-16 00:08:50 +01:00
parent c6d034b9f7
commit 102d03c4bb
7 changed files with 101 additions and 57 deletions

View File

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

View File

@@ -1,6 +1,5 @@
<script>
import { link } from "svelte-spa-router";
import Header from '../pieces/Header.svelte';
</script>

View File

@@ -3,7 +3,6 @@
import { onMount, onDestroy } from "svelte";
import { fade, fly } from 'svelte/transition';
import Header from '../../pieces/Header.svelte';
import { fetchUser, fetchAllUsers, fetchAvatar } from "../../pieces/utils";
import * as pong from "./client/pong";
@@ -35,14 +34,15 @@
const watchGameStateIntervalRate = 142;
let watchMatchStartInterval;
const watchMatchStartIntervalRate = 111;
let timeoutArr = [];
onMount( async() => {
user = await fetchUser();
allUsers = await fetchAllUsers();
if (!user) {
showError = true;
errorMessage = "User load failed";
showError = true;
return;
}
@@ -57,6 +57,9 @@
onDestroy( async() => {
clearInterval(watchMatchStartInterval);
clearInterval(watchGameStateInterval);
timeoutArr.forEach((value) => {
clearTimeout(value);
});
pong.destroy();
})
@@ -73,9 +76,9 @@
const initGame = async() =>
{
showWaitPage = true;
const matchOptions = pong.computeMatchOptions(options);
try {
const response = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/ticket`, {
fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/ticket`, {
method : "POST",
headers : {'Content-Type': 'application/json'},
body : JSON.stringify({
@@ -84,11 +87,15 @@
gameOptions : matchOptions,
isGameIsWithInvitation : options.isSomeoneIsInvited
})
});
console.log("status : " + response.status);
const responseBody = await response.json();
const token : string = responseBody.token;
if (response.ok && token)
})
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
})
.then((body) => {
if (body.token)
{
if (options.isSomeoneIsInvited) {
options.reset(user.username);
@@ -97,25 +104,25 @@
else {
watchMatchStartInterval = setInterval(watchMatchStart, watchMatchStartIntervalRate);
watchGameStateInterval = setInterval(watchGameState, watchGameStateIntervalRate);
pong.init(matchOptions, options, gameAreaId, token);
pong.init(matchOptions, options, gameAreaId, body.token);
setHiddenGame(false);
}
}
else
{
console.log(responseBody);
console.log("On refuse le ticket");
errorMessage = responseBody.message;
showError = true;
options.reset(user.username);
setTimeout(() => {
showError = false;
errorMessage = "";
}, 5000);
else {
throw new Error(`body.token undefined`);
}
} catch (e) {
console.log(e);
}
})
.catch((error) => {
console.log("catch initGame: ", error);
errorMessage = "Get ticket error";
showError = true;
options.reset(user.username);
const timeout = setTimeout(() => {
showError = false;
}, 5000);
timeoutArr = timeoutArr.concat([timeout]);
});
showWaitPage = false;
}
@@ -159,10 +166,11 @@
gameState.matchEnded = gameState.matchEnded; // trigger Svelte reactivity
gameState.matchAborted = gameState.matchAborted; // trigger Svelte reactivity
console.log("watchGameState, end");
setTimeout(() => {
const timeout = setTimeout(() => {
resetPage();
console.log("watchGameState : setTimeout");
}, 5000);
timeoutArr = timeoutArr.concat([timeout]);
}
}
@@ -174,37 +182,61 @@
const fetchInvitations = async() => {
console.log("fetchInvitations");
invitations = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/invitations`)
.then(x => x.json());
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.json();
})
.catch((error) => {
console.log("catch fetchInvitations: ", error);
return [];
});
showGameOptions = false;
showInvitations = true;
}
const rejectInvitation = async(invitation) => {
await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/decline`, {
const rejectInvitation = async(invitation) =>
{
fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/decline`, {
method: "POST",
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({
token : invitation.token
})
})
.then(x => x.json())
.catch(error => console.log(error));
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
})
.catch((error) => {
console.log("catch rejectInvitation: ", error);
});
fetchInvitations();
}
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",
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({
token : invitation.token
})
}).catch(error => console.log(error));
if (res && res.ok) {
})
.then((response) => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
initInvitationGame(invitation);
}
})
.catch((error) => {
console.log("catch rejectInvitation: ", error);
fetchInvitations();
});
}
function leaveMatch() {
@@ -213,22 +245,23 @@
resetPage();
};
function setHiddenGame(value: boolean) {
let game_page_class = "";
function setHiddenGame(value: boolean)
{
if (value) {
document.getElementById("game_page").classList.remove("dim_background");
game_page_class = "";
}
else {
document.getElementById("game_page").classList.add("dim_background");
game_page_class = "dim_background";
}
hiddenGame = value;
}
</script>
<Header />
<!-- <div id="game_page"> Replacement for <body>.
Might become useless after CSS rework. -->
<div id="game_page">
<div id="game_page" class={game_page_class}>
{#if showError}
<div class="div_game" in:fly="{{ y: 10, duration: 1000 }}">
@@ -318,7 +351,7 @@
<label for="invitation_checkbox">
<input type="checkbox" id="invitation_checkbox" bind:checked={options.isSomeoneIsInvited}>
Invite a friend
Invite a player
</label>
{#if options.isSomeoneIsInvited}
@@ -361,6 +394,10 @@
<style>
.dim_background {
background-color: #222;
}
#game_page {
margin: 0;
position: relative;

View File

@@ -3,7 +3,6 @@
import { onMount, onDestroy } from "svelte";
import { fade, fly } from 'svelte/transition';
import Header from '../../pieces/Header.svelte';
import MatchListElem from "../../pieces/MatchListElem.svelte";
import type { Match } from "../../pieces/Match";
import { fetchUser, fetchAllUsers, fetchAvatar } from "../../pieces/utils";
@@ -24,6 +23,7 @@
let matchList: Match[] = [];
let watchGameStateInterval;
const watchGameStateIntervalRate = 142;
let timeoutArr = [];
onMount( async() => {
matchList = await fetchMatchList();
@@ -31,6 +31,9 @@
onDestroy( async() => {
clearInterval(watchGameStateInterval);
timeoutArr.forEach((value) => {
clearTimeout(value);
});
pongSpectator.destroy();
})
@@ -57,10 +60,11 @@
gameState.matchAborted = gameState.matchAborted; // trigger Svelte reactivity
clearInterval(watchGameStateInterval);
console.log("watchGameState, end")
setTimeout(() => {
const timeout = setTimeout(() => {
resetPage();
console.log("watchGameState : setTimeout")
}, 5000);
timeoutArr = timeoutArr.concat([timeout]);
}
}
@@ -93,12 +97,14 @@
});
};
function setHiddenGame(value: boolean) {
let game_page_class = "";
function setHiddenGame(value: boolean)
{
if (value) {
document.getElementById("game_page").classList.remove("dim_background");
game_page_class = "";
}
else {
document.getElementById("game_page").classList.add("dim_background");
game_page_class = "dim_background";
}
hiddenGame = value;
}
@@ -106,10 +112,9 @@
</script>
<!-- -->
<Header />
<!-- <div id="game_page"> Replacement for <body>.
Might become useless after CSS rework. -->
<div id="game_page">
<div id="game_page" class={game_page_class}>
{#if !hiddenGame}
{#if gameState.matchEnded}
@@ -175,6 +180,10 @@
<!-- -->
<style>
.dim_background {
background-color: #222;
}
#game_page {
margin: 0;
padding: 20px;

View File

@@ -1,7 +1,6 @@
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import Header from "../../pieces/Header.svelte";
//user's stuff
@@ -26,7 +25,7 @@
.then( x => allUsers = x );
}
</script>
<Header />
<br />
<div class="background-pages">
<div class="principal-div">

View File

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