Skip to content

Commit

Permalink
added spinner when creating room, some code changes
Browse files Browse the repository at this point in the history
  • Loading branch information
keshav2010 committed Apr 28, 2024
1 parent 8fd6b36 commit 58ab9a7
Show file tree
Hide file tree
Showing 9 changed files with 114 additions and 116 deletions.
34 changes: 19 additions & 15 deletions gameserver/commands/OnSoldierAttackCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,25 @@ export class OnSoldierAttackCommand extends Command<
targetPlayerId: string;
targetUnitId: string;
}>) {
const attacker = this.state.getPlayer(client.id);
const victim = this.state.getPlayer(message.targetPlayerId);
if (!attacker || !victim) {
return;
}
const targetSoldier = victim.getSoldier(message.targetUnitId);
if (!targetSoldier) {
return;
}
try {
const attacker = this.state.getPlayer(client.id);
const victim = this.state.getPlayer(message.targetPlayerId);
if (!attacker || !victim) {
return;
}
const targetSoldier = victim.getSoldier(message.targetUnitId);
if (!targetSoldier) {
return;
}

const attackerUnits = attacker
.getAllSoldiers()
.filter((soldier) => message.soldiers.includes(soldier.id));
attackerUnits.forEach((unit: SoldierState) => {
unit.attackUnit(targetSoldier, gameManager!);
});
const attackerUnits = attacker
.getAllSoldiers()
.filter((soldier) => message.soldiers.includes(soldier.id));
attackerUnits.forEach((unit: SoldierState) => {
unit.attackUnit(targetSoldier, gameManager!);
});
} catch (error) {
console.error(error);
}
}
}
37 changes: 21 additions & 16 deletions gameserver/commands/OnSoldierMoveCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,26 @@ export class OnSoldierMoveCommand extends Command<SessionRoom, CommandPayload> {
expectedPositionX: number;
expectedPositionY: number;
}>) {
const sceneSize = gameManager?.scene.getDimension();
if (!sceneSize) return;

const soldierObjects = message.soldierIds
.map((id) => this.state.getPlayer(client.sessionId)?.getSoldier(id))
.filter(Boolean) as SoldierState[];
if (soldierObjects.length === 0) return;
const offset = 96;
const gridFormation = new GroupFormation(
soldierObjects,
offset,
new SAT.Box(new SAT.Vector(), sceneSize.x, sceneSize.y)
);
gridFormation.calculatePositions(
new SAT.Vector(message.expectedPositionX, message.expectedPositionY)
);
try {
const sceneSize = gameManager?.scene.getDimension();
if (!sceneSize) {
throw new Error(`sceneSize not found`);
}
const soldierObjects = message.soldierIds
.map((id) => this.state.getPlayer(client.sessionId)?.getSoldier(id))
.filter(Boolean) as SoldierState[];
if (soldierObjects.length === 0) return;
const offset = 96;
const gridFormation = new GroupFormation(
soldierObjects,
offset,
new SAT.Box(new SAT.Vector(), sceneSize.x, sceneSize.y)
);
gridFormation.calculatePositions(
new SAT.Vector(message.expectedPositionX, message.expectedPositionY)
);
} catch (error) {
console.error(error);
}
}
}
16 changes: 8 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"npx": "^10.2.2",
"phaser": "^3.70.0",
"phaser-ui-tools": "^2.0.0-beta",
"phaser3-rex-plugins": "^1.1.82",
"phaser3-rex-plugins": "^1.80.2",
"quadtree-lib": "^1.0.9",
"sat": "^0.9.0",
"socket.io": "^4.4.1",
Expand Down
1 change: 1 addition & 0 deletions public/game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { PlayerStatisticHUD } from "./scenes/PlayerStatisticHUD";
import { SessionLobbyScene } from "./scenes/SessionLobbyScene";
import { SessionBrowserScene } from "./scenes/SessionBrowserScene";
import SpinnerPlugin from "phaser3-rex-plugins/templates/spinner/spinner-plugin.js";

