Skip to content

Commit

Permalink
Code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
keshav2010 committed May 4, 2024
1 parent f8d30ef commit ad5b702
Show file tree
Hide file tree
Showing 12 changed files with 167 additions and 126 deletions.
20 changes: 15 additions & 5 deletions gameserver/commands/OnSoldierCreateCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,20 @@ export class OnSoldierCreateCommand extends Command<
CommandPayload
> {
execute({ client, message, gameManager }: CommandPayload) {
console.log('received soldier create request, queueing');
let lengthBefore = this.state.getPlayer(client.id)?.spawnRequestDetailMap.size;
this.state.getPlayer(client.id)?.queueSpawnRequest(message.soldierType);
let lengthAfter = this.state.getPlayer(client.id)?.spawnRequestDetailMap.size;
console.log(`added to queue ${lengthAfter} <-- ${lengthBefore}`)
console.log("received soldier create request, queueing");
try {
this.state
.getPlayer(client.id)
?.addNewSoldier("SPEARMAN", gameManager!.scene);
return;
let lengthBefore = this.state.getPlayer(client.id)?.spawnRequestDetailMap
.size;
this.state.getPlayer(client.id)?.queueSpawnRequest(message.soldierType);
let lengthAfter = this.state.getPlayer(client.id)?.spawnRequestDetailMap
.size;
console.log(`added to queue ${lengthAfter} <-- ${lengthBefore}`);
} catch (error) {
console.error(error);
}
}
}
2 changes: 1 addition & 1 deletion gameserver/commands/OnSoldierMoveCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class OnSoldierMoveCommand extends Command<SessionRoom, CommandPayload> {
.map((id) => this.state.getPlayer(client.sessionId)?.getSoldier(id))
.filter(Boolean) as SoldierState[];
if (soldierObjects.length === 0) return;
const offset = 96;
const offset = 80;
const gridFormation = new GroupFormation(
soldierObjects,
offset,
Expand Down
17 changes: 10 additions & 7 deletions gameserver/core/Scene.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,14 @@ export class Scene extends Quadtree<TypeQuadtreeItem> {
* @returns
*/
getNearbyUnits(
x: number,
y: number,
centerX: number,
centerY: number,
squareWidth: number,
type?: SceneObjectType[]
) {
const query: TypeQuadtreeItem = {
x: x - squareWidth / 2,
y: y - squareWidth / 2,
x: centerX - squareWidth / 2,
y: centerY - squareWidth / 2,
w: squareWidth,
h: squareWidth,
width: squareWidth,
Expand All @@ -74,7 +74,10 @@ export class Scene extends Quadtree<TypeQuadtreeItem> {
collidable: false,
};
let result = this.colliding(query);
if (type) result = result.filter((body) => type?.includes(body.type));
if (type)
result = result.filter(
(body) => type?.includes(body.type) && body.id !== "query-object"
);
return result;
}

Expand All @@ -88,8 +91,8 @@ export class Scene extends Quadtree<TypeQuadtreeItem> {

//fetch all bodies which are colliding with the soldier specified by x,y,r in arg.
let bodiesNearby = this.getNearbyUnits(
mainCollidingObject.pos.x,
mainCollidingObject.pos.y,
mainCollidingObject.getCircleCenter().x,
mainCollidingObject.getCircleCenter().y,
mainCollidingObject.width,
bodyTypeToCheck
);
Expand Down
4 changes: 2 additions & 2 deletions gameserver/core/types/SceneObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ export class SceneObject extends SAT.Box {
this.id = id;

// top-left corner of square hitbox
this.x = this.pos.x;
this.y = this.pos.y;
this.x = x;
this.y = y;
this.r = size / 2;
this.type = type;
this.collidable = collidable;
Expand Down
2 changes: 1 addition & 1 deletion gameserver/schema/PlayerState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export class PlayerState extends Schema implements ISceneItem {
sessionId,
x,
y,
100,
64,
"FIXED",
false
);
Expand Down
19 changes: 13 additions & 6 deletions gameserver/schema/SoldierState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,8 @@ export class SoldierState extends Schema implements ISceneItem, IBoidAgent {
) {
const soldier = this.getSceneItem();
const nearbyUnits = stateManager.scene.getNearbyUnits(
soldier.x,
soldier.y,
soldier.getCircleCenter().x,
soldier.getCircleCenter().y,
MOVABLE_UNIT_CONSTANTS.NEARBY_SEARCH_RADI,
["MOVABLE"]
);
Expand Down Expand Up @@ -320,20 +320,27 @@ export class SoldierState extends Schema implements ISceneItem, IBoidAgent {
}
}
);
const soldierCenterPosition = this.getSceneItem().getCircleCenter();

const enemyTowers = stateManager.scene
.getNearbyUnits(this.currentPositionX, this.currentPositionY, 100, [
"FIXED",
])
.getNearbyUnits(
this.currentPositionX,
this.currentPositionY,
100,
["FIXED"]
)
.filter(
(quadtreeItem) =>
stateManager.getPlayer(quadtreeItem.id) &&
quadtreeItem.id !== this.playerId
quadtreeItem.id !== this.playerId &&
stateManager.getPlayer(quadtreeItem.id)!.getSceneItem().getCircleCenter().clone().sub(soldierCenterPosition).len() < 100
)
.map((d) => stateManager.getPlayer(d.id));

enemyTowers.forEach((playerBase) => {
if (!playerBase) return;
const enemyTowerCenter = playerBase.getSceneItem().getCircleCenter();
console.log('dist = ',enemyTowerCenter.clone().sub(soldierCenterPosition).len());
const flagHealth = playerBase.spawnFlagHealth - 0.45 * delta;
playerBase.spawnFlagHealth = Math.max(0, flagHealth);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ export default {

// if nearby unit getting attacked.
const nearbyUnits = stateManager.scene.getNearbyUnits(
soldier.getSceneItem().pos.x,
soldier.getSceneItem().pos.y,
soldier.getSceneItem().getCircleCenter().x,
soldier.getSceneItem().getCircleCenter().y,
MOVABLE_UNIT_CONSTANTS.NEARBY_SEARCH_RADI,
['MOVABLE']
);
Expand Down Expand Up @@ -78,8 +78,8 @@ export default {
}
soldier.move(delta, stateManager);
const nearbyUnits = stateManager.scene.getNearbyUnits(
soldier.getSceneItem().pos.x,
soldier.getSceneItem().pos.y,
soldier.getSceneItem().getCircleCenter().x,
soldier.getSceneItem().getCircleCenter().y,
MOVABLE_UNIT_CONSTANTS.NEARBY_SEARCH_RADI,
["MOVABLE"]
);
Expand Down Expand Up @@ -162,9 +162,9 @@ export default {
}) => {
try {
soldier.setAttackTarget(null);
var nearbyUnits = stateManager.scene.getNearbyUnits(
soldier.getSceneItem().pos.x,
soldier.getSceneItem().pos.y,
const nearbyUnits = stateManager.scene.getNearbyUnits(
soldier.getSceneItem().getCircleCenter().x,
soldier.getSceneItem().getCircleCenter().y,
MOVABLE_UNIT_CONSTANTS.NEARBY_SEARCH_RADI,
["MOVABLE"]
);
Expand Down
Binary file renamed public/assets/flag.png → public/assets/castle.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
13 changes: 9 additions & 4 deletions public/gameObjects/playerCastle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export class PlayerCastle extends Phaser.GameObjects.Sprite {
super(scene, x, y, texture, frame);
this.health = initialParam?.health || 100;
scene.add.existing(this);
this.setOrigin(0);
this.player = initialParam.player;
scene.events.on("update", this.update, this);
this.setPosition(x, y);
Expand All @@ -45,7 +46,7 @@ export class PlayerCastle extends Phaser.GameObjects.Sprite {
});

// Create the circle of influence
this.createCircleOfInfluence(scene, x, y, 100); // Assuming a radius of 100
this.createCircleOfInfluence(scene, x, y, this.height / 2); // Assuming a radius of 100
}

createCircleOfInfluence(
Expand All @@ -55,7 +56,7 @@ export class PlayerCastle extends Phaser.GameObjects.Sprite {
radius: number
) {
this.circleOfInfluence = scene.add.graphics();
this.circleOfInfluence.lineStyle(5, 0xffffff, 1); // Thickness, color, alpha
this.circleOfInfluence.lineStyle(3, 0xffffff); // Thickness, color, alpha
this.circleOfInfluence.strokeCircle(x, y, radius);

// Animate the circle
Expand All @@ -71,8 +72,12 @@ export class PlayerCastle extends Phaser.GameObjects.Sprite {
renderCircleOfInfluence(x: number, y: number) {
if (this.circleOfInfluence) {
this.circleOfInfluence.clear();
this.circleOfInfluence.lineStyle(5, 0xffffff, 1);
this.circleOfInfluence.strokeCircle(x, y, 100); // Assuming a fixed radius
this.circleOfInfluence.lineStyle(1, 0xffffff, 1);
this.circleOfInfluence.strokeCircle(x, y, this.height / 2); // Assuming a fixed radius
this.circleOfInfluence.lineStyle(1, 0x22ffff, 1);
this.circleOfInfluence.strokeRectShape(
new Phaser.Geom.Rectangle(x, y, 64, 64)
);
}
}

Expand Down
74 changes: 10 additions & 64 deletions public/scenes/GameScene.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ 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 @@ -74,7 +73,7 @@ export class GameScene extends BaseScene {
this.load.image("playbutton", "../assets/playbutton.png");
this.load.image("knight", "../assets/knight.png");
this.load.image("texture_spearman", "../assets/spearman.png");
this.load.image("flag", "../assets/flag.png");
this.load.image("castle", "../assets/castle.png");
this.load.image("img_groundtiles", "../assets/groundtiles.png");
this.load.tilemapTiledJSON("map1", "../assets/map1.json");
}
Expand Down Expand Up @@ -182,10 +181,10 @@ export class GameScene extends BaseScene {
return;
}

phaserSceneObject.setData("serverPosition", {
x: soldierState.currentPositionX,
y: soldierState.currentPositionY,
});
phaserSceneObject.setServerPosition(
soldierState.currentPositionX,
soldierState.currentPositionY
);
}

onSoldierHealthUpdate(
Expand Down Expand Up @@ -267,7 +266,7 @@ export class GameScene extends BaseScene {
const playerSoldiersGameObject = this.data.get(
"playerSoldiersGameObject"
) as Map<PlayerId, soldierIdToPhaserMap>;
let circle = new Phaser.Geom.Circle(
const circle = new Phaser.Geom.Circle(
pointer.worldX,
pointer.worldY,
16
Expand Down Expand Up @@ -335,10 +334,6 @@ export class GameScene extends BaseScene {
});

this.AddInputEvent("pointermove", (pointer: any) => {
const selectedSoldiersMap = this.data.get("selectedSoldiersMap") as Map<
string,
BaseSoldier
>;
const playerSoldiersGameObject = this.data.get(
"playerSoldiersGameObject"
) as Map<PlayerId, soldierIdToPhaserMap>;
Expand Down Expand Up @@ -416,11 +411,6 @@ export class GameScene extends BaseScene {
.setName("WorldCamera");
this.cameras.main.setBackgroundColor("rgba(255,255,255,0.3)");

var mapGraphics = this.add.graphics();
mapGraphics.depth = -5;
mapGraphics.fillStyle(0x000000, 1);
mapGraphics.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
this.AddObject(mapGraphics);
cursors = this.input.keyboard?.createCursorKeys();
const controlConfig = {
camera: this.cameras.main,
Expand Down Expand Up @@ -590,7 +580,7 @@ export class GameScene extends BaseScene {
//show initial spawnpoint choice on map for player
networkManager.getState()?.players.forEach((player) => {
this.AddObject(
new PlayerCastle(this, player.posX, player.posY, "flag", null, {
new PlayerCastle(this, player.posX, player.posY, "castle", null, {
health: 500,
player: player,
}),
Expand All @@ -607,63 +597,19 @@ export class GameScene extends BaseScene {
this.events.removeAllListeners();
});
}
renderDebugPath() {
const painter = this.GetObject<Phaser.GameObjects.Graphics>("obj_brush")!;
painter.clear();
const soldierPhaserObjs = <Map<PlayerId, soldierIdToPhaserMap>>(
this.data.get("playerSoldiersGameObject")
);
for (let [playerId, soldierMap] of soldierPhaserObjs) {
for (let [soldierId, soldierPhaserObj] of soldierMap) {
const serverPos = <{ x: number; y: number }>(
soldierPhaserObj.getData("serverPosition")
);
painter.lineStyle(3, 0x000000, 1);
painter.strokeCircle(serverPos.x, serverPos.y, 32!);
}
}

const clientId = networkManager.getClientId();
const sessionState = networkManager.getState();
if (!sessionState || !clientId) return;
const playerState = SessionStateClientHelpers.getPlayer(
sessionState,
clientId
);
playerState?.soldiers.forEach((value) => {
painter.lineStyle(3, 0xffffff, 1);
painter.strokeCircle(
value.expectedPositionX,
value.expectedPositionY,
value.radius
);
painter.lineStyle(1, 0xffffee, 1);
painter.strokeLineShape(
new Phaser.Geom.Line(
value.currentPositionX,
value.currentPositionY,
value.expectedPositionX,
value.expectedPositionY
)
);
});
}

update(delta: number) {
this.renderDebugPath();
this.controls?.update(delta);

const soldierPhaserObjs = <Map<PlayerId, soldierIdToPhaserMap>>(
this.data.get("playerSoldiersGameObject")
);
for (let [playerId, soldierMap] of soldierPhaserObjs) {
for (let [soldierId, soldierPhaserObj] of soldierMap) {
const serverPos = <{ x: number; y: number }>(
soldierPhaserObj.getData("serverPosition")
);
const serverPos = soldierPhaserObj.getServerPosition();
soldierPhaserObj.setPosition(
Phaser.Math.Linear(soldierPhaserObj.x, serverPos.x, 0.15),
Phaser.Math.Linear(soldierPhaserObj.y, serverPos.y, 0.15)
Phaser.Math.Linear(soldierPhaserObj.x, serverPos.x, BaseSoldier.LERP_RATE),
Phaser.Math.Linear(soldierPhaserObj.y, serverPos.y, BaseSoldier.LERP_RATE)
);
}
}
Expand Down
4 changes: 2 additions & 2 deletions public/scenes/SpawnSelectionScene.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class SpawnSelectionScene extends BaseScene {
this.load.image("playbutton", "../assets/playbutton.png");
this.load.image("knight", "../assets/knight.png");
this.load.image("spearman", "../assets/spearman.png");
this.load.image("flag", "../assets/flag.png");
this.load.image("castle", "../assets/castle.png");
this.load.image("img_groundtiles", "../assets/groundtiles.png");
this.load.tilemapTiledJSON("map1", "../assets/map1.json");
}
Expand Down Expand Up @@ -263,7 +263,7 @@ export class SpawnSelectionScene extends BaseScene {
spawnFlag.setPosition(x, y);
spawnFlag.setHealth(2);
} else {
const castle = new PlayerCastle(this, x, y, "flag", null, {
const castle = new PlayerCastle(this, x, y, "castle", null, {
health: playerState.spawnFlagHealth,
player: playerState,
});
Expand Down
Loading

0 comments on commit ad5b702

Please sign in to comment.