Skip to content

Commit

Permalink
last bit of lint
Browse files Browse the repository at this point in the history
  • Loading branch information
Half-Shot committed Jan 9, 2025
1 parent af773e9 commit 1115e98
Show file tree
Hide file tree
Showing 20 changed files with 160 additions and 111 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"build": "tsc && vite build",
"preview": "vite preview",
"lint:eslint": "eslint src/",
"lint:eslint-fix": "eslint --fix src/",
"test": "jest",
"assets": "node scripts/generateAssetManifest.mjs > src/assets/manifest.ts",
"lint:prettier": "prettier 'src/**/*.(ts|tsx|md)' '*.md' -c",
Expand Down
2 changes: 1 addition & 1 deletion src/entities/playable/remoteWorm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { FireFn, Worm } from "./worm";
import { StateWormAction } from "../../state/model";
import Logger from "../../log";
import { InnerWormState } from "./wormState";
import Controller, { InputKind } from "../../input";
import { InputKind } from "../../input";

const logger = new Logger("RemoteWorm");

Expand Down
1 change: 0 additions & 1 deletion src/frontend/components/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { assetLoadPercentage, assetsAreReady } from "../../assets";
import {
NetClientConfig,
NetGameClient,
NetGameInstance,
RunningNetGameInstance,
} from "../../net/client";
import { GameReactChannel } from "../../interop/gamechannel";
Expand Down
2 changes: 1 addition & 1 deletion src/frontend/components/ingame-view.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from "preact/hooks";
import styles from "./ingame-view.module.css";
import { Game } from "../../game";
import { NetGameInstance, RunningNetGameInstance } from "../../net/client";
import { RunningNetGameInstance } from "../../net/client";
import { AmmoCount, GameReactChannel } from "../../interop/gamechannel";
import { WeaponSelector } from "./gameui/weapon-select";