import Phaser from "phaser";
const config = {
type: Phaser.WEBGL,
Expand Down
44 changes: 8 additions & 36 deletions public/scenes/BaseScene.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,13 @@ import { NetworkManager } from "../NetworkManager";
import { ClientStateManager } from "../ClientStateManager";
import CONSTANT from "../constant";
import { nanoid } from "nanoid";
interface Destroyable {
destroy: Function;
}
type ManagedTypes = Destroyable;

export class BaseScene extends Phaser.Scene {
objectSet: Map<
string,
| Phaser.GameObjects.Graphics
| PlayerCastle
| Phaser.Cameras.Controls.SmoothedKeyControl
| Phaser.GameObjects.Text
| Phaser.GameObjects.DOMElement
| Phaser.GameObjects.Image
>;
objectSet: Map<string, ManagedTypes>;
registeredInputEvents: Set<string>;
registeredSceneEvents: Set<string>;

Expand Down Expand Up @@ -73,29 +69,13 @@ export class BaseScene extends Phaser.Scene {
}
}

AddObject<
T extends
| Phaser.GameObjects.Graphics
| PlayerCastle
| Phaser.Cameras.Controls.SmoothedKeyControl
| Phaser.GameObjects.Text
| Phaser.GameObjects.DOMElement
| Phaser.GameObjects.Image
>(newObject: T, key?: string): T {
AddObject<T extends ManagedTypes>(newObject: T, key?: string): T {
let mKey = nanoid();
this.objectSet.set(key || mKey, newObject);
return newObject;
}

GetObject<
T extends
| Phaser.GameObjects.Graphics
| PlayerCastle
| Phaser.Cameras.Controls.SmoothedKeyControl
| Phaser.GameObjects.Text
| Phaser.GameObjects.DOMElement
| Phaser.GameObjects.Image
>(key: string) {
GetObject<T extends ManagedTypes>(key: string) {
return this.objectSet.get(key) as T | undefined;
}

Expand Down Expand Up @@ -124,15 +104,7 @@ export class BaseScene extends Phaser.Scene {
}

// Recursively destroy an object, including any children if it's a group
DestroyObject<
T extends
| Phaser.GameObjects.Graphics
| PlayerCastle
| Phaser.GameObjects.Text
| Phaser.GameObjects.DOMElement
| Phaser.GameObjects.Image
| Phaser.Cameras.Controls.SmoothedKeyControl
>(obj: T) {
DestroyObject<T extends ManagedTypes>(obj: T) {
if ((obj as any)?.type === "Group") obj.destroy(true);
else obj.destroy();
}
Expand Down
9 changes: 3 additions & 6 deletions public/scenes/GameScene.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import SessionStateClientHelpers from "../helpers/SessionStateClientHelpers";
import { BaseSoldier } from "../soldiers/BaseSoldier";
import { Spearman } from "../soldiers/Spearman";
import { BaseScene } from "./BaseScene";
import SpinnerPlugin from "phaser3-rex-plugins/templates/spinner/spinner-plugin.js";

import $ from "jquery";

var selectorColor = 0xffff00;
Expand Down Expand Up @@ -56,7 +58,7 @@ export class GameScene extends BaseScene {
canvasWidth: number;
canvasHeight: number;
controls?: Phaser.Cameras.Controls.SmoothedKeyControl;

rexSpinner: SpinnerPlugin.Spinner | undefined;
constructor() {
super(CONSTANT.SCENES.GAME);
this.canvasWidth = 1962;
Expand Down Expand Up @@ -88,10 +90,6 @@ export class GameScene extends BaseScene {
[ownerPlayer.colorR, ownerPlayer.colorG, ownerPlayer.colorB],
ownerPlayer.id
);
spearmen.setData("serverPosition", {
x: soldier.currentPositionX,
y: soldier.currentPositionY,
});
const playerSoldiersGameObject = this.data.get(
"playerSoldiersGameObject"
) as Map<PlayerId, soldierIdToPhaserMap>;
Expand Down Expand Up @@ -207,7 +205,6 @@ export class GameScene extends BaseScene {

create() {
networkManager = this.registry.get("networkManager") as NetworkManager;

const stylus = this.add.graphics();
stylus.setDepth(9999);

Expand Down
67 changes: 45 additions & 22 deletions public/scenes/MenuScene.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ import CONSTANT from "../constant";
import { BaseScene } from "./BaseScene";
import { NetworkManager } from "../NetworkManager";
import { addBackgroundImage } from "../helpers/addBackgroundImage";
import SpinnerPlugin from "phaser3-rex-plugins/templates/spinner/spinner-plugin.js";

const URL = `${window.location.host}`;

export class MenuScene extends BaseScene {
rexSpinner: SpinnerPlugin | undefined;
constructor() {
super(CONSTANT.SCENES.MENU);
console.log(URL);
Expand All @@ -15,8 +19,24 @@ export class MenuScene extends BaseScene {
this.scene.bringToTop();
this.load.html("playerForm", "../html/menu-form.html");
this.load.image("background", "../assets/background.png");
this.load.scenePlugin({
key: "rexSpinner",
url: SpinnerPlugin,
sceneKey: "rexSpinner",
});
}
create() {
const spinner = this.rexSpinner!.add.spinner({
width: 80,
height: 80,
duration: 500,
x: 80,
y: 80,
});
spinner.setDepth(9999);
spinner.setVisible(false);
this.AddObject(spinner, "obj_spinner");

let networkManager = this.registry.get("networkManager") as NetworkManager;
addBackgroundImage(this, "background");
this.AddObject(this.add.text(100, 20, "War.IO"), "obj_introText");
Expand All @@ -35,11 +55,13 @@ export class MenuScene extends BaseScene {
let playBtn = playerForm.getChildByName("btnJoin");
let createSessionBtn = playerForm.getChildByName("btnCreate");
const tutorialBtn = playerForm.getChildByName("btnTutorial");

let inputField = playerForm.getChildByName("nameInput");

inputField?.addEventListener("input", (event) => {
var inputName = playerForm.getChildByName("nameInput") as Element & { value: string };
var inputName = <Element & { value: string }>(
playerForm.getChildByName("nameInput")
);
if (!inputName) return;
if (inputName.value !== "") {
let name = inputName.value.trim().replace(" ", "-");
Expand All @@ -54,7 +76,7 @@ export class MenuScene extends BaseScene {
event.stopPropagation();
this.scene.start(CONSTANT.SCENES.TUTORIAL);
});

playerForm.addListener("click");
playerForm.on("click", function (event: any) {
event.stopPropagation();
Expand All @@ -66,12 +88,17 @@ export class MenuScene extends BaseScene {
});

createSessionBtn?.addEventListener("pointerdown", async (event) => {
event.stopPropagation();
await this.onCreateSessionClick();
try {
event.stopPropagation();

await this.onCreateSessionClick();
} catch (error) {
console.log(error);
}
});

this.AddSceneEvent("shutdown", (data: any) => {
console.log("shutdown ", data.config.key);
console.log(`[shutdown]: ${data.config.key}`);
this.Destroy();
});

Expand All @@ -86,7 +113,9 @@ export class MenuScene extends BaseScene {
const networkManager = this.registry.get(
"networkManager"
) as NetworkManager;
var inputName = playerForm.getChildByName("nameInput") as Element & { value: string };
var inputName = <Element & { value: string }>(
playerForm.getChildByName("nameInput")
);
if (inputName?.nodeValue !== "") {
let name = inputName?.value.trim().replace(" ", "-");
networkManager.setPlayerName(name || "");
Expand All @@ -109,7 +138,7 @@ export class MenuScene extends BaseScene {
this.scene.start(CONSTANT.SCENES.MENU);
};
//join session
await(
await (
this.registry.get("networkManager") as NetworkManager
).connectGameServer(`${URL}/${sessionId}`);
} catch (err) {
Expand All @@ -130,29 +159,23 @@ export class MenuScene extends BaseScene {
"obj_playerForm"
)?.getChildByName("nameInput") as Element & { value: string })!.value;
const sessions = await networkManager.getAvailableSession();
console.log('available sessions ', sessions);
}
catch(error) {

}
console.log("available sessions ", sessions);
} catch (error) {}
}
async onCreateSessionClick() {
try {
const networkManager = this.registry.get(
"networkManager"
) as NetworkManager;
const networkManager = <NetworkManager>(
this.registry.get("networkManager")
);
const spinner = <SpinnerPlugin.Spinner>this.GetObject("obj_spinner");
spinner.setVisible(true);
if (!networkManager) {
throw new Error("NetworkManager is not defined");
}

const playerName = (this.GetObject<Phaser.GameObjects.DOMElement>(
"obj_playerForm"
)?.getChildByName("nameInput") as Element & { value: string })!.value;
await networkManager?.hostAndJoinSession(
`${playerName}`
);

console.log("[client id] : ", networkManager?.getClientId());
await networkManager?.hostAndJoinSession(`${playerName}`);
this.scene.start(CONSTANT.SCENES.SESSIONLOBBY);
} catch (error) {
console.log(error);
Expand Down
Loading

0 comments on commit 58ab9a7

Please sign in to comment.