use consolex in client folder

This commit is contained in:
evanpelle
2024-12-18 14:01:34 -08:00
parent ff02d9d8b6
commit 0d3d49fdd0
12 changed files with 67 additions and 57 deletions
+13 -13
View File
@@ -51,19 +51,19 @@ export function joinLobby(lobbyConfig: LobbyConfig, onjoin: () => void): () => v
)
const onconnect = () => {
console.log(`Joined game lobby ${lobbyConfig.gameID}`);
consolex.log(`Joined game lobby ${lobbyConfig.gameID}`);
transport.joinGame(0)
};
const onmessage = (message: ServerMessage) => {
if (message.type == "start") {
console.log('lobby: game started')
consolex.log('lobby: game started')
onjoin()
createClientGame(lobbyConfig, message.config, eventBus, transport).then(r => r.start())
};
}
transport.connect(onconnect, onmessage)
return () => {
console.log('leaving game')
consolex.log('leaving game')
transport.leaveGame()
}
}
@@ -78,14 +78,14 @@ export async function createClientGame(lobbyConfig: LobbyConfig, gameConfig: Gam
let game = createGame(terrainMap, miniMap, eventBus, config, gameConfig)
const worker = new WorkerClient(game, gameConfig.gameMap)
console.log('going to init path finder')
consolex.log('going to init path finder')
await worker.initialize()
console.log('inited path finder')
consolex.log('inited path finder')
const canvas = createCanvas()
let gameRenderer = createRenderer(canvas, game, eventBus, lobbyConfig.clientID)
console.log(`creating private game got difficulty: ${gameConfig.difficulty}`)
consolex.log(`creating private game got difficulty: ${gameConfig.difficulty}`)
return new GameRunner(
lobbyConfig.clientID,
@@ -121,7 +121,7 @@ export class GameRunner {
) { }
public start() {
console.log('starting client game')
consolex.log('starting client game')
this.isActive = true
this.eventBus.on(PlayerEvent, (e) => this.playerEvent(e))
this.eventBus.on(MouseUpEvent, (e) => this.inputEvent(e))
@@ -137,13 +137,13 @@ export class GameRunner {
this.intervalID = setInterval(() => this.tick(), 10);
const onconnect = () => {
console.log('Connected to game server!');
consolex.log('Connected to game server!');
this.transport.joinGame(this.turns.length)
};
const onmessage = (message: ServerMessage) => {
if (message.type == "start") {
this.hasJoined = true
console.log("starting game!")
consolex.log("starting game!")
for (const turn of message.turns) {
if (turn.turnNumber < this.turns.length) {
continue
@@ -157,7 +157,7 @@ export class GameRunner {
return
}
if (this.turns.length != message.turn.turnNumber) {
console.error(`got wrong turn have turns ${this.turns.length}, received turn ${message.turn.turnNumber}`)
consolex.error(`got wrong turn have turns ${this.turns.length}, received turn ${message.turn.turnNumber}`)
} else {
this.turns.push(message.turn)
}
@@ -183,7 +183,7 @@ export class GameRunner {
this.gs.executeNextTick()
} catch (error) {
const errorText = `Error: ${error.message}\nStack: ${error.stack}`;
console.error(errorText)
consolex.error(errorText)
alert(`Game crashed! client id: ${this.clientID}\n Please paste the following your bug report in Discord:\n` + errorText);
}
this.renderer.tick()
@@ -193,7 +193,7 @@ export class GameRunner {
private playerEvent(event: PlayerEvent) {
if (event.player.clientID() == this.clientID) {
console.log('setting name')
consolex.log('setting name')
this.myPlayer = event.player
}
}
@@ -206,7 +206,7 @@ export class GameRunner {
if (!this.gs.isOnMap(cell)) {
return
}
console.log(`clicked cell ${cell}`)
consolex.log(`clicked cell ${cell}`)
const tile = this.gs.tile(cell)
if (tile.isLand() && !tile.hasOwner() && this.gs.inSpawnPhase()) {
this.eventBus.emit(new SendSpawnIntentEvent(cell))
+7 -6
View File
@@ -2,6 +2,7 @@ import { LitElement, html, css } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';
import { Difficulty, GameMap, GameType } from '../core/game/Game';
import { Lobby } from '../core/Schemas';
import { consolex } from '../core/Consolex';
@customElement('host-lobby-modal')
export class HostLobbyModal extends LitElement {
@@ -168,13 +169,13 @@ export class HostLobbyModal extends LitElement {
private async handleMapChange(e: Event) {
this.selectedMap = String((e.target as HTMLSelectElement).value) as GameMap;
console.log(`updating map to ${this.selectedMap}`)
consolex.log(`updating map to ${this.selectedMap}`)
this.putGameConfig()
}
private async handleDifficultyChange(e: Event) {
this.selectedDiffculty = String((e.target as HTMLSelectElement).value) as Difficulty;
console.log(`updating difficulty to ${this.selectedDiffculty}`)
consolex.log(`updating difficulty to ${this.selectedDiffculty}`)
this.putGameConfig()
}
@@ -189,7 +190,7 @@ export class HostLobbyModal extends LitElement {
}
private async startGame() {
console.log(`Starting private game with map: ${GameMap[this.selectedMap]}`);
consolex.log(`Starting private game with map: ${GameMap[this.selectedMap]}`);
this.close();
const response = await fetch(`/start_private_lobby/${this.lobbyId}`, {
method: 'POST',
@@ -208,7 +209,7 @@ export class HostLobbyModal extends LitElement {
this.copySuccess = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
consolex.error('Failed to copy text: ', err);
}
}
@@ -230,7 +231,7 @@ async function createLobby(): Promise<Lobby> {
}
const data = await response.json();
console.log('Success:', data);
consolex.log('Success:', data);
// Assuming the server returns an object with an 'id' property
const lobby: Lobby = {
@@ -240,7 +241,7 @@ async function createLobby(): Promise<Lobby> {
return lobby;
} catch (error) {
console.error('Error creating lobby:', error);
consolex.error('Error creating lobby:', error);
throw error; // Re-throw the error so the caller can handle it
}
}
+4 -3
View File
@@ -1,6 +1,7 @@
import { LitElement, html, css } from 'lit';
import { customElement, property, state, query } from 'lit/decorators.js';
import { GameMap, GameType } from '../core/game/Game';
import { consolex } from '../core/Consolex';
@customElement('join-private-lobby-modal')
export class JoinPrivateLobbyModal extends LitElement {
@@ -149,13 +150,13 @@ export class JoinPrivateLobbyModal extends LitElement {
const clipText = await navigator.clipboard.readText();
this.lobbyIdInput.value = clipText;
} catch (err) {
console.error('Failed to read clipboard contents: ', err);
consolex.error('Failed to read clipboard contents: ', err);
}
}
private joinLobby() {
const lobbyId = this.lobbyIdInput.value;
console.log(`Joining lobby with ID: ${lobbyId}`);
consolex.log(`Joining lobby with ID: ${lobbyId}`);
this.message = 'Checking lobby...'; // Set initial message
fetch(`/lobby/${lobbyId}/exists`, {
@@ -183,7 +184,7 @@ export class JoinPrivateLobbyModal extends LitElement {
}
})
.catch(error => {
console.error('Error checking lobby existence:', error);
consolex.error('Error checking lobby existence:', error);
this.message = 'An error occurred. Please try again.';
});
}
+2 -1
View File
@@ -1,4 +1,5 @@
import { Config } from "../core/configuration/Config";
import { consolex } from "../core/Consolex";
import { ClientID, ClientMessage, ClientMessageSchema, GameConfig, GameID, GameRecordSchema, Intent, PlayerRecord, ServerMessage, ServerStartGameMessageSchema, ServerTurnMessageSchema, Turn } from "../core/Schemas";
import { CreateGameRecord, generateID } from "../core/Util";
import { LobbyConfig } from "./GameRunner";
@@ -56,7 +57,7 @@ export class LocalServer {
}
public endGame() {
console.log('local server ending game')
consolex.log('local server ending game')
clearInterval(this.endTurnIntervalID)
const players: PlayerRecord[] = [{
ip: null,
+6 -5
View File
@@ -11,6 +11,7 @@ import { HostLobbyModal as HostPrivateLobbyModal } from "./HostLobbyModal";
import { JoinPrivateLobbyModal } from "./JoinPrivateLobbyModal";
import { generateID } from "../core/Util";
import { generateCryptoRandomUUID } from "./Utils";
import { consolex } from "../core/Consolex";
class Client {
private gameStop: () => void
@@ -24,10 +25,10 @@ class Client {
initialize(): void {
this.usernameInput = document.querySelector('username-input') as UsernameInput;
if (!this.usernameInput) {
console.warn('Username input element not found');
consolex.warn('Username input element not found');
}
window.addEventListener('beforeunload', (event) => {
console.log('Browser is closing');
consolex.log('Browser is closing');
if (this.gameStop != null) {
this.gameStop()
}
@@ -60,9 +61,9 @@ class Client {
private async handleJoinLobby(event: CustomEvent) {
const lobby = event.detail.lobby
console.log(`joining lobby ${lobby.id}`)
consolex.log(`joining lobby ${lobby.id}`)
if (this.gameStop != null) {
console.log('joining lobby, stopping existing game')
consolex.log('joining lobby, stopping existing game')
this.gameStop()
}
this.gameStop = joinLobby(
@@ -84,7 +85,7 @@ class Client {
if (this.gameStop == null) {
return
}
console.log('leaving lobby, cancelling game')
consolex.log('leaving lobby, cancelling game')
this.gameStop()
this.gameStop = null
}
+3 -2
View File
@@ -2,6 +2,7 @@ import { LitElement, html, css } from 'lit';
import { customElement, state } from 'lit/decorators.js';
import { Lobby } from "../core/Schemas";
import { Difficulty, GameMap, GameType } from '../core/game/Game';
import { consolex } from '../core/Consolex';
@customElement('public-lobby')
export class PublicLobby extends LitElement {
@@ -65,7 +66,7 @@ export class PublicLobby extends LitElement {
const lobbies = await this.fetchLobbies();
this.lobbies = lobbies;
} catch (error) {
console.error('Error fetching and updating lobbies:', error);
consolex.error('Error fetching and updating lobbies:', error);
}
}
@@ -79,7 +80,7 @@ export class PublicLobby extends LitElement {
const data = await response.json();
return data.lobbies;
} catch (error) {
console.error('Error fetching lobbies:', error);
consolex.error('Error fetching lobbies:', error);
throw error;
}
}
+2 -1
View File
@@ -2,6 +2,7 @@ import { LitElement, html, css } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';
import { Difficulty, GameMap, GameType } from '../core/game/Game';
import { generateID as generateID } from '../core/Util';
import { consolex } from '../core/Consolex';
@customElement('single-player-modal')
export class SinglePlayerModal extends LitElement {
@@ -123,7 +124,7 @@ export class SinglePlayerModal extends LitElement {
this.selectedDifficulty = String((e.target as HTMLSelectElement).value) as Difficulty;
}
private startGame() {
console.log(`Starting single player game with map: ${GameMap[this.selectedMap]}`);
consolex.log(`Starting single player game with map: ${GameMap[this.selectedMap]}`);
this.dispatchEvent(new CustomEvent('join-lobby', {
detail: {
gameType: GameType.Singleplayer,
+12 -12
View File
@@ -1,5 +1,5 @@
import { Config } from "../core/configuration/Config"
import { SendLogEvent } from "../core/Consolex"
import { consolex, SendLogEvent } from "../core/Consolex"
import { EventBus, GameEvent } from "../core/EventBus"
import { AllianceRequest, AllPlayers, Cell, GameType, Player, PlayerID, PlayerType, Tile, UnitType } from "../core/game/Game"
import { ClientID, ClientIntentMessageSchema, ClientJoinMessageSchema, GameID, Intent, ServerMessage, ServerMessageSchema, ClientPingMessageSchema, GameConfig, ClientLogMessageSchema } from "../core/Schemas"
@@ -167,9 +167,9 @@ export class Transport {
this.onconnect = onconnect
this.onmessage = onmessage
this.socket.onopen = () => {
console.log('Connected to game server!');
consolex.log('Connected to game server!');
while (this.buffer.length > 0) {
console.log('sending dropped message')
consolex.log('sending dropped message')
this.sendMsg(this.buffer.pop())
}
onconnect()
@@ -178,13 +178,13 @@ export class Transport {
onmessage(ServerMessageSchema.parse(JSON.parse(event.data)))
};
this.socket.onerror = (err) => {
console.error('Socket encountered error: ', err, 'Closing socket');
consolex.error('Socket encountered error: ', err, 'Closing socket');
this.socket.close();
};
this.socket.onclose = (event: CloseEvent) => {
console.log(`WebSocket closed. Code: ${event.code}, Reason: ${event.reason}`);
consolex.log(`WebSocket closed. Code: ${event.code}, Reason: ${event.reason}`);
if (event.code != 1000) {
console.log(`reconnecting`)
consolex.log(`reconnecting`)
this.connect(onconnect, onmessage)
}
};
@@ -227,11 +227,11 @@ export class Transport {
}
this.stopPing()
if (this.socket.readyState === WebSocket.OPEN) {
console.log('on stop: leaving game')
consolex.log('on stop: leaving game')
this.socket.close()
} else {
console.log('WebSocket is not open. Current state:', this.socket.readyState);
console.error('attempting reconnect')
consolex.log('WebSocket is not open. Current state:', this.socket.readyState);
consolex.error('attempting reconnect')
}
this.socket.onclose = (event: CloseEvent) => { }
}
@@ -362,8 +362,8 @@ export class Transport {
})
this.sendMsg(JSON.stringify(msg))
} else {
console.log('WebSocket is not open. Current state:', this.socket.readyState);
console.log('attempting reconnect')
consolex.log('WebSocket is not open. Current state:', this.socket.readyState);
consolex.log('attempting reconnect')
}
}
@@ -372,7 +372,7 @@ export class Transport {
this.localServer.onMessage(msg)
} else {
if (this.socket.readyState == WebSocket.CLOSED || this.socket.readyState == WebSocket.CLOSED) {
console.warn('socket not ready, closing and trying later')
consolex.warn('socket not ready, closing and trying later')
this.socket.close()
this.socket = null
this.connectRemote(this.onconnect, this.onmessage)
+7 -6
View File
@@ -17,6 +17,7 @@ import { BuildMenu } from "./layers/radial/BuildMenu";
import { UnitLayer } from "./layers/UnitLayer";
import { StructureLayer } from "./layers/StructureLayer";
import { PlayerInfoOverlay } from "./layers/PlayerInfoOverlay";
import { consolex } from "../../core/Consolex";
export function createRenderer(canvas: HTMLCanvasElement, game: Game, eventBus: EventBus, clientID: ClientID): GameRenderer {
@@ -27,18 +28,18 @@ export function createRenderer(canvas: HTMLCanvasElement, game: Game, eventBus:
// TODO maybe append this to dcoument instead of querying for them?
const emojiTable = document.querySelector('emoji-table') as EmojiTable;
if (!emojiTable || !(emojiTable instanceof EmojiTable)) {
console.error('EmojiTable element not found in the DOM');
consolex.error('EmojiTable element not found in the DOM');
}
const buildMenu = document.querySelector('build-menu') as BuildMenu;
if (!buildMenu || !(buildMenu instanceof BuildMenu)) {
console.error('BuildMenu element not found in the DOM')
consolex.error('BuildMenu element not found in the DOM')
}
buildMenu.game = game
buildMenu.eventBus = eventBus
const leaderboard = document.querySelector('leader-board') as Leaderboard;
if (!emojiTable || !(leaderboard instanceof Leaderboard)) {
console.error('EmojiTable element not found in the DOM');
consolex.error('EmojiTable element not found in the DOM');
}
leaderboard.clientID = clientID
leaderboard.eventBus = eventBus
@@ -46,7 +47,7 @@ export function createRenderer(canvas: HTMLCanvasElement, game: Game, eventBus:
const controlPanel = document.querySelector('control-panel') as ControlPanel;
if (!(controlPanel instanceof ControlPanel)) {
console.error('ControlPanel element not found in the DOM');
consolex.error('ControlPanel element not found in the DOM');
}
controlPanel.clientID = clientID
controlPanel.eventBus = eventBus
@@ -54,7 +55,7 @@ export function createRenderer(canvas: HTMLCanvasElement, game: Game, eventBus:
const eventsDisplay = document.querySelector('events-display') as EventsDisplay;
if (!(eventsDisplay instanceof EventsDisplay)) {
console.error('events display not found')
consolex.error('events display not found')
}
eventsDisplay.eventBus = eventBus
eventsDisplay.game = game
@@ -62,7 +63,7 @@ export function createRenderer(canvas: HTMLCanvasElement, game: Game, eventBus:
const playerInfo = document.querySelector('player-info-overlay') as PlayerInfoOverlay
if (!(playerInfo instanceof PlayerInfoOverlay)) {
console.error('player info overlay not found')
consolex.error('player info overlay not found')
}
playerInfo.eventBus = eventBus
playerInfo.clientID = clientID
+6 -5
View File
@@ -8,6 +8,7 @@ import { Layer } from "./Layer";
import { TransformHandler } from "../TransformHandler";
import { MessageType } from "./EventsDisplay";
import { SendBreakAllianceIntentEvent } from "../../Transport";
import { consolex } from "../../../core/Consolex";
interface MenuOption {
label: string;
@@ -64,7 +65,7 @@ export class UILayer implements Layer {
initRightClickMenu() {
if (!this.customMenu) {
console.error('Custom menu not found');
consolex.error('Custom menu not found');
return;
}
@@ -82,7 +83,7 @@ export class UILayer implements Layer {
}
createWinModal() {
console.log("Creating win modal");
consolex.log("Creating win modal");
this.winModal = document.createElement('div');
this.winModal.style.cssText = `
display: none;
@@ -133,7 +134,7 @@ export class UILayer implements Layer {
this.winModal.appendChild(content);
document.body.appendChild(this.winModal);
console.log("Win modal appended to body");
consolex.log("Win modal appended to body");
}
styleButton(button: HTMLButtonElement) {
@@ -185,7 +186,7 @@ export class UILayer implements Layer {
}
onWinEvent(event: WinEvent) {
console.log(`${event.winner.name()} won the game!!}`)
consolex.log(`${event.winner.name()} won the game!!}`)
this.showWinModal(event.winner)
}
@@ -206,7 +207,7 @@ export class UILayer implements Layer {
}
onExitButtonClick() {
console.log('Button clicked!');
consolex.log('Button clicked!');
window.location.reload();
}
+2 -1
View File
@@ -4,6 +4,7 @@ import { Unit, UnitEvent, Cell, Game, Tile, UnitType } from "../../../core/game/
import { bfs, dist, euclDist } from "../../../core/Util";
import { Layer } from "./Layer";
import { EventBus } from "../../../core/EventBus";
import { consolex } from "../../../core/Consolex";
export class UnitLayer implements Layer {
private canvas: HTMLCanvasElement;
@@ -150,7 +151,7 @@ export class UnitLayer implements Layer {
}
);
} catch {
console.log('uh oh')
consolex.log('uh oh')
}
bfs(event.unit.tile(), dist(event.unit.tile(), 2))
.forEach(t => this.paintCell(t.cell(), this.theme.borderColor(event.unit.owner().info()), 255));
@@ -19,6 +19,7 @@ import buildIcon from '../../../../../resources/images/BuildIconWhite.svg';
import { EmojiTable } from "./EmojiTable";
import { UIState } from "../../UIState";
import { BuildMenu } from "./BuildMenu";
import { consolex } from "../../../../core/Consolex";
enum Slot {
@@ -228,7 +229,7 @@ export class RadialMenu implements Layer {
const myPlayer = this.game.players().find(p => p.clientID() == this.clientID)
if (!myPlayer) {
console.warn('my player not found')
consolex.warn('my player not found')
return
}
@@ -383,7 +384,7 @@ export class RadialMenu implements Layer {
if (!this.isCenterButtonEnabled) {
return
}
console.log('Center button clicked');
consolex.log('Center button clicked');
const clicked = this.game.tile(this.clickedCell)
if (this.game.inSpawnPhase()) {
this.eventBus.emit(new SendSpawnIntentEvent(this.clickedCell))