Expand Down
3 changes: 1 addition & 2 deletions src/frontend/components/menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import styles from "./menu.module.css";
import {
NetClientConfig,
NetGameClient,
NetGameInstance,
RunningNetGameInstance,
} from "../../net/client";
import { GameMenu } from "./menus/types";
Expand Down Expand Up @@ -147,7 +146,7 @@ export function Menu({
return (
<menu className={styles.menu}>
<MenuHeader onGoBack={goBack}>Team Editor</MenuHeader>
<TeamEditorMenu client={client} />
<TeamEditorMenu />
</menu>
);
} else if (currentMenu === GameMenu.Settings) {
Expand Down
23 changes: 13 additions & 10 deletions src/frontend/components/menus/lobby.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,13 @@ export function ActiveLobby({
const [error, setError] = useState<string>();

const membersMap = useObservableEagerState(gameInstance.members);
const members = useMemo(() => Object.entries(membersMap).sort(([uA], [uB]) => [uA, uB].sort().indexOf(uA)), [membersMap]);
const members = useMemo(
() =>
Object.entries(membersMap).sort(([uA], [uB]) =>
[uA, uB].sort().indexOf(uA),
),
[membersMap],
);
const proposedTeams = useObservableEagerState(gameInstance.proposedTeams);
const [storedLocalTeams] = useLocalStorageState<StoredTeam[]>(
WORMGINE_STORAGE_KEY_TEAMS,
Expand Down Expand Up @@ -115,8 +121,8 @@ export function ActiveLobby({

const viableToStart = true;

// const viableToStart = useMemo(() =>
// gameInstance.isHost && members.length >= 2 && proposedTeams.length >= 2 &&
// const viableToStart = useMemo(() =>
// gameInstance.isHost && members.length >= 2 && proposedTeams.length >= 2 &&
// proposedTeams.reduce<Partial<Record<TeamGroup, number>>>((v, o) => ({
// ...v,
// [o.group]: (v[o.group] ?? 0) + 1
Expand Down Expand Up @@ -182,7 +188,8 @@ export function ActiveLobby({
}
const onRemoveTeam = () => removeTeam(t);
const incrementWormCount = () => {
const newWormCount = t.wormCount >= MAX_WORMS ? 1 : t.wormCount + 1;
const newWormCount =
t.wormCount >= MAX_WORMS ? 1 : t.wormCount + 1;
gameInstance.addProposedTeam(t, newWormCount, t.group);
};
const changeTeamColor = () => {
Expand Down Expand Up @@ -216,10 +223,7 @@ export function ActiveLobby({
</section>

<section>
<button
onClick={() => onOpenIngame()}
disabled={!viableToStart}
>
<button onClick={() => onOpenIngame()} disabled={!viableToStart}>
Start Game
</button>
<button onClick={() => exitToMenu()} disabled={gameInstance.isHost}>
Expand All @@ -236,7 +240,6 @@ export function Lobby({ client, gameRoomId, onOpenIngame, exitToMenu }: Props) {

const clientState = useObservableEagerState(client.state);


useEffect(() => {
if (!gameInstance) {
return;
Expand All @@ -256,7 +259,7 @@ export function Lobby({ client, gameRoomId, onOpenIngame, exitToMenu }: Props) {
}
});
return () => s.unsubscribe();
}, [gameInstance])
}, [gameInstance]);

useEffect(() => {
if (clientState !== ClientState.Connected) {
Expand Down
2 changes: 2 additions & 0 deletions src/frontend/components/menus/online-play.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,8 @@ export function OnlinePlayWithClient({
// Client was logged out.
NetGameClient.clearConfig();
setClientConfig(null);
return null;
break;
default:
return (
<div>
Expand Down
7 changes: 1 addition & 6 deletions src/frontend/components/menus/team-editor.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import useLocalStorageState from "use-local-storage-state";
import { NetGameClient } from "../../../net/client";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { JSX } from "preact/jsx-runtime";
import styles from "./team-editor.module.css";
import { StoredTeam, WORMGINE_STORAGE_KEY_TEAMS } from "../../../settings";

interface Props {
client?: NetGameClient;
}

const MAX_WORM_NAMES = 8;
const MAX_TEAMS = 32;

Expand Down Expand Up @@ -165,7 +160,7 @@ export function TeamEditor({
);
}

export default function TeamEditorMenu({ client }: Props) {
export default function TeamEditorMenu() {
const [localTeams, setLocalTeams] = useLocalStorageState<StoredTeam[]>(
WORMGINE_STORAGE_KEY_TEAMS,
{
Expand Down
7 changes: 7 additions & 0 deletions src/levels/scenarioParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
import { WormSpawnRecordedState } from "../entities/state/wormSpawn";
import { Team, TeamGroup, WormIdentity } from "../logic/teams";
import { IWeaponCode } from "../weapons/weapon";
import { DefaultWeaponSchema } from "../weapons/schema";

export const COMPATIBLE_TILED_VERSION = "1.11";
const logger = new Logger("scenarioParser");
Expand Down Expand Up @@ -125,6 +126,8 @@ function determineRules(rules?: TiledGameRulesProperties): GameRules {
logger.warning("No rules in level, assuming deathmatch");
return {
winWhenOneGroupRemains: true,
wormHealth: 100,
ammoSchema: DefaultWeaponSchema,
};
}
rules["wormgine.end_condition"] ??= "Deathmatch";
Expand All @@ -135,10 +138,14 @@ function determineRules(rules?: TiledGameRulesProperties): GameRules {
winWhenAllObjectsOfTypeDestroyed: Object.entries(EntityType).find(
([_k, v]) => v === obj,
)?.[1],
wormHealth: 100,
ammoSchema: DefaultWeaponSchema,
};
} else if (rules["wormgine.end_condition"] === "Deathmatch") {
return {
winWhenOneGroupRemains: true,
wormHealth: 100,
ammoSchema: DefaultWeaponSchema,
};
}
throw Error("Misconfigured rules object");
Expand Down
3 changes: 1 addition & 2 deletions src/logic/gamestate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export interface GameRules {
roundDurationMs?: number;
winWhenOneGroupRemains?: boolean;
winWhenAllObjectsOfTypeDestroyed?: EntityType;
wormHealth: number,
wormHealth: number;
ammoSchema: Record<IWeaponCode | string, number>;
}

Expand Down Expand Up @@ -275,7 +275,6 @@ export class GameState {
this.recorder.recordGameState({
iteration: iteration,
wind: this.currentWind,
nextTeam: this.activeTeam?.name!,
teams: teams.map((t) => ({
name: t.name,
group: t.group,
Expand Down
81 changes: 54 additions & 27 deletions src/net/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
ProposedTeam,
GameProposedTeamEventType,
GameActionEventType,
GameClientReadyEvent,
GameClientReadyEventType,
} from "./models";
import { EventEmitter } from "pixi.js";
Expand Down Expand Up @@ -63,7 +62,7 @@ export enum ClientState {
}
export class NetGameInstance {
private readonly _stage: BehaviorSubject<GameStage>;
public readonly stage: Observable<GameStage>
public readonly stage: Observable<GameStage>;
private readonly _members: BehaviorSubject<Record<string, string>>;
public members: Observable<Record<string, string>>;
private readonly _proposedTeams: BehaviorSubject<
Expand All @@ -72,7 +71,7 @@ export class NetGameInstance {
public readonly proposedTeams: Observable<ProposedTeam[]>;
private readonly _rules: BehaviorSubject<GameRules>;
public readonly proposedRules: Observable<GameRules>;

public readonly hostUserId: string;
public readonly isHost: boolean;

Expand Down Expand Up @@ -112,7 +111,11 @@ export class NetGameInstance {
}
const stateKey = event.getStateKey();
const type = event.getType();
if (stateKey && type === GameProposedTeamEventType && this._stage.value === GameStage.Lobby) {
if (
stateKey &&
type === GameProposedTeamEventType &&
this._stage.value === GameStage.Lobby
) {
const content = event.getContent() as ProposedTeam;
if (Object.keys(content).length > 0) {
this._proposedTeams.next({
Expand Down Expand Up @@ -165,7 +168,7 @@ export class NetGameInstance {
}

public async addProposedTeam(
proposedTeam: StoredTeam|ProposedTeam,
proposedTeam: StoredTeam | ProposedTeam,
wormCount: number,
teamGroup: TeamGroup = TeamGroup.Red,
) {
Expand All @@ -176,7 +179,10 @@ export class NetGameInstance {
...proposedTeam,
group: teamGroup,
wormCount,
playerUserId: "playerUserId" in proposedTeam ? proposedTeam.playerUserId : this.client.userId,
playerUserId:
"playerUserId" in proposedTeam
? proposedTeam.playerUserId
: this.client.userId,
// TODO: What should the proper stateKey be?
},
`${this.client.userId.slice(1)}/${proposedTeam.name}`,
Expand All @@ -193,19 +199,22 @@ export class NetGameInstance {
}

public async startGame() {
const teams: Team[] = Object.values(this._proposedTeams.value).map(v => ({
const teams: Team[] = Object.values(this._proposedTeams.value).map((v) => ({
name: v.name,
flag: v.flagb64,
group: v.group,
playerUserId: v.playerUserId,
// Needs to come from rules.
ammo: this._rules.value.ammoSchema,
worms: v.worms.slice(0, v.wormCount).map(w => ({
name: w,
health: this._rules.value.wormHealth,
maxHealth: this._rules.value.wormHealth,
uuid: globalThis.crypto.randomUUID(),
} satisfies WormIdentity)),
worms: v.worms.slice(0, v.wormCount).map(
(w) =>
({
name: w,
health: this._rules.value.wormHealth,
maxHealth: this._rules.value.wormHealth,
uuid: globalThis.crypto.randomUUID(),
}) satisfies WormIdentity,
),
}));
// Initial full state of the game.
await this.client.client.sendStateEvent(this.roomId, GameStateEventType, {
Expand Down Expand Up @@ -390,16 +399,16 @@ export class NetGameClient extends EventEmitter {
let stateEvents;
try {
stateEvents = await this.client.roomState(roomId);
} catch (ex) {
} catch {
// TODO: Timeout.
await new Promise<void>((r) => room.on(RoomEvent.MyMembership, () => r()));
await new Promise<void>((r) =>
room.on(RoomEvent.MyMembership, () => r()),
);
stateEvents = await this.client.roomState(roomId);
}

const createEvent = stateEvents.find((s) => s.type === "m.room.create");
const stageEvent = stateEvents.find(
(s) => s.type === GameStageEventType,
);
const stageEvent = stateEvents.find((s) => s.type === GameStageEventType);
const configEvent = stateEvents.find(
(s) => s.type === GameConfigEventType,
) as unknown as GameConfigEvent;
Expand Down Expand Up @@ -445,14 +454,18 @@ export class NetGameClient extends EventEmitter {
if (!fullStateEvent) {
throw Error("In progress game had no state");
}
return new RunningNetGameInstance(room, this, initialConfig, fullStateEvent["content"]);
return new RunningNetGameInstance(
room,
this,
initialConfig,
fullStateEvent["content"],
);
}

return new NetGameInstance(room, this, initialConfig);
}
}


export class RunningNetGameInstance extends NetGameInstance {
private readonly _gameState: BehaviorSubject<FullGameStateEvent["content"]>;
public readonly gameState: Observable<FullGameStateEvent["content"]>;
Expand All @@ -466,8 +479,13 @@ export class RunningNetGameInstance extends NetGameInstance {
return this.initialConfig.rules;
}

constructor(room: Room, client: NetGameClient, private readonly initialConfig: NetGameConfiguration, currentState: FullGameStateEvent["content"]) {
super(room, client, initialConfig)
constructor(
room: Room,
client: NetGameClient,
private readonly initialConfig: NetGameConfiguration,
currentState: FullGameStateEvent["content"],
) {
super(room, client, initialConfig);
this._gameState = new BehaviorSubject(currentState);
this.gameState = this._gameState.asObservable();
client.client.on(RoomStateEvent.Events, (event, state) => {
Expand All @@ -493,17 +511,27 @@ export class RunningNetGameInstance extends NetGameInstance {
}

writeAction(data: StateRecordLine<unknown>) {
return this.client.client.sendEvent(this.roomId, GameActionEventType, { action: data });
return this.client.client.sendEvent(this.roomId, GameActionEventType, {
action: data,
});
}

async ready() {
return this.client.client.sendEvent(this.roomId, GameClientReadyEventType, { });
return this.client.client.sendEvent(
this.roomId,
GameClientReadyEventType,
{},
);
}

async allClientsReady() {
const setOfReady = new Set<string>([
this.myUserId,
...this.room.getLiveTimeline().getEvents().filter(e => e.getType() === GameClientReadyEventType).map(e => e.getSender()) as string[],
...(this.room
.getLiveTimeline()
.getEvents()
.filter((e) => e.getType() === GameClientReadyEventType)
.map((e) => e.getSender()) as string[]),
]);

const expectedCount = Object.values(this.initialConfig.members).length;
Expand All @@ -520,4 +548,3 @@ export class RunningNetGameInstance extends NetGameInstance {
});
}
}

Loading

0 comments on commit 1115e98

Please sign in to comment.