Skip to content

Commit

Permalink
lint
Browse files Browse the repository at this point in the history
  • Loading branch information
Half-Shot committed Jan 19, 2025
1 parent 7e1f5fd commit 62259af
Show file tree
Hide file tree
Showing 17 changed files with 115 additions and 267 deletions.
3 changes: 1 addition & 2 deletions src/entities/phys/physicsEntity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ import { CameraLockPriority } from "../../camera";
import { BehaviorSubject, distinct, Observable } from "rxjs";
import Logger from "../../log";


const log = new Logger('PhysicsEntity');
const log = new Logger("PhysicsEntity");

/**
* Abstract class for any physical object in the world. The
Expand Down
22 changes: 14 additions & 8 deletions src/frontend/components/atoms/button.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import { ComponentChildren } from "preact";
import clsx from 'clsx';
import clsx from "clsx";

Check failure on line 2 in src/frontend/components/atoms/button.tsx

View workflow job for this annotation

GitHub Actions / ci

Cannot find module 'clsx' or its corresponding type declarations.

Check failure on line 2 in src/frontend/components/atoms/button.tsx

View workflow job for this annotation

GitHub Actions / deploy

Cannot find module 'clsx' or its corresponding type declarations.
import styles from "./button.module.css";
import { JSX } from "preact";

export default function Button({children, kind = "normal", ...props}: {children : ComponentChildren, kind?: "normal"|"error"}&JSX.HTMLAttributes<HTMLButtonElement>) {
return <button {...props} className={clsx(
styles.button,
styles[kind],
)}>
{children}
export default function Button({
children,
kind = "normal",
...props
}: {
children: ComponentChildren;
kind?: "normal" | "error";
} & JSX.HTMLAttributes<HTMLButtonElement>) {
return (
<button {...props} className={clsx(styles.button, styles[kind])}>
{children}
</button>
}
);
}
5 changes: 3 additions & 2 deletions src/frontend/components/atoms/menu-header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ export default function MenuHeader({
}) {
return (
<header style={menuStyle}>
<Button
<Button
style={{ height: "3em", marginTop: "auto", marginBottom: "auto" }}
onClick={onGoBack}>
onClick={onGoBack}
>
Back
</Button>
<h1>{children}</h1>
Expand Down
1 change: 0 additions & 1 deletion src/frontend/components/menus/lobby.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,6 @@ export function Lobby({ client, gameRoomId, onOpenIngame, exitToMenu }: Props) {

const clientState = useObservableEagerState(client.state);


useEffect(() => {
globalThis.location.hash = `#?gameRoomId=${encodeURIComponent(gameRoomId)}`;
}, []);
Expand Down
7 changes: 5 additions & 2 deletions src/frontend/components/menus/team-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,10 @@ export function TeamEditor({
<section>
<h3> Flag </h3>

<button className={styles.flagUpload} onClick={() => uploadRef.current?.click()}>
<button
className={styles.flagUpload}
onClick={() => uploadRef.current?.click()}
>
{tempBlobUrl ? (
<img
onClick={() => uploadRef.current?.click()}
Expand Down Expand Up @@ -254,7 +257,7 @@ export default function TeamEditorMenu() {
))}
</select>
<Button disabled={localTeams.length >= MAX_TEAMS} onClick={onCreateTeam}>
Add new team
Add new team
</Button>
<TeamEditor
onDeleteTeam={onDeleteTeam}
Expand Down
2 changes: 1 addition & 1 deletion src/logic/gamestate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import Logger from "../log";
import { EntityType } from "../entities/type";
import { GameWorld } from "../world";
import { IWeaponCode } from "../weapons/weapon";
import { BehaviorSubject, distinctUntilChanged, map, skip, tap } from "rxjs";
import { BehaviorSubject, distinctUntilChanged, map, skip } from "rxjs";

export interface GameRules {
roundDurationMs?: number;
Expand Down
55 changes: 42 additions & 13 deletions src/net/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
GameStateIncrementalEvent,
} from "./models";
import { EventEmitter } from "pixi.js";
import { StateRecordLine } from "../state/model";
import { RecordedEntityState, StateRecordLine } from "../state/model";
import {
ClientEvent,
createClient,
Expand Down Expand Up @@ -69,7 +69,7 @@ export class NetGameInstance {
private readonly _proposedTeams: BehaviorSubject<
Record<string, ProposedTeam>
>;
public readonly proposedTeams: Observable<ProposedTeam[]>;
public readonly proposedTeams: Observable<ProposedTeam[]>;
private readonly _rules: BehaviorSubject<GameRules>;
public readonly proposedRules: Observable<GameRules>;

Expand Down Expand Up @@ -252,7 +252,11 @@ export class NetGameInstance {
}

public async sendGameState(data: GameStateIncrementalEvent["content"]) {
await this.client.client.sendEvent(this.roomId, GameStateIncrementalEventType, data);
await this.client.client.sendEvent(
this.roomId,
GameStateIncrementalEventType,
data,
);
}
}

Expand Down Expand Up @@ -525,16 +529,24 @@ export class NetGameClient extends EventEmitter {
}
}

type DecodedGameState = {
iteration: number;
ents: (RecordedEntityState & { uuid: string })[];
};

export class RunningNetGameInstance extends NetGameInstance {
private readonly _gameConfig: BehaviorSubject<GameConfigEvent["content"]>;
private readonly _gameConfig: BehaviorSubject<GameConfigEvent["content"]>;
public readonly gameConfig: Observable<GameConfigEvent["content"]>;
private readonly _gameState: BehaviorSubject<GameStateIncrementalEvent["content"]>;
public readonly gameState: Observable<GameStateIncrementalEvent["content"]>;
private readonly _gameState: BehaviorSubject<DecodedGameState>;
public readonly gameState: Observable<DecodedGameState>;
public readonly player: MatrixStateReplay;

public get gameConfigImmediate() {
return this._gameConfig.value;
}
public get gameHasStarted() {
return this._gameState.value.iteration > 0;
}

public get rules() {
return this.initialConfig.rules;
Expand All @@ -549,14 +561,23 @@ export class RunningNetGameInstance extends NetGameInstance {
super(room, client, initialConfig);
this._gameConfig = new BehaviorSubject(currentState);
this.gameConfig = this._gameConfig.asObservable();
this._gameState = new BehaviorSubject({ iteration: 0, ents: [] as GameStateIncrementalEvent["content"]["ents"]});
this._gameState = new BehaviorSubject({
iteration: 0,
ents: [] as DecodedGameState["ents"],
});
this.gameState = this._gameState.asObservable();
this.player = new MatrixStateReplay();
room.on(RoomStateEvent.Events, (event) => {
const stateKey = event.getStateKey();
const type = event.getType();
if (stateKey && type === GameConfigEventType && event.getSender() !== this.myUserId) {
const content = fromNetObject(event.getContent() as GameConfigEvent["content"]);
if (
stateKey &&
type === GameConfigEventType &&
event.getSender() !== this.myUserId
) {
const content = fromNetObject(
event.getContent() as GameConfigEvent["content"],
);
this._gameConfig.next(content as GameConfigEvent["content"]);
}
});
Expand All @@ -570,10 +591,18 @@ export class RunningNetGameInstance extends NetGameInstance {
) {
void this.player.handleEvent(event.getContent());
}
if (type === GameStateIncrementalEventType && event.getSender() !== this.myUserId) {
const content = fromNetObject(event.getContent() as GameStateIncrementalEvent["content"]);
logger.info("Got new incremental event", content)
this._gameState.next(content as GameStateIncrementalEvent["content"]);
if (
type === GameStateIncrementalEventType &&
event.getSender() !== this.myUserId
) {
const content = fromNetObject(
event.getContent() as GameStateIncrementalEvent["content"],
) as {
iteration: number;
ents: (RecordedEntityState & { uuid: string })[];
};
logger.info("Got new incremental event", content);
this._gameState.next(content);
}
});
}
Expand Down
5 changes: 2 additions & 3 deletions src/net/models.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { InputKind } from "../input";
import { GameRules } from "../logic/gamestate";
import { Team, TeamGroup } from "../logic/teams";
import { StoredTeam } from "../settings";
import { RecordedEntityState } from "../state/model";
import { NetObject } from "./netfloat";

export interface EntityDescriptor {
pos: { x: number; y: number };
Expand Down Expand Up @@ -44,7 +43,7 @@ export interface GameStateIncrementalEvent {
type: typeof GameStateIncrementalEventType;
content: {
iteration: number;
ents: (RecordedEntityState & { uuid: string })[];
ents: NetObject[];
};
}

Expand Down
1 change: 0 additions & 1 deletion src/net/netGameState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,6 @@ export class NetGameState extends GameState {
if (!this.shouldControlState) {
// Waiting for other client to make the move.
return;
} else {
}

if (roundState === RoundState.Preround) {
Expand Down
48 changes: 25 additions & 23 deletions src/net/netGameWorld.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { Ticker, UPDATE_PRIORITY } from "pixi.js";
import { GameWorld } from "../world";
import RAPIER from "@dimforge/rapier2d-compat";
import { RecordedEntityState } from "../state/model";
import { PhysicsEntity } from "../entities/phys/physicsEntity";
import Logger from "../log";
import { RunningNetGameInstance } from "./client";
import { toNetObject } from "./netfloat";
import { IPhysicalEntity } from "../entities/entity";
import { NetObject, toNetObject } from "./netfloat";

const TICK_EVERY_MS = 350;

Expand All @@ -24,25 +22,27 @@ export class NetGameWorld extends GameWorld {
private readonly instance: RunningNetGameInstance,
) {
super(rapierWorld, ticker);
instance.gameState.subscribe(s => {
logger.info("Remote state update", s.iteration);
if (this.broadcasting) {
return;
instance.gameState.subscribe((s) => {
logger.info("Remote state update", s.iteration);
if (this.broadcasting) {
return;
}
s.ents.forEach((e) => {
const ent = this.entities.get(e.uuid);
if (!ent) {
logger.warning(
`Could not find entity ${e.uuid} but got state update`,
);
return;
}
s.ents.forEach(e => {
const ent = this.entities.get(e.uuid);
if (!ent) {
logger.warning(`Could not find entity ${e.uuid} but got state update`);
return;
}
(ent as PhysicsEntity).applyState(e);
});
})
(ent as PhysicsEntity).applyState(e);
});
});
}

public setBroadcasting(isBroadcasting: boolean) {
if (this.broadcasting === isBroadcasting) {
return;
return;
}
if (isBroadcasting) {
logger.info("Enabled broadcasting from this client");
Expand All @@ -55,7 +55,7 @@ export class NetGameWorld extends GameWorld {
}

public collectEntityState() {
const state: (RecordedEntityState & { uuid: string })[] = [];
const state: NetObject[] = [];
for (const [uuid, ent] of this.entities.entries()) {
if ("recordState" in ent === false) {
// Not recordable.
Expand All @@ -70,7 +70,7 @@ export class NetGameWorld extends GameWorld {
this.entStateHash.set(uuid, hashData);
state.push({
uuid,
...toNetObject(data as any) as any,
...toNetObject(data),
});
}
return state;
Expand All @@ -91,11 +91,13 @@ export class NetGameWorld extends GameWorld {
return;
}
logger.info(`Found ${collectedState.length} entity updates to send`);
this.instance.sendGameState({
this.instance
.sendGameState({
iteration: ++this.iteration,
ents: collectedState,
}).catch((ex) => {
logger.warning("Failed to send game state");
})
})
.catch((ex) => {
logger.warning("Failed to send game state", ex);
});
};
}
16 changes: 12 additions & 4 deletions src/net/netfloat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,17 @@ export function fromNetworkFloat(v: NetworkFloat): number {
return Number(v.e);
}

export function toNetObject(
o: Record<string, unknown>,
): Record<string, unknown> {
/**
* Type that should never be used directly.
*/
export type NetObject = Record<string, unknown>;

/**
*
* @param o
* @returns Not exactly T.
*/
export function toNetObject<T extends object>(o: T): NetObject {
return Object.fromEntries(
Object.entries(o).map<[string, unknown]>(([key, v]) => {
if (typeof v === "number" && !Number.isInteger(v)) {
Expand Down Expand Up @@ -48,7 +56,7 @@ export function fromNetObject(o: unknown): unknown {
}

if (Array.isArray(o)) {
return o.map(o => fromNetObject(o));
return o.map((o) => fromNetObject(o));
}

if (isNF(o)) {
Expand Down
Loading

0 comments on commit 62259af

Please sign in to comment.