Skip to content

Commit

Permalink
Split onlinegame.js into several smaller files
Browse files Browse the repository at this point in the history
  • Loading branch information
Naviary2 committed Jan 7, 2025
1 parent 072c128 commit 87570d7
Show file tree
Hide file tree
Showing 35 changed files with 1,696 additions and 1,151 deletions.
18 changes: 9 additions & 9 deletions src/client/css/play.css
Original file line number Diff line number Diff line change
Expand Up @@ -748,7 +748,7 @@ button.join-button, button.copy-button {

/* Top Navigation: Zoom buttons, coordinates, rewind/forward game, pause */

.navigation {
.navigation-bar {
position: absolute;
top: 0;
width: 100%;
Expand Down Expand Up @@ -828,7 +828,7 @@ button.join-button, button.copy-button {
margin: 0;
}

.navigation .button {
.navigation-bar .button {
position: relative;
width: 0.74em;
height: 0.74em;
Expand All @@ -841,28 +841,28 @@ button.join-button, button.copy-button {
-webkit-tap-highlight-color: transparent; /* No more blue highlight when tapping buttons on mobile */
}

.navigation .button:hover {
.navigation-bar .button:hover {
transform: scale(1.07);
}

.navigation .button:active {
.navigation-bar .button:active {
transform: scale(1);
}

.navigation svg {
.navigation-bar svg {
position: absolute;
}

/* Start shrinking top navigation bar */
@media only screen and (max-width: 700px) { /* 700px needs to be updated within camera.updatePIXEL_HEIGHT_OF_NAVS() !!! */
.navigation {
.navigation-bar {
font-size: 12vw; /* Update with doc!! */
}
}

/* Small screens. HIDE the coords and make the buttons bigger! */
@media only screen and (max-width: 550px) { /* 550 needs to be updated within camera.updatePIXEL_HEIGHT_OF_NAVS() !!! */
.navigation {
.navigation-bar {
justify-content: space-between;
font-size: 66px; /* Update with doc!! */
}
Expand All @@ -874,7 +874,7 @@ button.join-button, button.copy-button {

/* Mobile screen, start shrinking the size again */
@media only screen and (max-width: 368px) { /* 368 needs to be updated within camera.updatePIXEL_HEIGHT_OF_NAVS() !!! */
.navigation {
.navigation-bar {
font-size: 17.9vw; /* Update with doc!! */
}
}
Expand All @@ -883,7 +883,7 @@ button.join-button, button.copy-button {

/* Bottom Navigation: Color to move, clocks, player names, draw offer UI */

.footer {
.game-info-bar {
position: absolute;
bottom: 0;
width: 100%;
Expand Down
5 changes: 3 additions & 2 deletions src/client/scripts/esm/chess/logic/clock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import gameloader from '../../game/chess/gameloader.js';

// @ts-ignore
import type gamefile from './gamefile.js';
import onlinegame from '../../game/misc/onlinegame/onlinegame.js';

/** An object containg the values of each color's clock, and which one is currently counting down, if any. */
interface ClockValues {
Expand Down Expand Up @@ -142,7 +143,7 @@ function adjustClockValuesForPing(clockValues: ClockValues): ClockValues {
*/
function push(gamefile: gamefile) {
const clocks = gamefile.clocks;
if (gameloader.areInOnlineGame()) return; // Only the server can push clocks
if (onlinegame.areInOnlineGame()) return; // Only the server can push clocks
if (clocks.untimed) return;
if (!moveutil.isGameResignable(gamefile)) return; // Don't push unless atleast 2 moves have been played

Expand Down Expand Up @@ -179,7 +180,7 @@ function update(gamefile: gamefile): string | undefined {
clocks.currentTime[clocks.colorTicking] = Math.ceil(clocks.timeRemainAtTurnStart! - timePassedSinceTurnStart);

// Has either clock run out of time?
if (gameloader.areInOnlineGame()) return; // Don't conclude game by time if in an online game, only the server does that.
if (onlinegame.areInOnlineGame()) return; // Don't conclude game by time if in an online game, only the server does that.

for (const [color,time] of Object.entries(clocks.currentTime)) {
if (time as number <= 0) {
Expand Down
2 changes: 1 addition & 1 deletion src/client/scripts/esm/chess/logic/legalmoves.js
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ function checkIfMoveLegal(legalMoves, startCoords, endCoords, { ignoreIndividual
* Tests if the provided move is legal to play in this game.
* This accounts for the piece color AND legal promotions, AND their claimed game conclusion.
* @param {gamefile} gamefile - The gamefile
* @param {Move} move - The move, with the bare minimum properties: `{ startCoords, endCoords, promotion }`
* @param {Move | undefined} move - The move, with the bare minimum properties: `{ startCoords, endCoords, promotion }`
* @returns {boolean | string} *true* If the move is legal, otherwise a string containing why it is illegal.
*/
function isOpponentsMoveLegal(gamefile, move, claimedGameConclusion) {
Expand Down
3 changes: 2 additions & 1 deletion src/client/scripts/esm/chess/logic/movepiece.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import frametracker from '../../game/rendering/frametracker.js';
import stats from '../../game/gui/stats.js';
import gameslot from '../../game/chess/gameslot.js';
import gameloader from '../../game/chess/gameloader.js';
import onlinegame from '../../game/misc/onlinegame/onlinegame.js';
// Import End

/**
Expand Down Expand Up @@ -94,7 +95,7 @@ function makeMove(gamefile, move, { flipTurn = true, recordMove = true, pushCloc
updateInCheck(gamefile, recordMove);
if (doGameOverChecks) {
gamefileutility.doGameOverChecks(gamefile);
if (!simulated && concludeGameIfOver && gamefile.gameConclusion && !gameloader.areInOnlineGame()) gameslot.concludeGame();
if (!simulated && concludeGameIfOver && gamefile.gameConclusion && !onlinegame.areInOnlineGame()) gameslot.concludeGame();
}

if (updateData) {
Expand Down
2 changes: 1 addition & 1 deletion src/client/scripts/esm/chess/util/colorutil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ function getColorFromExtension(colorExtention: string): string {
* @param {string} color - "White" / "Black"
* @returns {string} The opposite color, "White" / "Black"
*/
function getOppositeColor(color: string): string {
function getOppositeColor(color: string): 'white' | 'black' {
if (color === 'white') return 'black';
else if (color === 'black') return 'white';
else throw new Error(`Cannot return the opposite color of color ${color}!`);
Expand Down
8 changes: 4 additions & 4 deletions src/client/scripts/esm/game/chess/copypastegame.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

// Import Start
import onlinegame from '../misc/onlinegame.js';
import onlinegame from '../misc/onlinegame/onlinegame.js';
import localstorage from '../../util/localstorage.js';
import formatconverter from '../../chess/logic/formatconverter.js';
import backcompatible from '../../chess/logic/backcompatible.js';
Expand Down Expand Up @@ -103,10 +103,10 @@ async function callbackPaste(event) {
if (guinavigation.isCoordinateActive()) return;

// Make sure we're not in a public match
if (gameloader.areInOnlineGame() && !onlinegame.getIsPrivate()) return statustext.showStatus(translations.copypaste.cannot_paste_in_public);
if (onlinegame.areInOnlineGame() && !onlinegame.getIsPrivate()) return statustext.showStatus(translations.copypaste.cannot_paste_in_public);

// Make sure it's legal in a private match
if (gameloader.areInOnlineGame() && onlinegame.getIsPrivate() && gameslot.getGamefile().moves.length > 0) return statustext.showStatus(translations.copypaste.cannot_paste_after_moves);
if (onlinegame.areInOnlineGame() && onlinegame.getIsPrivate() && gameslot.getGamefile().moves.length > 0) return statustext.showStatus(translations.copypaste.cannot_paste_after_moves);

// Do we have clipboard permission?
let clipboard;
Expand Down Expand Up @@ -256,7 +256,7 @@ async function pasteGame(longformat) { // game: { startingPosition (key-list), p
gameRules: longformat.gameRules
};

if (gameloader.areInOnlineGame() && onlinegame.getIsPrivate()) {
if (onlinegame.areInOnlineGame() && onlinegame.getIsPrivate()) {
// Playing a custom private game! Save the pasted position in browser
// storage so that we can remember it upon refreshing.
const gameID = onlinegame.getGameID();
Expand Down
38 changes: 24 additions & 14 deletions src/client/scripts/esm/game/chess/game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,18 @@
* And contains our main update() and render() methods
*/


// @ts-ignore
import onlinegame from '../misc/onlinegame.js';
import type gamefile from '../../chess/logic/gamefile.js';


import gui from '../gui/gui.js';
import jsutil from '../../util/jsutil.js';
import highlights from '../rendering/highlights/highlights.js';
import gameslot from './gameslot.js';
import guinavigation from '../gui/guinavigation.js';
// @ts-ignore
import onlinegame from '../misc/onlinegame/onlinegame.js';
// @ts-ignore
import arrows from '../rendering/arrows.js';
// @ts-ignore
Expand Down Expand Up @@ -51,17 +60,11 @@ import dragAnimation from '../rendering/draganimation.js';
import piecesmodel from '../rendering/piecesmodel.js';
// @ts-ignore
import loadbalancer from '../misc/loadbalancer.js';
import jsutil from '../../util/jsutil.js';
import highlights from '../rendering/highlights/highlights.js';
import gameslot from './gameslot.js';
import guinavigation from '../gui/guinavigation.js';


// Type Definitions -------------------------------------------------------------------------------


// @ts-ignore
import type gamefile from '../../chess/logic/gamefile.js';
import camera from '../rendering/camera.js';
// @ts-ignore
import guigameinfo from '../gui/guigameinfo.js';
import gameloader from './gameloader.js';


// Functions -------------------------------------------------------------------------------
Expand All @@ -88,14 +91,17 @@ function update() {

if (!guinavigation.isCoordinateActive()) {
if (input.isKeyDown('`')) options.toggleDeveloperMode();
if (input.isKeyDown('2')) console.log(jsutil.deepCopyObject(gamefile));
if (input.isKeyDown('2')) {
console.log(jsutil.deepCopyObject(gamefile));
console.log('Estimated gamefile memory usage: ' + jsutil.estimateMemorySizeOf(gamefile));
}
if (input.isKeyDown('m')) options.toggleFPS();
if (gamefile.mesh.locked && input.isKeyDown('z')) loadbalancer.setForceCalc(true);
}

updateBoard(gamefile); // Other screen, board is visible, update everything board related

onlinegame.update();
gameloader.update(); // Updates whatever game is currently loaded.

guinavigation.updateElement_Coords(); // Update the division on the screen displaying your current coordinates
}
Expand All @@ -113,7 +119,11 @@ function updateBoard(gamefile: gamefile) {
if (input.isKeyDown('escape')) guipause.toggle();
if (input.isKeyDown('tab')) guipause.callback_TogglePointers();
if (input.isKeyDown('r')) piecesmodel.regenModel(gamefile, options.getPieceRegenColorArgs(), true);
if (input.isKeyDown('n')) guinavigation.toggleNavigationBar();
if (input.isKeyDown('n')) {
guinavigation.toggle();
guigameinfo.toggle();
camera.updatePIXEL_HEIGHT_OF_NAVS();
}
}

const timeWinner = clock.update(gamefile);
Expand Down
65 changes: 28 additions & 37 deletions src/client/scripts/esm/game/chess/gameloader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,11 @@ import guinavigation from "../gui/guinavigation.js";
// @ts-ignore
import sound from '../misc/sound.js';
// @ts-ignore
import onlinegame from "../misc/onlinegame.js";
import onlinegame from "../misc/onlinegame/onlinegame.js";
// @ts-ignore
import drawoffers from "../misc/drawoffers.js";
// @ts-ignore
import localstorage from "../../util/localstorage.js";
import jsutil from "../../util/jsutil.js";
// @ts-ignore
import perspective from "../rendering/perspective.js";
import gui from "../gui/gui.js";
Expand All @@ -42,6 +41,8 @@ import type { GameRules } from "../../chess/variants/gamerules.js";
import type { MetaData } from "../../chess/util/metadata.js";
import type { Coords, CoordsKey } from "../../chess/util/coordutil.js";
import type { ClockValues } from "../../chess/logic/clock.js";
import type { DisconnectInfo, DrawOfferInfo } from "../misc/onlinegamerouter.js";
import localgame from "../misc/localgame/localgame.js";


// Type Definitions --------------------------------------------------------------------
Expand Down Expand Up @@ -101,12 +102,11 @@ function areInAGame(): boolean {
return inAGame;
}

function areInLocalGame(): boolean {
return typeOfGameWeAreIn === 'local';
}

function areInOnlineGame(): boolean {
return typeOfGameWeAreIn === 'online';
/**
* Updates whatever game is currently loaded, for what needs to be updated.
*/
function update() {
if (typeOfGameWeAreIn === 'online') onlinegame.update();
}


Expand All @@ -123,31 +123,24 @@ async function startLocalGame(options: {
metadata: {
...options,
Event: `Casual local ${translations[options.Variant]} infinite chess game`,
Site: "https://www.infinitechess.org/",
Round: "-",
Site: 'https://www.infinitechess.org/' as 'https://www.infinitechess.org/',
Round: '-' as '-',
UTCDate: timeutil.getCurrentUTCDate(),
UTCTime: timeutil.getCurrentUTCTime()
} as MetaData
}
};

guigameinfo.hidePlayerNames(); // --------------------------

loadGame(gameOptions, true, true);
await loadGame(gameOptions, true, true);
typeOfGameWeAreIn = 'local';
localgame.initLocalGame();
}

/**
* Starts an online game according to the options provided by the server.
*/
async function startOnlineGame(options: {
clock: MetaData['TimeControl'],
drawOffer: {
/** True if our opponent has extended a draw offer we haven't yet confirmed/denied */
unconfirmed: boolean,
/** The move ply WE HAVE last offered a draw, if we have, otherwise undefined. */
lastOfferPly?: number,
},
gameConclusion: string | false,
/** The id of the online game */
id: string,
metadata: MetaData,
/** Existing moves, if any, to forward to the front of the game. Should be specified if reconnecting to an online. Each move should be in the most compact notation, e.g., `['1,2>3,4','10,7>10,8Q']`. */
Expand All @@ -157,6 +150,16 @@ async function startOnlineGame(options: {
youAreColor: 'white' | 'black',
/** Provide if the game is timed. */
clockValues?: ClockValues,
drawOffer: DrawOfferInfo,
/** If our opponent has disconnected, this will be present. */
disconnect?: DisconnectInfo,
/**
* If our opponent is afk, this is how many millseconds left until they will be auto-resigned,
* at the time the server sent the message. Subtract half our ping to get the correct estimated value!
*/
millisUntilAutoAFKResign?: number,
/** If the server us restarting soon for maintenance, this is the time (on the server's machine) that it will be restarting. */
serverRestartingAt?: number,
}) {
// console.log("Starting online game with invite options:");
// console.log(jsutil.deepCopyObject(options));
Expand All @@ -165,30 +168,18 @@ async function startOnlineGame(options: {
if (options.clockValues) options.clockValues = clock.adjustClockValuesForPing(options.clockValues);

// Must be set BEFORE loading the game, because the mesh generation relies on the color we are.
options.variantOptions = generateVariantOptionsIfReloadingPrivateCustomGame();
if (options.publicity === 'private') options.variantOptions = localstorage.loadItem(options.id);
const fromWhitePerspective = options.youAreColor === 'white';

await loadGame(options, fromWhitePerspective, false);
typeOfGameWeAreIn = 'online';

onlinegame.initOnlineGame(options);
guigameinfo.setAndRevealPlayerNames(options);
drawoffers.set(options.drawOffer);
}





function generateVariantOptionsIfReloadingPrivateCustomGame() {
if (!onlinegame.getIsPrivate()) return; // Can't play/paste custom position in public matches.
const gameID = onlinegame.getGameID();
if (!gameID) return console.error("Can't generate variant options when reloading private custom game because gameID isn't defined yet.");
return localstorage.loadItem(gameID);
}






Expand Down Expand Up @@ -235,8 +226,8 @@ async function loadGame(

const gamefile = gameslot.getGamefile()!;
guinavigation.open(gamefile, { allowEditCoords }); // Editing your coords allowed in local games
guigameinfo.open(gameOptions.metadata);
guiclock.set(gamefile);
guigameinfo.updateWhosTurn(gamefile);

sound.playSound_gamestart();

Expand All @@ -246,6 +237,7 @@ async function loadGame(
function unloadGame() {
onlinegame.closeOnlineGame();
guinavigation.close();
guigameinfo.close();
gameslot.unloadGame();
perspective.disable();
gui.prepareForOpen();
Expand All @@ -256,8 +248,7 @@ function unloadGame() {

export default {
areInAGame,
areInLocalGame,
areInOnlineGame,
update,
startLocalGame,
startOnlineGame,
loadGame,
Expand Down
Loading

0 comments on commit 87570d7

Please sign in to comment.