From 8d8df24230b360e0959c09243b1341b548e3da0f Mon Sep 17 00:00:00 2001 From: Nick Kosarev Date: Wed, 8 May 2024 11:03:34 +0200 Subject: [PATCH] lint fix --- apps/api/src/bot/bot.controller.ts | 90 +- apps/api/src/bot/bot.service.ts | 84 +- apps/api/src/config.ts | 30 +- apps/api/src/db/db.client.ts | 4 +- apps/api/src/db/db.repository.ts | 94 +- apps/api/src/game/chunks/forest.ts | 40 +- apps/api/src/game/chunks/gameChunk.ts | 82 +- apps/api/src/game/chunks/index.ts | 6 +- apps/api/src/game/chunks/lake.ts | 50 +- apps/api/src/game/chunks/village.ts | 108 +- apps/api/src/game/common/event.ts | 72 +- apps/api/src/game/common/group.ts | 32 +- apps/api/src/game/common/index.ts | 10 +- apps/api/src/game/common/inventory.ts | 104 +- apps/api/src/game/common/route.ts | 106 +- apps/api/src/game/common/skill.ts | 56 +- apps/api/src/game/game.ts | 62 +- .../src/game/objects/buildings/building.ts | 28 +- .../src/game/objects/buildings/campfire.ts | 10 +- .../src/game/objects/buildings/wagonStop.ts | 10 +- .../src/game/objects/buildings/warehouse.ts | 10 +- apps/api/src/game/objects/flag.ts | 50 +- apps/api/src/game/objects/gameObject.ts | 112 +- apps/api/src/game/objects/index.ts | 14 +- apps/api/src/game/objects/lake.ts | 60 +- apps/api/src/game/objects/rabbit.ts | 30 +- apps/api/src/game/objects/stone.ts | 74 +- apps/api/src/game/objects/tree.ts | 156 +- apps/api/src/game/objects/units/index.ts | 2 +- apps/api/src/game/objects/units/mechanic.ts | 20 +- apps/api/src/game/objects/units/player.ts | 234 +-- apps/api/src/game/objects/units/raider.ts | 34 +- apps/api/src/game/objects/units/unit.ts | 44 +- .../src/game/objects/units/villageCourier.ts | 66 +- .../src/game/objects/units/villageFarmer.ts | 68 +- apps/api/src/game/objects/wagon.ts | 120 +- apps/api/src/game/objects/water.ts | 16 +- apps/api/src/game/objects/wolf.ts | 26 +- apps/api/src/game/scenes/defenceScene.ts | 80 +- apps/api/src/game/scenes/gameScene.ts | 779 +++++----- apps/api/src/game/scenes/index.ts | 8 +- apps/api/src/game/scenes/movingScene.ts | 42 +- apps/api/src/game/scenes/villageScene.ts | 34 +- apps/api/src/index.ts | 40 +- apps/api/src/websocket/websocket.server.ts | 20 +- apps/client/src/components/chunkBlock.tsx | 23 +- apps/client/src/components/dealer.tsx | 64 +- apps/client/src/components/eventCard.tsx | 21 +- apps/client/src/components/eventsBlock.tsx | 12 +- .../client/src/components/groupPlayerCard.tsx | 19 +- apps/client/src/components/groupPlayers.tsx | 21 +- apps/client/src/components/interface.tsx | 81 +- apps/client/src/components/loader.tsx | 4 +- .../src/components/player-full-body.tsx | 12 +- apps/client/src/components/player-skill.tsx | 33 +- apps/client/src/components/player-top.tsx | 6 +- apps/client/src/components/routeBlock.tsx | 43 +- apps/client/src/components/tool.tsx | 62 +- apps/client/src/components/topPlayerCard.tsx | 44 +- apps/client/src/components/topPlayers.tsx | 15 +- .../client/src/components/wagonStatsBlock.tsx | 44 +- .../src/game/components/buildingInterface.ts | 102 +- .../game/components/fireParticlesContainer.ts | 64 +- .../src/game/components/graphicsContainer.ts | 38 +- .../src/game/components/playerInterface.ts | 42 +- .../src/game/components/unitHairContainer.ts | 28 +- .../src/game/components/unitHeadContainer.ts | 28 +- .../src/game/components/unitInterface.ts | 288 ++-- .../src/game/components/unitTopContainer.ts | 28 +- .../components/wagonEngineCloudsContainer.ts | 58 +- .../game/components/wagonEngineContainer.ts | 20 +- .../game/components/wagonWheelContainer.ts | 26 +- apps/client/src/game/game.ts | 384 ++--- apps/client/src/game/index.ts | 6 +- .../src/game/objects/buildings/building.ts | 22 +- .../src/game/objects/buildings/campfire.ts | 48 +- .../src/game/objects/buildings/wagonStop.ts | 26 +- .../src/game/objects/buildings/warehouse.ts | 36 +- apps/client/src/game/objects/flag.ts | 42 +- .../src/game/objects/gameObjectContainer.ts | 54 +- apps/client/src/game/objects/index.ts | 12 +- apps/client/src/game/objects/lake.ts | 38 +- apps/client/src/game/objects/rabbit.ts | 50 +- apps/client/src/game/objects/stone.ts | 56 +- apps/client/src/game/objects/tree.ts | 98 +- apps/client/src/game/objects/units/courier.ts | 12 +- apps/client/src/game/objects/units/farmer.ts | 12 +- apps/client/src/game/objects/units/index.ts | 2 +- .../client/src/game/objects/units/mechanic.ts | 16 +- apps/client/src/game/objects/units/player.ts | 78 +- apps/client/src/game/objects/units/raider.ts | 16 +- apps/client/src/game/objects/units/unit.ts | 132 +- apps/client/src/game/objects/wagon.ts | 102 +- apps/client/src/game/objects/wolf.ts | 52 +- apps/client/src/game/utils/assetsManager.ts | 367 ++--- apps/client/src/game/utils/audioManager.ts | 80 +- .../src/game/utils/generators/background.ts | 1340 ++--------------- .../game/utils/generators/backgroundImages.ts | 88 ++ apps/client/src/game/utils/index.ts | 8 +- apps/client/src/game/utils/sceneManager.ts | 14 +- .../client/src/game/utils/webSocketManager.ts | 36 +- apps/client/src/hooks/useCountdown.ts | 30 +- apps/client/src/hooks/useScene.ts | 28 +- apps/client/src/hooks/useTopPlayers.ts | 28 +- apps/client/src/main.tsx | 10 +- apps/client/vite.config.ts | 8 +- biome.json | 12 +- packages/api-sdk/src/index.ts | 10 +- packages/api-sdk/src/lib/client.ts | 32 +- packages/api-sdk/src/lib/date.ts | 8 +- packages/api-sdk/src/lib/messageController.ts | 8 +- packages/api-sdk/src/lib/random.ts | 4 +- packages/api-sdk/src/lib/types.ts | 247 ++- 113 files changed, 3557 insertions(+), 4538 deletions(-) create mode 100644 apps/client/src/game/utils/generators/backgroundImages.ts diff --git a/apps/api/src/bot/bot.controller.ts b/apps/api/src/bot/bot.controller.ts index ac2699c5..4de895b0 100644 --- a/apps/api/src/bot/bot.controller.ts +++ b/apps/api/src/bot/bot.controller.ts @@ -1,38 +1,38 @@ -import { RefreshingAuthProvider } from "@twurple/auth"; -import { Bot } from "@twurple/easy-bot"; -import { PubSubClient } from "@twurple/pubsub"; -import type { Game } from "../game/game"; -import { BotService } from "./bot.service"; +import { RefreshingAuthProvider } from "@twurple/auth" +import { Bot } from "@twurple/easy-bot" +import { PubSubClient } from "@twurple/pubsub" +import type { Game } from "../game/game" +import { BotService } from "./bot.service" export class BotController { - private readonly channel = process.env.TWITCH_CHANNEL_NAME as string; - private readonly userId = process.env.TWITCH_CHANNEL_ID as string; - private readonly clientId = process.env.TWITCH_CLIENT_ID as string; - private readonly clientSecret = process.env.TWITCH_SECRET_ID as string; + private readonly channel = process.env.TWITCH_CHANNEL_NAME as string + private readonly userId = process.env.TWITCH_CHANNEL_ID as string + private readonly clientId = process.env.TWITCH_CLIENT_ID as string + private readonly clientSecret = process.env.TWITCH_SECRET_ID as string - private readonly service: BotService; + private readonly service: BotService constructor(game: Game) { - this.service = new BotService(game); + this.service = new BotService(game) } private async prepareAuthProvider() { - const tokenFile = Bun.file(`./apps/api/tmp/${this.userId}.token.json`); - const tokenData = await tokenFile.json(); + const tokenFile = Bun.file(`./apps/api/tmp/${this.userId}.token.json`) + const tokenData = await tokenFile.json() const authProvider = new RefreshingAuthProvider({ clientId: this.clientId, clientSecret: this.clientSecret, - }); + }) authProvider.onRefresh(async (_, newTokenData) => { - const data = JSON.stringify(newTokenData, null, 4); - await Bun.write(tokenFile, data); - }); + const data = JSON.stringify(newTokenData, null, 4) + await Bun.write(tokenFile, data) + }) - await authProvider.addUserForToken(tokenData, ["chat", "channel"]); + await authProvider.addUserForToken(tokenData, ["chat", "channel"]) - return authProvider; + return authProvider } prepareBotCommands() { @@ -50,21 +50,21 @@ export class BotController { this.service.commandBuy(), this.service.commandHelp(), this.service.commandDonate(), - ]; + ] } public async serve() { - const authProvider = await this.prepareAuthProvider(); + const authProvider = await this.prepareAuthProvider() - const pubSubClient = new PubSubClient({ authProvider }); + const pubSubClient = new PubSubClient({ authProvider }) pubSubClient.onRedemption(this.userId, ({ userId, userName, rewardId }) => { this.service.reactOnChannelRewardRedemption({ userId, userName, rewardId, - }); - }); + }) + }) const bot = new Bot({ authProvider, @@ -73,50 +73,50 @@ export class BotController { chatClientOptions: { requestMembershipEvents: true, }, - }); + }) bot.onRaid(({ broadcasterName, userName, userId, viewerCount }) => { - void bot.say(broadcasterName, `@${userName} устроил(а) рейд! Готовимся!`); - void this.service.reactOnRaid({ userName, userId, viewerCount }); - }); + void bot.say(broadcasterName, `@${userName} устроил(а) рейд! Готовимся!`) + void this.service.reactOnRaid({ userName, userId, viewerCount }) + }) bot.onRaidCancel((event) => { - console.log("raid canceled!", event); - }); + console.log("raid canceled!", event) + }) bot.onMessage(({ userId, isAction, text }) => { - console.log("message", userId, isAction, text); - }); + console.log("message", userId, isAction, text) + }) bot.onAction(({ userId, userName, isAction, text }) => { - console.log("action!", userId, userName, isAction, text); - }); + console.log("action!", userId, userName, isAction, text) + }) bot.onJoin(({ userName }) => { - console.log(new Date().toLocaleTimeString(), "joined!", userName); - }); + console.log(new Date().toLocaleTimeString(), "joined!", userName) + }) bot.onLeave(({ userName }) => { - console.log("left!", userName); - }); + console.log("left!", userName) + }) bot.onSub(({ broadcasterName, userName }) => { void bot.say( broadcasterName, `Thanks to @${userName} for subscribing to the channel!`, - ); - }); + ) + }) bot.onResub(({ broadcasterName, userName, months }) => { void bot.say( broadcasterName, `Thanks to @${userName} for subscribing to the channel for a total of ${months} months!`, - ); - }); + ) + }) bot.onSubGift(({ broadcasterName, gifterName, userName }) => { void bot.say( broadcasterName, `Thanks to @${gifterName} for gifting a subscription to @${userName}!`, - ); - }); + ) + }) - return bot; + return bot } } diff --git a/apps/api/src/bot/bot.service.ts b/apps/api/src/bot/bot.service.ts index 0be4b8e2..fae78792 100644 --- a/apps/api/src/bot/bot.service.ts +++ b/apps/api/src/bot/bot.service.ts @@ -1,13 +1,13 @@ -import { createBotCommand } from "@twurple/easy-bot"; -import type { IGameSceneAction } from "../../../../packages/api-sdk/src"; -import { TWITCH_CHANNEL_REWARDS } from "../config"; -import type { Game } from "../game/game"; +import { createBotCommand } from "@twurple/easy-bot" +import type { IGameSceneAction } from "../../../../packages/api-sdk/src" +import { TWITCH_CHANNEL_REWARDS } from "../config" +import type { Game } from "../game/game" export class BotService { - public game: Game; + public game: Game constructor(game: Game) { - this.game = game; + this.game = game } private buildCommand(commandName: string, action: IGameSceneAction) { @@ -19,103 +19,103 @@ export class BotService { userId, userName, params, - }); + }) if (result.message) { - void reply(result.message); + void reply(result.message) } }, - ); + ) } public commandStartChangingScene() { - return this.buildCommand("вернуться", "START_CHANGING_SCENE"); + return this.buildCommand("вернуться", "START_CHANGING_SCENE") } public commandStartGroupBuild() { - return this.buildCommand("собрать", "START_GROUP_BUILD"); + return this.buildCommand("собрать", "START_GROUP_BUILD") } public commandJoinGroup() { - return this.buildCommand("го", "JOIN_GROUP"); + return this.buildCommand("го", "JOIN_GROUP") } public commandDisbandGroup() { - return this.buildCommand("расформировать", "DISBAND_GROUP"); + return this.buildCommand("расформировать", "DISBAND_GROUP") } public commandStartCreatingNewAdventure() { - return this.buildCommand("путешествовать", "START_CREATING_NEW_ADVENTURE"); + return this.buildCommand("путешествовать", "START_CREATING_NEW_ADVENTURE") } public commandRefuel() { - return this.buildCommand("заправить", "REFUEL"); + return this.buildCommand("заправить", "REFUEL") } public commandChop() { - return this.buildCommand("рубить", "CHOP"); + return this.buildCommand("рубить", "CHOP") } public commandMine() { - return this.buildCommand("добыть", "MINE"); + return this.buildCommand("добыть", "MINE") } public commandGift() { - return this.buildCommand("подарить", "GIFT"); + return this.buildCommand("подарить", "GIFT") } public commandSell() { - return this.buildCommand("продать", "SELL"); + return this.buildCommand("продать", "SELL") } public commandBuy() { - return this.buildCommand("купить", "BUY"); + return this.buildCommand("купить", "BUY") } public commandHelp() { - return this.buildCommand("помощь", "HELP"); + return this.buildCommand("помощь", "HELP") } public commandDonate() { - return this.buildCommand("донат", "DONATE"); + return this.buildCommand("донат", "DONATE") } public async reactOnRaid({ - userName, - userId, - viewerCount, - }: { - userName: string; - userId: string; - viewerCount: number; + userName, + userId, + viewerCount, + }: { + userName: string + userId: string + viewerCount: number }) { return this.game.handleChatCommand({ action: "START_RAID", userId, userName, viewerCount, - }); + }) } public async reactOnChannelRewardRedemption({ - userId, - userName, - rewardId, - }: { - userId: string; - userName: string; - rewardId: string; + userId, + userName, + rewardId, + }: { + userId: string + userName: string + rewardId: string }) { - console.log("reactOnChannelRewardRedemption", userId, userName, rewardId); + console.log("reactOnChannelRewardRedemption", userId, userName, rewardId) const player = await this.game.repository.findOrCreatePlayer( userId, userName, - ); + ) if (rewardId === TWITCH_CHANNEL_REWARDS.add150ViewerPointsId) { - await this.game.repository.addPlayerViewerPoints(player.id, 150); - return; + await this.game.repository.addPlayerViewerPoints(player.id, 150) + return } if (rewardId === TWITCH_CHANNEL_REWARDS.villainStealFuelId) { - await this.game.scene.stealFuelAction(player.id); + await this.game.scene.stealFuelAction(player.id) return } } diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts index d526d926..091bbf29 100644 --- a/apps/api/src/config.ts +++ b/apps/api/src/config.ts @@ -1,22 +1,22 @@ -export const SERVER_TICK_MS = 25; +export const SERVER_TICK_MS = 25 -export const MIN_X = 20; -export const MAX_X = 2520; +export const MIN_X = 20 +export const MAX_X = 2520 -export const MIN_Y = 120; -export const MAX_Y = 1190; +export const MIN_Y = 120 +export const MAX_Y = 1190 -export const RAIDER_CAMP_MIN_X = 3000; -export const RAIDER_CAMP_MAX_X = 3500; -export const RAIDER_CAMP_MIN_Y = 120; -export const RAIDER_CAMP_MAX_Y = 1190; +export const RAIDER_CAMP_MIN_X = 3000 +export const RAIDER_CAMP_MAX_X = 3500 +export const RAIDER_CAMP_MIN_Y = 120 +export const RAIDER_CAMP_MAX_Y = 1190 -export const DONATE_URL = "https://www.donationalerts.com/r/hmbanan666"; -export const DISCORD_SERVER_INVITE_URL = "https://discord.gg/B6etUajrGZ"; +export const DONATE_URL = "https://www.donationalerts.com/r/hmbanan666" +export const DISCORD_SERVER_INVITE_URL = "https://discord.gg/B6etUajrGZ" export const TWITCH_CHANNEL_REWARDS = { - "add150ViewerPointsId": "d8237822-c943-434f-9d7e-87a9f549f4c4", - "villainStealFuelId": "d5956de4-54ff-49e4-afbe-ee4e62718eee" -}; + add150ViewerPointsId: "d8237822-c943-434f-9d7e-87a9f549f4c4", + villainStealFuelId: "d5956de4-54ff-49e4-afbe-ee4e62718eee", +} -export const ADMIN_PLAYER_ID = "svhjz9p5467wne9ybasf1bwy"; +export const ADMIN_PLAYER_ID = "svhjz9p5467wne9ybasf1bwy" diff --git a/apps/api/src/db/db.client.ts b/apps/api/src/db/db.client.ts index dff3b3e9..c4333030 100644 --- a/apps/api/src/db/db.client.ts +++ b/apps/api/src/db/db.client.ts @@ -1,3 +1,3 @@ -import { PrismaClient } from "@prisma/client"; +import { PrismaClient } from "@prisma/client" -export const db = new PrismaClient(); +export const db = new PrismaClient() diff --git a/apps/api/src/db/db.repository.ts b/apps/api/src/db/db.repository.ts index 2db11a5a..a11ea0c8 100644 --- a/apps/api/src/db/db.repository.ts +++ b/apps/api/src/db/db.repository.ts @@ -1,47 +1,47 @@ -import { createId } from "@paralleldrive/cuid2"; -import { getRandomInRange } from "../../../../packages/api-sdk/src"; -import { db } from "./db.client"; +import { createId } from "@paralleldrive/cuid2" +import { getRandomInRange } from "../../../../packages/api-sdk/src" +import { db } from "./db.client" export class DBRepository { - private readonly db; + private readonly db constructor() { - this.db = db; + this.db = db } findVillage() { - return db.village.findFirst(); + return db.village.findFirst() } findActivePlayers() { - const milliseconds = 20 * 60 * 1000; - const gte = new Date(new Date().getTime() - milliseconds); + const milliseconds = 20 * 60 * 1000 + const gte = new Date(new Date().getTime() - milliseconds) return this.db.player.findMany({ where: { lastActionAt: { gte }, }, - }); + }) } async findTopPlayers() { const famous = await db.player.findFirst({ orderBy: { reputation: "desc" }, - }); + }) const rich = await db.player.findFirst({ orderBy: { coins: "desc" }, - }); + }) const viewer = await db.player.findFirst({ orderBy: { viewerPoints: "desc" }, - }); + }) const villain = await db.player.findFirst({ orderBy: { villainPoints: "desc" }, }) const refueller = await db.player.findFirst({ orderBy: { refuellerPoints: "desc" }, }) - const woodsman = await this.findTopWoodsmanPlayer(); - const miner = await this.findTopMinerPlayer(); + const woodsman = await this.findTopWoodsmanPlayer() + const miner = await this.findTopMinerPlayer() return { famous: { @@ -66,63 +66,63 @@ export class DBRepository { }, woodsman, miner, - }; + } } async findTopWoodsmanPlayer() { const topSkill = await db.skill.findFirst({ where: { type: "WOODSMAN" }, orderBy: { lvl: "desc" }, - }); + }) if (!topSkill) { - return null; + return null } const player = await db.player.findUnique({ where: { id: topSkill.objectId }, - }); + }) return { player, points: topSkill.lvl, - }; + } } async findTopMinerPlayer() { const topSkill = await db.skill.findFirst({ where: { type: "MINER" }, orderBy: { lvl: "desc" }, - }); + }) if (!topSkill) { - return null; + return null } const player = await db.player.findUnique({ where: { id: topSkill.objectId }, - }); + }) return { player, points: topSkill.lvl, - }; + } } findPlayerByTwitchId(twitchId: string) { return this.db.player.findFirst({ where: { twitchId }, - }); + }) } createPlayer({ - twitchId, - userName, - inventoryId, - id, - }: { - twitchId: string; - userName: string; - inventoryId: string; - id: string; + twitchId, + userName, + inventoryId, + id, + }: { + twitchId: string + userName: string + inventoryId: string + id: string }) { - const colorIndex = getRandomInRange(0, 360); + const colorIndex = getRandomInRange(0, 360) return db.player.create({ data: { id, @@ -133,23 +133,23 @@ export class DBRepository { colorIndex, inventoryId, }, - }); + }) } async findOrCreatePlayer(twitchId: string, userName: string) { - const player = await this.findPlayerByTwitchId(twitchId); + const player = await this.findPlayerByTwitchId(twitchId) if (!player) { - const id = createId(); - const inventory = await this.createInventory(id); + const id = createId() + const inventory = await this.createInventory(id) return this.createPlayer({ id, twitchId, userName, inventoryId: inventory.id, - }); + }) } - return player; + return player } createInventory(objectId: string) { @@ -158,7 +158,7 @@ export class DBRepository { id: createId(), objectId, }, - }); + }) } addPlayerViewerPoints(id: string, increment: number) { @@ -167,7 +167,7 @@ export class DBRepository { data: { viewerPoints: { increment }, }, - }); + }) } addWoodToVillage(increment: number) { @@ -175,7 +175,7 @@ export class DBRepository { data: { wood: { increment }, }, - }); + }) } async addStoneToVillage(amount: number) { @@ -185,15 +185,15 @@ export class DBRepository { increment: amount, }, }, - }); + }) // Global target - const village = await this.findVillage(); + const village = await this.findVillage() if (village?.globalTargetSuccess && village?.globalTarget) { const plusToTarget = village.globalTargetSuccess >= village.globalTarget + amount ? amount - : 0; + : 0 await db.village.updateMany({ data: { @@ -201,7 +201,7 @@ export class DBRepository { increment: plusToTarget, }, }, - }); + }) } } } diff --git a/apps/api/src/game/chunks/forest.ts b/apps/api/src/game/chunks/forest.ts index f0b36269..061496cf 100644 --- a/apps/api/src/game/chunks/forest.ts +++ b/apps/api/src/game/chunks/forest.ts @@ -1,14 +1,14 @@ import { type IGameForestChunk, getRandomInRange, -} from "../../../../../packages/api-sdk/src"; -import { Tree, Stone } from "../objects"; -import { GameChunk } from "./gameChunk"; +} from "../../../../../packages/api-sdk/src" +import { Stone, Tree } from "../objects" +import { GameChunk } from "./gameChunk" interface IForestOptions { - center: IGameForestChunk["center"]; - width: number; - height: number; + center: IGameForestChunk["center"] + width: number + height: number } export class Forest extends GameChunk implements IGameForestChunk { @@ -19,42 +19,42 @@ export class Forest extends GameChunk implements IGameForestChunk { width, height, center, - }); + }) - const treesToPrepare = Math.round((this.area.endX - this.area.startX) / 10); - console.log(`preparing ${treesToPrepare} trees`); - this.initTrees(treesToPrepare); - this.initStones(3); + const treesToPrepare = Math.round((this.area.endX - this.area.startX) / 10) + console.log(`preparing ${treesToPrepare} trees`) + this.initTrees(treesToPrepare) + this.initStones(3) } live() { - super.live(); + super.live() for (const obj of this.objects) { - void obj.live(); + void obj.live() } } initTrees(count: number) { for (let i = 0; i < count; i++) { - const point = this.getRandomPoint(); - const size = getRandomInRange(75, 90); + const point = this.getRandomPoint() + const size = getRandomInRange(75, 90) const tree = new Tree({ x: point.x, y: point.y, size, resource: 1, health: 20, - }); - this.objects.push(tree); + }) + this.objects.push(tree) } } initStones(count: number) { for (let i = 0; i < count; i++) { - const point = this.getRandomPoint(); - const stone = new Stone({ x: point.x, y: point.y, resource: 1 }); - this.objects.push(stone); + const point = this.getRandomPoint() + const stone = new Stone({ x: point.x, y: point.y, resource: 1 }) + this.objects.push(stone) } } } diff --git a/apps/api/src/game/chunks/gameChunk.ts b/apps/api/src/game/chunks/gameChunk.ts index 0a6eec9f..8b947674 100644 --- a/apps/api/src/game/chunks/gameChunk.ts +++ b/apps/api/src/game/chunks/gameChunk.ts @@ -1,66 +1,66 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import { type IGameChunk, getRandomInRange, -} from "../../../../../packages/api-sdk/src"; -import type { GameObject } from "../objects"; +} from "../../../../../packages/api-sdk/src" +import type { GameObject } from "../objects" interface IGameChunkOptions { - center: IGameChunk["center"]; - title: IGameChunk["title"]; - type: IGameChunk["type"]; - theme: IGameChunk["theme"]; - width: number; - height: number; + center: IGameChunk["center"] + title: IGameChunk["title"] + type: IGameChunk["type"] + theme: IGameChunk["theme"] + width: number + height: number } export class GameChunk implements IGameChunk { - public id: string; - public title: string; - public type: IGameChunk["type"]; - public theme: IGameChunk["theme"]; - public center!: IGameChunk["center"]; - public area!: IGameChunk["area"]; - public isVisibleOnClient = false; + public id: string + public title: string + public type: IGameChunk["type"] + public theme: IGameChunk["theme"] + public center!: IGameChunk["center"] + public area!: IGameChunk["area"] + public isVisibleOnClient = false - public needToSendDataToClient: boolean; - public objects: GameObject[] = []; + public needToSendDataToClient: boolean + public objects: GameObject[] = [] constructor({ - title, - type, - theme, - width, - height, - center - }: IGameChunkOptions) { - this.id = createId(); - this.center = center; - this.title = title; - this.type = type; - this.theme = theme; + title, + type, + theme, + width, + height, + center, + }: IGameChunkOptions) { + this.id = createId() + this.center = center + this.title = title + this.type = type + this.theme = theme - this.needToSendDataToClient = false; + this.needToSendDataToClient = false - this.initArea(width, height); + this.initArea(width, height) } private initArea(width: number, height: number) { - const halfWidth = Math.round(width / 2); - const halfHeight = Math.round(height / 2); + const halfWidth = Math.round(width / 2) + const halfHeight = Math.round(height / 2) this.area = { startX: this.center.x - halfWidth, endX: this.center.x + halfWidth, startY: this.center.y - halfHeight, endY: this.center.y + halfHeight, - }; + } } public live() { for (const obj of this.objects) { - obj.isVisibleOnClient = this.isVisibleOnClient; - obj.needToSendDataToClient = this.needToSendDataToClient; + obj.isVisibleOnClient = this.isVisibleOnClient + obj.needToSendDataToClient = this.needToSendDataToClient } } @@ -68,23 +68,23 @@ export class GameChunk implements IGameChunk { return { x: getRandomInRange(this.area.startX, this.area.endX), y: getRandomInRange(this.area.startY, this.area.endY), - }; + } } public getRandomOutPointOnRight() { return { x: this.area.endX, y: getRandomInRange(this.area.startY, this.area.endY), - }; + } } public checkIfPointIsInArea(point: { x: number; y: number }): boolean { if (point.x >= this.area.startX && point.x <= this.area.endX) { if (point.y >= this.area.startY && point.y <= this.area.endY) { - return true; + return true } } - return false; + return false } } diff --git a/apps/api/src/game/chunks/index.ts b/apps/api/src/game/chunks/index.ts index f43bdf87..f795be06 100644 --- a/apps/api/src/game/chunks/index.ts +++ b/apps/api/src/game/chunks/index.ts @@ -1,4 +1,4 @@ -export { Forest } from "./forest"; -export { GameChunk } from "./gameChunk"; -export { Village } from "./village"; +export { Forest } from "./forest" +export { GameChunk } from "./gameChunk" +export { Village } from "./village" export { LakeChunk } from "./lake" diff --git a/apps/api/src/game/chunks/lake.ts b/apps/api/src/game/chunks/lake.ts index 701dbb41..18990999 100644 --- a/apps/api/src/game/chunks/lake.ts +++ b/apps/api/src/game/chunks/lake.ts @@ -1,14 +1,14 @@ import { + type IGameLakeChunk, getRandomInRange, - IGameLakeChunk, -} from "../../../../../packages/api-sdk/src"; -import { Tree, Stone, Lake } from "../objects"; -import { GameChunk } from "./gameChunk"; +} from "../../../../../packages/api-sdk/src" +import { Lake, Stone, Tree } from "../objects" +import { GameChunk } from "./gameChunk" interface ILakeOptions { - center: IGameLakeChunk["center"]; - width: number; - height: number; + center: IGameLakeChunk["center"] + width: number + height: number } export class LakeChunk extends GameChunk implements IGameLakeChunk { @@ -19,49 +19,49 @@ export class LakeChunk extends GameChunk implements IGameLakeChunk { width, height, center, - }); + }) - const treesToPrepare = Math.round((this.area.endX - this.area.startX) / 30); - console.log(`preparing ${treesToPrepare} trees`); - this.initTrees(treesToPrepare); - this.initStones(3); - this.initLake(); + const treesToPrepare = Math.round((this.area.endX - this.area.startX) / 30) + console.log(`preparing ${treesToPrepare} trees`) + this.initTrees(treesToPrepare) + this.initStones(3) + this.initLake() } live() { - super.live(); + super.live() for (const obj of this.objects) { - void obj.live(); + void obj.live() } } initLake() { - const lake = new Lake({ x: this.center.x - 100, y: this.center.y + 400 }); - const lake2 = new Lake({ x: this.center.x - 600, y: this.center.y + 500 }); - this.objects.push(lake, lake2); + const lake = new Lake({ x: this.center.x - 100, y: this.center.y + 400 }) + const lake2 = new Lake({ x: this.center.x - 600, y: this.center.y + 500 }) + this.objects.push(lake, lake2) } initTrees(count: number) { for (let i = 0; i < count; i++) { - const point = this.getRandomPoint(); - const size = getRandomInRange(75, 90); + const point = this.getRandomPoint() + const size = getRandomInRange(75, 90) const tree = new Tree({ x: point.x, y: point.y, size, resource: 1, health: 20, - }); - this.objects.push(tree); + }) + this.objects.push(tree) } } initStones(count: number) { for (let i = 0; i < count; i++) { - const point = this.getRandomPoint(); - const stone = new Stone({ x: point.x, y: point.y, resource: 1 }); - this.objects.push(stone); + const point = this.getRandomPoint() + const stone = new Stone({ x: point.x, y: point.y, resource: 1 }) + this.objects.push(stone) } } } diff --git a/apps/api/src/game/chunks/village.ts b/apps/api/src/game/chunks/village.ts index c6c62359..c9824666 100644 --- a/apps/api/src/game/chunks/village.ts +++ b/apps/api/src/game/chunks/village.ts @@ -2,106 +2,106 @@ import { type IGameObjectFlag, type IGameVillageChunk, getRandomInRange, -} from "../../../../../packages/api-sdk/src"; -import { Flag, Stone, Tree } from "../objects"; -import { Campfire } from "../objects/buildings/campfire"; -import { WagonStop } from "../objects/buildings/wagonStop"; -import { Warehouse } from "../objects/buildings/warehouse"; -import { GameChunk } from "./gameChunk"; -import { VillageCourier, VillageFarmer } from "../objects/units"; +} from "../../../../../packages/api-sdk/src" +import { Flag, Stone, Tree } from "../objects" +import { Campfire } from "../objects/buildings/campfire" +import { WagonStop } from "../objects/buildings/wagonStop" +import { Warehouse } from "../objects/buildings/warehouse" +import { VillageCourier, VillageFarmer } from "../objects/units" +import { GameChunk } from "./gameChunk" interface IVillageOptions { - width: number; - height: number; - center: IGameVillageChunk["center"]; - theme: IGameVillageChunk["theme"]; + width: number + height: number + center: IGameVillageChunk["center"] + theme: IGameVillageChunk["theme"] } export class Village extends GameChunk implements IGameVillageChunk { constructor({ width, height, center, theme }: IVillageOptions) { - super({ title: "", type: "VILLAGE", theme, width, height, center }); + super({ title: "", type: "VILLAGE", theme, width, height, center }) - this.title = this.getRandomTitle(); + this.title = this.getRandomTitle() - this.initFlags("RESOURCE", 40); - this.initFlags("MOVEMENT", 30); - this.initTrees(20); - this.initStones(5); + this.initFlags("RESOURCE", 40) + this.initFlags("MOVEMENT", 30) + this.initTrees(20) + this.initStones(5) - this.initCourier(); - this.initFarmer(); - this.initBuildings(); + this.initCourier() + this.initFarmer() + this.initBuildings() } live() { - super.live(); + super.live() for (const obj of this.objects) { - void obj.live(); + void obj.live() } } initFlag(type: IGameObjectFlag["type"]) { - const randomPoint = this.getRandomPoint(); - this.objects.push(new Flag({ type, x: randomPoint.x, y: randomPoint.y })); + const randomPoint = this.getRandomPoint() + this.objects.push(new Flag({ type, x: randomPoint.x, y: randomPoint.y })) } initFlags(type: IGameObjectFlag["type"], count: number) { for (let i = 0; i < count; i++) { - this.initFlag(type); + this.initFlag(type) } } initTrees(count: number) { for (let i = 0; i < count; i++) { - const flag = this.getRandomEmptyResourceFlagInVillage(); + const flag = this.getRandomEmptyResourceFlagInVillage() if (flag) { - const size = getRandomInRange(75, 90); + const size = getRandomInRange(75, 90) const tree = new Tree({ x: flag.x, y: flag.y, size, resource: 1, health: 20, - variant: this.theme - }); - flag.target = tree; - this.objects.push(tree); + variant: this.theme, + }) + flag.target = tree + this.objects.push(tree) } } } initStones(count: number) { for (let i = 0; i < count; i++) { - const flag = this.getRandomEmptyResourceFlagInVillage(); + const flag = this.getRandomEmptyResourceFlagInVillage() if (flag) { - const stone = new Stone({ x: flag.x, y: flag.y, resource: 1 }); - flag.target = stone; - this.objects.push(stone); + const stone = new Stone({ x: flag.x, y: flag.y, resource: 1 }) + flag.target = stone + this.objects.push(stone) } } } initCourier() { - const randomPoint = this.getRandomPoint(); + const randomPoint = this.getRandomPoint() this.objects.push( new VillageCourier({ village: this, x: randomPoint.x, y: randomPoint.y, }), - ); + ) } initFarmer() { - const randomPoint = this.getRandomPoint(); + const randomPoint = this.getRandomPoint() this.objects.push( new VillageFarmer({ village: this, x: randomPoint.x, y: randomPoint.y, }), - ); + ) } initBuildings() { @@ -110,46 +110,46 @@ export class Village extends GameChunk implements IGameVillageChunk { x: this.center.x, y: this.center.y, }), - ); + ) this.objects.push( new Warehouse({ x: this.center.x + 300, y: this.center.y - 120, }), - ); + ) this.objects.push( new WagonStop({ x: this.center.x - 480, y: this.center.y + 220, }), - ); + ) } public getWagonStopPoint() { for (const object of this.objects) { if (object instanceof WagonStop) { - return { x: object.x, y: object.y }; + return { x: object.x, y: object.y } } } - return { x: 500, y: 500 }; + return { x: 500, y: 500 } } getRandomEmptyResourceFlagInVillage() { const flags = this.objects.filter( (f) => f instanceof Flag && f.type === "RESOURCE" && !f.target, - ); + ) return flags.length > 0 ? flags[Math.floor(Math.random() * flags.length)] - : undefined; + : undefined } getRandomMovementFlagInVillage() { const flags = this.objects.filter( (f) => f instanceof Flag && f.type === "MOVEMENT", - ); + ) return flags.length > 0 ? flags[Math.floor(Math.random() * flags.length)] - : undefined; + : undefined } getRandomTitle() { @@ -164,21 +164,21 @@ export class Village extends GameChunk implements IGameVillageChunk { "Магическая Долина", "Королевское Пристанище", "Призрачный Утес", - ]; - return titles[Math.floor(Math.random() * titles.length)]; + ] + return titles[Math.floor(Math.random() * titles.length)] } checkIfNeedToPlantTree() { const treesNow = this.objects.filter( (t) => t instanceof Tree && t.state !== "DESTROYED", - ); + ) if (treesNow.length < 40) { - return this.getRandomEmptyResourceFlagInVillage(); + return this.getRandomEmptyResourceFlagInVillage() } } plantNewTree(flag: Flag, tree: Tree) { - flag.target = tree; - this.objects.push(tree); + flag.target = tree + this.objects.push(tree) } } diff --git a/apps/api/src/game/common/event.ts b/apps/api/src/game/common/event.ts index ad210f67..01e74884 100644 --- a/apps/api/src/game/common/event.ts +++ b/apps/api/src/game/common/event.ts @@ -1,74 +1,74 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import { type GameSceneType, type IGameEvent, getDatePlusSeconds, -} from "../../../../../packages/api-sdk/src"; -import { sendMessage } from "../../websocket/websocket.server"; -import { Village } from "../chunks"; -import type { Game } from "../game"; +} from "../../../../../packages/api-sdk/src" +import { sendMessage } from "../../websocket/websocket.server" +import { Village } from "../chunks" +import type { Game } from "../game" interface IEventOptions { - game: Game; - title: string; - type: IGameEvent["type"]; - secondsToEnd: number; - scene?: GameSceneType; + game: Game + title: string + type: IGameEvent["type"] + secondsToEnd: number + scene?: GameSceneType } export class Event implements IGameEvent { - public id: string; - public title: string; - public type: IGameEvent["type"]; - public status: IGameEvent["status"]; - public scene?: GameSceneType; - public endsAt: Date; - public deletesAt: Date; + public id: string + public title: string + public type: IGameEvent["type"] + public status: IGameEvent["status"] + public scene?: GameSceneType + public endsAt: Date + public deletesAt: Date - public game: Game; + public game: Game constructor({ game, title, type, secondsToEnd, scene }: IEventOptions) { - this.game = game; + this.game = game - this.id = createId(); - this.title = title; - this.type = type; - this.scene = scene; - this.endsAt = getDatePlusSeconds(secondsToEnd); - this.deletesAt = getDatePlusSeconds(secondsToEnd + 30); - this.status = "STARTED"; + this.id = createId() + this.title = title + this.type = type + this.scene = scene + this.endsAt = getDatePlusSeconds(secondsToEnd) + this.deletesAt = getDatePlusSeconds(secondsToEnd + 30) + this.status = "STARTED" - sendMessage(type); + sendMessage(type) } public checkStatus() { if (this.endsAt.getTime() <= new Date().getTime()) { - this.status = "STOPPED"; + this.status = "STOPPED" } if (this.deletesAt.getTime() <= new Date().getTime()) { - this.status = "STOPPED"; + this.status = "STOPPED" } - return this.status; + return this.status } public handleEnding() { if (this.type === "SCENE_CHANGING_STARTED" && this.scene) { - this.game.initScene(this.scene); + this.game.initScene(this.scene) } if (this.type === "GROUP_FORM_STARTED" && this.scene) { - this.game.initScene(this.scene); + this.game.initScene(this.scene) } if (this.type === "RAID_STARTED") { - this.game.scene.stopRaid(); + this.game.scene.stopRaid() } if (this.type === "COUNTDOWN_NEXT_WAVE_STARTED") { - console.log("Next wave!"); + console.log("Next wave!") } if (this.type === "CREATING_NEW_ADVENTURE_STARTED") { - const village = this.game.scene.chunkNow; + const village = this.game.scene.chunkNow if (village instanceof Village) { - this.game.scene.generateAdventure(village); + this.game.scene.generateAdventure(village) } } } diff --git a/apps/api/src/game/common/group.ts b/apps/api/src/game/common/group.ts index d8c076ad..c53c8ef9 100644 --- a/apps/api/src/game/common/group.ts +++ b/apps/api/src/game/common/group.ts @@ -1,42 +1,42 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import type { GameSceneType, IGameGroup, IGameObjectPlayer, -} from "../../../../../packages/api-sdk/src"; +} from "../../../../../packages/api-sdk/src" interface IGroupOptions { - creator: IGameObjectPlayer; - target: GameSceneType; + creator: IGameObjectPlayer + target: GameSceneType } export class Group implements IGameGroup { - id: string; - players: IGameObjectPlayer[] = []; - target: GameSceneType; + id: string + players: IGameObjectPlayer[] = [] + target: GameSceneType constructor({ creator, target }: IGroupOptions) { - this.id = createId(); + this.id = createId() - this.join(creator); - this.target = target; + this.join(creator) + this.target = target } join(player: IGameObjectPlayer): boolean { - const check = this.findPlayer(player.id); + const check = this.findPlayer(player.id) if (check) { - return false; + return false } - this.players.push(player); - return true; + this.players.push(player) + return true } findPlayer(id: string) { - return this.players.find((p) => p.id === id); + return this.players.find((p) => p.id === id) } disband() { - this.players = []; + this.players = [] } } diff --git a/apps/api/src/game/common/index.ts b/apps/api/src/game/common/index.ts index a4fb7280..ce8cc0b2 100644 --- a/apps/api/src/game/common/index.ts +++ b/apps/api/src/game/common/index.ts @@ -1,5 +1,5 @@ -export { Inventory } from "./inventory"; -export { Skill } from "./skill"; -export { Event } from "./event"; -export { Group } from "./group"; -export { Route } from "./route"; +export { Inventory } from "./inventory" +export { Skill } from "./skill" +export { Event } from "./event" +export { Group } from "./group" +export { Route } from "./route" diff --git a/apps/api/src/game/common/inventory.ts b/apps/api/src/game/common/inventory.ts index 364bff6d..c5560f9a 100644 --- a/apps/api/src/game/common/inventory.ts +++ b/apps/api/src/game/common/inventory.ts @@ -1,116 +1,116 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import type { IGameInventory, InventoryItem, ItemType, -} from "../../../../../packages/api-sdk/src"; -import { db } from "../../db/db.client"; +} from "../../../../../packages/api-sdk/src" +import { db } from "../../db/db.client" interface IInventoryOptions { - objectId: string; - id: string; - saveInDb: boolean; + objectId: string + id: string + saveInDb: boolean } export class Inventory implements IGameInventory { - public id: string; - public objectId: string; - public items: InventoryItem[] = []; - public saveInDb: boolean; + public id: string + public objectId: string + public items: InventoryItem[] = [] + public saveInDb: boolean constructor({ id, objectId, saveInDb }: IInventoryOptions) { - this.id = id; - this.objectId = objectId; - this.saveInDb = saveInDb; + this.id = id + this.objectId = objectId + this.saveInDb = saveInDb } public async init() { - await this.updateFromDB(); + await this.updateFromDB() } public transferItemWithType(type: ItemType) { - return this.items.find((i) => i.type === type); + return this.items.find((i) => i.type === type) } public destroyItem(id: string) { - const itemIndex = this.items.findIndex((i) => i.id === id); + const itemIndex = this.items.findIndex((i) => i.id === id) if (itemIndex < 0) { - return; + return } - this.items.splice(itemIndex, 1); + this.items.splice(itemIndex, 1) } public async reduceOrDestroyItem(type: ItemType, amount: number) { - const item = this.checkIfAlreadyHaveItem(type); + const item = this.checkIfAlreadyHaveItem(type) if (!item) { - return false; + return false } if (amount > item.amount) { - return false; + return false } if (amount === item.amount) { - this.destroyItem(item.id); - return true; + this.destroyItem(item.id) + return true } - item.amount -= amount; - return true; + item.amount -= amount + return true } public async addOrCreateItem(type: ItemType, amount: number) { if (this.saveInDb) { - return this.addOrCreateItemInDB(type, amount); + return this.addOrCreateItemInDB(type, amount) } - const item = this.checkIfAlreadyHaveItem(type); + const item = this.checkIfAlreadyHaveItem(type) if (!item) { - this.createItem(type, amount); - return; + this.createItem(type, amount) + return } - item.amount += amount; + item.amount += amount } async addOrCreateItemInDB(type: ItemType, amount: number) { - const item = await this.checkIfAlreadyHaveItemInDB(this.id, type); + const item = await this.checkIfAlreadyHaveItemInDB(this.id, type) if (!item) { - await this.createItemInDB(this.id, type, amount); - await this.updateFromDB(); - return; + await this.createItemInDB(this.id, type, amount) + await this.updateFromDB() + return } - await this.incrementAmountOfItemInDB(item.id, amount); - await this.updateFromDB(); + await this.incrementAmountOfItemInDB(item.id, amount) + await this.updateFromDB() } async destroyItemInDB(id: string) { await db.inventoryItem.delete({ where: { id }, - }); - await this.updateFromDB(); + }) + await this.updateFromDB() } public tryGetItemInDB(type: ItemType) { - return this.checkIfAlreadyHaveItemInDB(this.id, type); + return this.checkIfAlreadyHaveItemInDB(this.id, type) } async checkAndBreakItem(item: InventoryItem, decrement: number) { if (item.durability <= decrement) { - await this.destroyItemInDB(item.id); - await this.updateFromDB(); - return; + await this.destroyItemInDB(item.id) + await this.updateFromDB() + return } - item.durability -= decrement; + item.durability -= decrement await db.inventoryItem.update({ where: { id: item.id }, data: { durability: { decrement }, }, - }); + }) } createItemInDB(inventoryId: string, type: ItemType, amount: number) { @@ -121,7 +121,7 @@ export class Inventory implements IGameInventory { inventoryId, amount, }, - }); + }) } incrementAmountOfItemInDB(id: string, amount: number) { @@ -132,17 +132,17 @@ export class Inventory implements IGameInventory { increment: amount, }, }, - }); + }) } checkIfAlreadyHaveItemInDB(inventoryId: string, type: ItemType) { return db.inventoryItem.findFirst({ where: { inventoryId, type }, - }); + }) } checkIfAlreadyHaveItem(type: ItemType) { - return this.items.find((item) => item.type === type); + return this.items.find((item) => item.type === type) } createItem(type: ItemType, amount: number) { @@ -154,14 +154,14 @@ export class Inventory implements IGameInventory { amount, durability: 100, inventoryId: "", - }; - this.items.push(item); + } + this.items.push(item) } async updateFromDB() { const items = await db.inventoryItem.findMany({ where: { inventoryId: this.id }, - }); - this.items = items as InventoryItem[]; + }) + this.items = items as InventoryItem[] } } diff --git a/apps/api/src/game/common/route.ts b/apps/api/src/game/common/route.ts index 811ec5a7..96b4d8f7 100644 --- a/apps/api/src/game/common/route.ts +++ b/apps/api/src/game/common/route.ts @@ -1,28 +1,28 @@ import type { IGameChunk, IGameRoute, -} from "../../../../../packages/api-sdk/src"; -import { Flag } from "../objects"; +} from "../../../../../packages/api-sdk/src" +import { Flag } from "../objects" interface IRoutePoint { - x: number; - y: number; + x: number + y: number } interface IRouteArea { - startX: number; - endX: number; - startY: number; - endY: number; + startX: number + endX: number + startY: number + endY: number } export class Route implements IGameRoute { - public startPoint!: IRoutePoint; - public endPoint!: IRoutePoint; - public chunks: IGameChunk[] = []; + public startPoint!: IRoutePoint + public endPoint!: IRoutePoint + public chunks: IGameChunk[] = [] - public flags: Flag[] = []; - public areas: IRouteArea[] = []; + public flags: Flag[] = [] + public areas: IRouteArea[] = [] public addChunk(chunk: IGameChunk) { this.chunks.push({ @@ -32,63 +32,63 @@ export class Route implements IGameRoute { center: chunk.center, area: chunk.area, isVisibleOnClient: chunk.isVisibleOnClient, - }); + }) } public setEndPoint({ x, y }: IRoutePoint) { - this.endPoint = { x, y }; + this.endPoint = { x, y } } public addFlag({ x, y }: IRoutePoint) { - const movementFlag = new Flag({ type: "WAGON_MOVEMENT", x, y }); + const movementFlag = new Flag({ type: "WAGON_MOVEMENT", x, y }) - const prevFlag = this.flags[this.flags.length - 1]; + const prevFlag = this.flags[this.flags.length - 1] if (prevFlag) { - this.initArea(prevFlag, movementFlag); + this.initArea(prevFlag, movementFlag) } - this.flags.push(movementFlag); + this.flags.push(movementFlag) } public addGlobalFlag(end: IRoutePoint) { - const prevGlobalFlag = this.flags[this.flags.length - 1]; + const prevGlobalFlag = this.flags[this.flags.length - 1] if (!prevGlobalFlag) { - return this.addFlag(end); + return this.addFlag(end) } - this.generatePath({ x: prevGlobalFlag.x, y: prevGlobalFlag.y }, end); - this.addFlag({ x: end.x, y: end.y }); + this.generatePath({ x: prevGlobalFlag.x, y: prevGlobalFlag.y }, end) + this.addFlag({ x: end.x, y: end.y }) } public getNextFlag() { - return this.flags[0]; + return this.flags[0] } public removeFlag(flag: Flag) { - const index = this.flags.findIndex((f) => f.id === flag.id); + const index = this.flags.findIndex((f) => f.id === flag.id) if (index >= 0) { - this.flags.splice(index, 1); + this.flags.splice(index, 1) } } public initArea(flag1: Flag, flag2: Flag) { - const offset = 150; - const halfOffset = offset / 2; + const offset = 150 + const halfOffset = offset / 2 - const startX = Math.min(flag1.x, flag2.x) - offset; - const endX = Math.max(flag1.x, flag2.x) + offset; + const startX = Math.min(flag1.x, flag2.x) - offset + const endX = Math.max(flag1.x, flag2.x) + offset - const startY = Math.min(flag1.y, flag2.y) - halfOffset; - const endY = Math.max(flag1.y, flag2.y) + halfOffset; + const startY = Math.min(flag1.y, flag2.y) - halfOffset + const endY = Math.max(flag1.y, flag2.y) + halfOffset const area = { startX, endX, startY, endY, - }; + } - this.areas.push(area); + this.areas.push(area) } private isInArea(area: IRouteArea, point: IRoutePoint) { @@ -97,49 +97,49 @@ export class Route implements IGameRoute { point.x < area.endX && area.startY < point.y && point.y < area.endY - ); + ) } public checkIfPointIsOnWagonPath(point: IRoutePoint) { for (const area of this.areas) { if (this.isInArea(area, point)) { - return true; + return true } } - return false; + return false } generatePath(start: IRoutePoint, end: IRoutePoint) { - const pathDistance = Route.getDistanceBetween2Points(start, end); - console.log("path", pathDistance); + const pathDistance = Route.getDistanceBetween2Points(start, end) + console.log("path", pathDistance) - const pointsCount = Math.round(pathDistance / 150) + 1; - console.log("points between", pointsCount); + const pointsCount = Math.round(pathDistance / 150) + 1 + console.log("points between", pointsCount) - const stepX = Math.round((end.x - start.x) / pointsCount); - const stepY = Math.round((end.y - start.y) / pointsCount); + const stepX = Math.round((end.x - start.x) / pointsCount) + const stepY = Math.round((end.y - start.y) / pointsCount) - let nowX = start.x; - let nowY = start.y; + let nowX = start.x + let nowY = start.y for (let i = 0; i < pointsCount; i++) { - nowX += stepX; - nowY += stepY; - this.addFlag({ x: nowX, y: nowY }); + nowX += stepX + nowY += stepY + this.addFlag({ x: nowX, y: nowY }) } } public static getDistanceBetween2Points( point1: { - x: number; - y: number; + x: number + y: number }, point2: { - x: number; - y: number; + x: number + y: number }, ) { - return Math.sqrt((point1.x - point2.x) ** 2 + (point1.y - point2.y) ** 2); + return Math.sqrt((point1.x - point2.x) ** 2 + (point1.y - point2.y) ** 2) } } diff --git a/apps/api/src/game/common/skill.ts b/apps/api/src/game/common/skill.ts index b251f6d9..1d522858 100644 --- a/apps/api/src/game/common/skill.ts +++ b/apps/api/src/game/common/skill.ts @@ -1,45 +1,45 @@ -import { createId } from "@paralleldrive/cuid2"; -import type { IGameSkill } from "../../../../../packages/api-sdk/src"; -import { db } from "../../db/db.client"; +import { createId } from "@paralleldrive/cuid2" +import type { IGameSkill } from "../../../../../packages/api-sdk/src" +import { db } from "../../db/db.client" interface ISkillOptions { - id: string; + id: string } export class Skill implements IGameSkill { - public id: string; - public objectId: string | null = null; - public type!: IGameSkill["type"]; + public id: string + public objectId: string | null = null + public type!: IGameSkill["type"] - public lvl = 0; - public xp = 0; - public xpNextLvl = 0; + public lvl = 0 + public xp = 0 + public xpNextLvl = 0 constructor({ id }: ISkillOptions) { - this.id = id; + this.id = id } public async init() { - await this.readFromDB(); + await this.readFromDB() } public async addXp(increment = 1) { - this.xp += increment; + this.xp += increment if (this.xp >= this.xpNextLvl) { - await this.lvlUpInDB(); - await this.init(); - return; + await this.lvlUpInDB() + await this.init() + return } return db.skill.update({ where: { id: this.id }, data: { xp: { increment } }, - }); + }) } public lvlUpInDB() { - const xpNextLvl = Math.floor(this.xpNextLvl * 1.5); + const xpNextLvl = Math.floor(this.xpNextLvl * 1.5) return db.skill.update({ where: { id: this.id }, data: { @@ -47,28 +47,28 @@ export class Skill implements IGameSkill { xp: 0, xpNextLvl, }, - }); + }) } async readFromDB() { const skill = await db.skill.findUnique({ where: { id: this.id }, - }); + }) if (!skill) { - return; + return } - this.objectId = skill.objectId; - this.type = skill.type as IGameSkill["type"]; - this.lvl = skill.lvl; - this.xp = skill.xp; - this.xpNextLvl = skill.xpNextLvl; + this.objectId = skill.objectId + this.type = skill.type as IGameSkill["type"] + this.lvl = skill.lvl + this.xp = skill.xp + this.xpNextLvl = skill.xpNextLvl } public static async findAllInDB(objectId: string) { return db.skill.findMany({ where: { objectId }, - }); + }) } public static createInDB(objectId: string, type: IGameSkill["type"]) { @@ -78,6 +78,6 @@ export class Skill implements IGameSkill { objectId, type, }, - }); + }) } } diff --git a/apps/api/src/game/game.ts b/apps/api/src/game/game.ts index cdf8b3c7..9769f467 100644 --- a/apps/api/src/game/game.ts +++ b/apps/api/src/game/game.ts @@ -1,38 +1,38 @@ import type { GameSceneType, IGameSceneAction, -} from "../../../../packages/api-sdk/src"; -import { DBRepository } from "../db/db.repository"; -import { sendMessage } from "../websocket/websocket.server"; -import type { Group } from "./common"; +} from "../../../../packages/api-sdk/src" +import { DBRepository } from "../db/db.repository" +import { sendMessage } from "../websocket/websocket.server" +import type { Group } from "./common" import { DefenceScene, type GameScene, MovingScene, VillageScene, -} from "./scenes"; +} from "./scenes" interface HandleChatCommandOptions { - action: IGameSceneAction; - userId: string; // Twitch - userName: string; // Twitch - viewerCount?: number; - params?: string[]; + action: IGameSceneAction + userId: string // Twitch + userName: string // Twitch + viewerCount?: number + params?: string[] } interface HandleChatCommandResponse { - ok: boolean; - message: string | null; + ok: boolean + message: string | null } export class Game { - public repository: DBRepository; - public scene!: GameScene; + public repository: DBRepository + public scene!: GameScene constructor() { - this.repository = new DBRepository(); + this.repository = new DBRepository() - this.initScene("MOVING"); + this.initScene("MOVING") } public async handleChatCommand({ @@ -42,45 +42,45 @@ export class Game { viewerCount, params, }: HandleChatCommandOptions): Promise { - const player = await this.repository.findOrCreatePlayer(userId, userName); + const player = await this.repository.findOrCreatePlayer(userId, userName) if (action === "START_RAID") { // Raid must be in all rooms! - return this.scene.startRaidAction(viewerCount); + return this.scene.startRaidAction(viewerCount) } - return this.scene.handleAction(action, player.id, params); + return this.scene.handleAction(action, player.id, params) } public initScene(scene: GameSceneType) { - const { group } = this.prepareSceneBeforeChange(); + const { group } = this.prepareSceneBeforeChange() if (scene === "MOVING") { - this.scene = new MovingScene({ game: this, group: undefined }); - return; + this.scene = new MovingScene({ game: this, group: undefined }) + return } if (scene === "VILLAGE") { - this.scene = new VillageScene({ game: this, group: undefined }); - return; + this.scene = new VillageScene({ game: this, group: undefined }) + return } if (scene === "DEFENCE") { - this.scene = new DefenceScene({ game: this, group }); - return; + this.scene = new DefenceScene({ game: this, group }) + return } } public prepareSceneBeforeChange() { - let group: Group | undefined; + let group: Group | undefined if (this.scene?.group) { - group = this.scene.group; + group = this.scene.group } if (this.scene) { - this.scene.destroy(); + this.scene.destroy() } - sendMessage("SCENE_CHANGED"); + sendMessage("SCENE_CHANGED") return { group, - }; + } } } diff --git a/apps/api/src/game/objects/buildings/building.ts b/apps/api/src/game/objects/buildings/building.ts index 43003773..0cc8cd2c 100644 --- a/apps/api/src/game/objects/buildings/building.ts +++ b/apps/api/src/game/objects/buildings/building.ts @@ -1,34 +1,34 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import type { IGameObjectBuilding, IGameObjectBuildingType, -} from "../../../../../../packages/api-sdk/src"; -import { Inventory } from "../../common"; -import { GameObject } from "../gameObject"; +} from "../../../../../../packages/api-sdk/src" +import { Inventory } from "../../common" +import { GameObject } from "../gameObject" interface IBuildingOptions { - entity: IGameObjectBuildingType; - x: number; - y: number; + entity: IGameObjectBuildingType + x: number + y: number } export class Building extends GameObject implements IGameObjectBuilding { - public inventory!: Inventory; + public inventory!: Inventory constructor({ entity, x, y }: IBuildingOptions) { - const finalId = createId(); + const finalId = createId() - super({ id: finalId, x, y, entity }); + super({ id: finalId, x, y, entity }) - this.initInventory(); + this.initInventory() } live() { - this.handleChange(); + this.handleChange() } handleChange() { - this.sendMessageObjectUpdated(); + this.sendMessageObjectUpdated() } public initInventory() { @@ -36,6 +36,6 @@ export class Building extends GameObject implements IGameObjectBuilding { objectId: this.id, id: createId(), saveInDb: false, - }); + }) } } diff --git a/apps/api/src/game/objects/buildings/campfire.ts b/apps/api/src/game/objects/buildings/campfire.ts index e27b625d..865d8699 100644 --- a/apps/api/src/game/objects/buildings/campfire.ts +++ b/apps/api/src/game/objects/buildings/campfire.ts @@ -1,13 +1,13 @@ -import type { IGameBuildingCampfire } from "../../../../../../packages/api-sdk/src"; -import { Building } from "./building"; +import type { IGameBuildingCampfire } from "../../../../../../packages/api-sdk/src" +import { Building } from "./building" interface ICampfireOptions { - x: number; - y: number; + x: number + y: number } export class Campfire extends Building implements IGameBuildingCampfire { constructor({ x, y }: ICampfireOptions) { - super({ entity: "CAMPFIRE", x, y }); + super({ entity: "CAMPFIRE", x, y }) } } diff --git a/apps/api/src/game/objects/buildings/wagonStop.ts b/apps/api/src/game/objects/buildings/wagonStop.ts index 90fe5807..61f1635a 100644 --- a/apps/api/src/game/objects/buildings/wagonStop.ts +++ b/apps/api/src/game/objects/buildings/wagonStop.ts @@ -1,13 +1,13 @@ -import type { IGameBuildingWagonStop } from "../../../../../../packages/api-sdk/src"; -import { Building } from "./building"; +import type { IGameBuildingWagonStop } from "../../../../../../packages/api-sdk/src" +import { Building } from "./building" interface IWagonStopOptions { - x: number; - y: number; + x: number + y: number } export class WagonStop extends Building implements IGameBuildingWagonStop { constructor({ x, y }: IWagonStopOptions) { - super({ entity: "WAGON_STOP", x, y }); + super({ entity: "WAGON_STOP", x, y }) } } diff --git a/apps/api/src/game/objects/buildings/warehouse.ts b/apps/api/src/game/objects/buildings/warehouse.ts index 9eab8964..71d7ff47 100644 --- a/apps/api/src/game/objects/buildings/warehouse.ts +++ b/apps/api/src/game/objects/buildings/warehouse.ts @@ -1,13 +1,13 @@ -import type { IGameBuildingWarehouse } from "../../../../../../packages/api-sdk/src"; -import { Building } from "./building"; +import type { IGameBuildingWarehouse } from "../../../../../../packages/api-sdk/src" +import { Building } from "./building" interface IWarehouseOptions { - x: number; - y: number; + x: number + y: number } export class Warehouse extends Building implements IGameBuildingWarehouse { constructor({ x, y }: IWarehouseOptions) { - super({ entity: "WAREHOUSE", x, y }); + super({ entity: "WAREHOUSE", x, y }) } } diff --git a/apps/api/src/game/objects/flag.ts b/apps/api/src/game/objects/flag.ts index 0a45e4f4..0c430ec6 100644 --- a/apps/api/src/game/objects/flag.ts +++ b/apps/api/src/game/objects/flag.ts @@ -1,54 +1,54 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import { type IGameObjectFlag, getRandomInRange, -} from "../../../../../packages/api-sdk/src"; -import { MAX_X, MAX_Y, MIN_X, MIN_Y } from "../../config"; -import { GameObject } from "./gameObject"; +} from "../../../../../packages/api-sdk/src" +import { MAX_X, MAX_Y, MIN_X, MIN_Y } from "../../config" +import { GameObject } from "./gameObject" interface IFlagOptions { - x?: number; - y?: number; - id?: string; - type: IGameObjectFlag["type"]; - offsetX?: number; - offsetY?: number; + x?: number + y?: number + id?: string + type: IGameObjectFlag["type"] + offsetX?: number + offsetY?: number } export class Flag extends GameObject implements IGameObjectFlag { - public type: IGameObjectFlag["type"]; + public type: IGameObjectFlag["type"] - public offsetX: number; - public offsetY: number; + public offsetX: number + public offsetY: number constructor({ x, y, id, type, offsetX, offsetY }: IFlagOptions) { - const finalId = id ?? createId(); - const finalX = x ?? getRandomInRange(MIN_X, MAX_X); - const finalY = y ?? getRandomInRange(MIN_Y, MAX_Y); + const finalId = id ?? createId() + const finalX = x ?? getRandomInRange(MIN_X, MAX_X) + const finalY = y ?? getRandomInRange(MIN_Y, MAX_Y) - super({ id: finalId, x: finalX, y: finalY, entity: "FLAG" }); + super({ id: finalId, x: finalX, y: finalY, entity: "FLAG" }) - this.type = type; - this.offsetX = offsetX ?? 0; - this.offsetY = offsetY ?? 0; + this.type = type + this.offsetX = offsetX ?? 0 + this.offsetY = offsetY ?? 0 } live() { if (this.target && this.target.state === "DESTROYED") { - this.removeTarget(); + this.removeTarget() } - const random = getRandomInRange(1, 60); + const random = getRandomInRange(1, 60) if (random <= 1) { - this.handleChange(); + this.handleChange() } } handleChange() { - this.sendMessageObjectUpdated(); + this.sendMessageObjectUpdated() } removeTarget() { - this.target = undefined; + this.target = undefined } } diff --git a/apps/api/src/game/objects/gameObject.ts b/apps/api/src/game/objects/gameObject.ts index e3ef5cbd..2d6de593 100644 --- a/apps/api/src/game/objects/gameObject.ts +++ b/apps/api/src/game/objects/gameObject.ts @@ -2,129 +2,127 @@ import type { IGameObject, IGameObjectDirection, IGameObjectState, -} from "../../../../../packages/api-sdk/src"; -import { sendMessage } from "../../websocket/websocket.server"; +} from "../../../../../packages/api-sdk/src" +import { sendMessage } from "../../websocket/websocket.server" interface IGameObjectOptions { - id: string; - x: number; - y: number; - entity: IGameObject["entity"]; - isVisibleOnClient?: boolean; + id: string + x: number + y: number + entity: IGameObject["entity"] + isVisibleOnClient?: boolean } export class GameObject implements IGameObject { - public id: string; - public x: number; - public y: number; - public health = 100; - public isVisibleOnClient: boolean; - public entity: IGameObject["entity"]; - public direction: IGameObjectDirection = "RIGHT"; - public state: IGameObjectState = "IDLE"; - public target: IGameObject | undefined; - - public needToSendDataToClient: boolean; - public isOnWagonPath = false; + public id: string + public x: number + public y: number + public health = 100 + public isVisibleOnClient: boolean + public entity: IGameObject["entity"] + public direction: IGameObjectDirection = "RIGHT" + public state: IGameObjectState = "IDLE" + public target: IGameObject | undefined + + public needToSendDataToClient: boolean + public isOnWagonPath = false constructor({ id, x, y, entity, isVisibleOnClient }: IGameObjectOptions) { - this.id = id; - this.x = x; - this.y = y; - this.entity = entity; - this.isVisibleOnClient = isVisibleOnClient ?? false; + this.id = id + this.x = x + this.y = y + this.entity = entity + this.isVisibleOnClient = isVisibleOnClient ?? false - this.needToSendDataToClient = false; + this.needToSendDataToClient = false } - live(): void { - } + live(): void {} move(speed: number, minDistance?: number) { - const isOnTarget = this.checkIfIsOnTarget(minDistance); + const isOnTarget = this.checkIfIsOnTarget(minDistance) if (isOnTarget) { - this.stop(); - return false; + this.stop() + return false } if (!this.target || !this.target.x || !this.target.y) { - this.stop(); - return false; + this.stop() + return false } - const distanceToX = this.getDistanceToTargetX(); - const distanceToY = this.getDistanceToTargetY(); + const distanceToX = this.getDistanceToTargetX() + const distanceToY = this.getDistanceToTargetY() // Fix diagonal speed - const finalSpeed = - distanceToX > 0 && distanceToY > 0 ? speed * 0.75 : speed; + const finalSpeed = distanceToX > 0 && distanceToY > 0 ? speed * 0.75 : speed - this.moveX(finalSpeed > distanceToX ? distanceToX : finalSpeed); - this.moveY(finalSpeed > distanceToY ? distanceToY : finalSpeed); - return true; + this.moveX(finalSpeed > distanceToX ? distanceToX : finalSpeed) + this.moveY(finalSpeed > distanceToY ? distanceToY : finalSpeed) + return true } moveX(speed: number) { if (!this.target?.x || this.target.x === this.x) { - return; + return } if (this.x < this.target.x) { - this.direction = "RIGHT"; - this.x += speed; + this.direction = "RIGHT" + this.x += speed } if (this.x > this.target.x) { - this.x -= speed; - this.direction = "LEFT"; + this.x -= speed + this.direction = "LEFT" } } moveY(speed: number) { if (!this.target?.y || this.target.y === this.y) { - return; + return } if (this.y < this.target.y) { - this.y += speed; + this.y += speed } if (this.y > this.target.y) { - this.y -= speed; + this.y -= speed } } stop() { - this.state = "IDLE"; + this.state = "IDLE" } checkIfIsOnTarget(minDistance = 1) { return ( this.getDistanceToTargetX() + this.getDistanceToTargetY() <= minDistance - ); + ) } getDistanceToTargetX() { if (!this.target?.x) { - return 0; + return 0 } - return Math.abs(this.target.x - this.x); + return Math.abs(this.target.x - this.x) } getDistanceToTargetY() { if (!this.target?.y) { - return 0; + return 0 } - return Math.abs(this.target.y - this.y); + return Math.abs(this.target.y - this.y) } public setTarget(target: IGameObject) { - this.target = target; - this.state = "MOVING"; + this.target = target + this.state = "MOVING" } public sendMessageObjectUpdated(object: Partial = this) { if (!this.needToSendDataToClient) { - return; + return } - sendMessage("OBJECT_UPDATED", object); + sendMessage("OBJECT_UPDATED", object) } } diff --git a/apps/api/src/game/objects/index.ts b/apps/api/src/game/objects/index.ts index 4bf57e0d..a77cace3 100644 --- a/apps/api/src/game/objects/index.ts +++ b/apps/api/src/game/objects/index.ts @@ -1,9 +1,9 @@ -export { GameObject } from "./gameObject"; -export { Rabbit } from "./rabbit"; -export { Wolf } from "./wolf"; -export { Tree } from "./tree"; -export { Stone } from "./stone"; -export { Flag } from "./flag"; -export { Wagon } from "./wagon"; +export { GameObject } from "./gameObject" +export { Rabbit } from "./rabbit" +export { Wolf } from "./wolf" +export { Tree } from "./tree" +export { Stone } from "./stone" +export { Flag } from "./flag" +export { Wagon } from "./wagon" export { Lake } from "./lake" export { Water } from "./water" diff --git a/apps/api/src/game/objects/lake.ts b/apps/api/src/game/objects/lake.ts index 3782c77a..e729672a 100644 --- a/apps/api/src/game/objects/lake.ts +++ b/apps/api/src/game/objects/lake.ts @@ -1,80 +1,80 @@ -import { GameObject } from "./gameObject"; +import { createId } from "@paralleldrive/cuid2" import { - IGameObjectLake, - getRandomInRange -} from "../../../../../packages/api-sdk/src"; -import { createId } from "@paralleldrive/cuid2"; -import { Water } from "./water"; + type IGameObjectLake, + getRandomInRange, +} from "../../../../../packages/api-sdk/src" +import { GameObject } from "./gameObject" +import { Water } from "./water" interface ILakeOptions { - x: number; - y: number; - id?: string; + x: number + y: number + id?: string } export class Lake extends GameObject implements IGameObjectLake { - public water: Water[] = []; + public water: Water[] = [] constructor({ id, x, y }: ILakeOptions) { - const objectId = id ?? createId(); + const objectId = id ?? createId() - super({ id: objectId, x, y, entity: "LAKE" }); + super({ id: objectId, x, y, entity: "LAKE" }) //this.init(320, 320); - this.generate(13); + this.generate(13) } generate(r: number) { for (let y = r; y >= -r; --y) { for (let x = -r; x <= r; x++) { - const value = x ** 2 + y ** 2; + const value = x ** 2 + y ** 2 if (value < r ** 2) { - this.draw(x, y); + this.draw(x, y) } } } } draw(x: number, y: number) { - const water = new Water({ x: x * 32, y: y * 32 }); - this.water.push(water); + const water = new Water({ x: x * 32, y: y * 32 }) + this.water.push(water) } init(width: number, height: number) { - const gridX = Math.ceil(width / 32); - const gridY = Math.floor(height / 32); + const gridX = Math.ceil(width / 32) + const gridY = Math.floor(height / 32) - console.log(gridX, gridY); + console.log(gridX, gridY) - const center = { x: Math.round(width / 2), y: Math.round(height / 2) }; + const center = { x: Math.round(width / 2), y: Math.round(height / 2) } for (let i = 0; i < gridX; i++) { for (let j = 0; j < gridY; j++) { - let x = i * 32; - let y = j * 32; + const x = i * 32 + const y = j * 32 // if (x <= center.x && y <= center.y) { // continue // } - const water = new Water({ x, y }); - this.water.push(water); + const water = new Water({ x, y }) + this.water.push(water) } } } live() { if (this.state === "IDLE") { - const random = getRandomInRange(1, 600); + const random = getRandomInRange(1, 600) if (random <= 1) { - this.handleChange(); + this.handleChange() } - return; + return } } handleChange() { - this.sendMessageObjectUpdated(); + this.sendMessageObjectUpdated() } -} \ No newline at end of file +} diff --git a/apps/api/src/game/objects/rabbit.ts b/apps/api/src/game/objects/rabbit.ts index 058eb5ac..e225c1de 100644 --- a/apps/api/src/game/objects/rabbit.ts +++ b/apps/api/src/game/objects/rabbit.ts @@ -1,39 +1,39 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import { type IGameObjectRabbit, getRandomInRange, -} from "../../../../../packages/api-sdk/src"; -import { MAX_X, MAX_Y, MIN_X, MIN_Y } from "../../config"; -import { GameObject } from "./gameObject"; +} from "../../../../../packages/api-sdk/src" +import { MAX_X, MAX_Y, MIN_X, MIN_Y } from "../../config" +import { GameObject } from "./gameObject" export class Rabbit extends GameObject implements IGameObjectRabbit { constructor() { - const id = createId(); - const x = getRandomInRange(MIN_X, MAX_X); - const y = getRandomInRange(MIN_Y, MAX_Y); + const id = createId() + const x = getRandomInRange(MIN_X, MAX_X) + const y = getRandomInRange(MIN_Y, MAX_Y) - super({ id, x, y, entity: "RABBIT" }); + super({ id, x, y, entity: "RABBIT" }) } live() { if (this.state === "IDLE") { - return; + return } if (this.state === "MOVING") { - const isMoving = this.move(1); - this.handleChange(); + const isMoving = this.move(1) + this.handleChange() if (!isMoving) { - this.state = "IDLE"; - return; + this.state = "IDLE" + return } - return; + return } } handleChange() { - this.sendMessageObjectUpdated(); + this.sendMessageObjectUpdated() } } diff --git a/apps/api/src/game/objects/stone.ts b/apps/api/src/game/objects/stone.ts index 6a341ede..7a8edd36 100644 --- a/apps/api/src/game/objects/stone.ts +++ b/apps/api/src/game/objects/stone.ts @@ -1,79 +1,79 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import { type IGameObjectStone, getRandomInRange, -} from "../../../../../packages/api-sdk/src"; -import { GameObject } from "./gameObject"; +} from "../../../../../packages/api-sdk/src" +import { GameObject } from "./gameObject" interface IStoneOptions { - id?: string; - x: number; - y: number; - resource?: number; - size?: number; - health?: number; + id?: string + x: number + y: number + resource?: number + size?: number + health?: number } export class Stone extends GameObject implements IGameObjectStone { - public type: IGameObjectStone["type"] = "1"; - public resource = 0; - public size = 100; - public health = 100; - public isReserved = false; + public type: IGameObjectStone["type"] = "1" + public resource = 0 + public size = 100 + public health = 100 + public isReserved = false constructor({ id, x, y, resource }: IStoneOptions) { - const objectId = id ?? createId(); + const objectId = id ?? createId() - super({ id: objectId, x, y, entity: "STONE" }); + super({ id: objectId, x, y, entity: "STONE" }) - this.state = "IDLE"; - this.resource = resource ?? getRandomInRange(1, 5); + this.state = "IDLE" + this.resource = resource ?? getRandomInRange(1, 5) } live() { if (this.state === "IDLE") { - const random = getRandomInRange(1, 60); + const random = getRandomInRange(1, 60) if (random <= 1) { - this.handleChange(); + this.handleChange() } - return; + return } if (this.state === "MINING") { if (this.health <= 0) { - this.setAsMined(); + this.setAsMined() } - const random = getRandomInRange(1, 20); + const random = getRandomInRange(1, 20) if (random <= 1 && this.health > 0) { - this.state = "IDLE"; - this.isReserved = false; - this.handleChange(); + this.state = "IDLE" + this.isReserved = false + this.handleChange() } - return; + return } if (this.state === "DESTROYED") { - return; + return } } handleChange() { - this.sendMessageObjectUpdated(); + this.sendMessageObjectUpdated() } mine() { - this.state = "MINING"; - this.isReserved = true; - this.health -= 0.08; - this.handleChange(); + this.state = "MINING" + this.isReserved = true + this.health -= 0.08 + this.handleChange() } setAsMined() { - this.size = 0; - this.health = 0; - this.state = "DESTROYED"; - this.handleChange(); + this.size = 0 + this.health = 0 + this.state = "DESTROYED" + this.handleChange() } } diff --git a/apps/api/src/game/objects/tree.ts b/apps/api/src/game/objects/tree.ts index 70fedad9..3c92d189 100644 --- a/apps/api/src/game/objects/tree.ts +++ b/apps/api/src/game/objects/tree.ts @@ -1,134 +1,142 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import { type IGameObjectTree, getRandomInRange, -} from "../../../../../packages/api-sdk/src"; -import { GameObject } from "./gameObject"; +} from "../../../../../packages/api-sdk/src" +import { GameObject } from "./gameObject" interface ITreeOptions { - id?: string; - x: number; - y: number; - resource?: number; - size?: number; - health?: number; - growSpeed?: number; - type?: IGameObjectTree["type"]; - variant?: IGameObjectTree["variant"]; + id?: string + x: number + y: number + resource?: number + size?: number + health?: number + growSpeed?: number + type?: IGameObjectTree["type"] + variant?: IGameObjectTree["variant"] } export class Tree extends GameObject implements IGameObjectTree { - public type: IGameObjectTree["type"] = "1"; - public variant: IGameObjectTree["variant"] = "GREEN"; - public resource = 0; - public size; - public minSizeToChop = 75; - public maxSize = 100; - public growSpeed; - public health; - public isReadyToChop = false; - public isReserved = false; + public type: IGameObjectTree["type"] = "1" + public variant: IGameObjectTree["variant"] = "GREEN" + public resource = 0 + public size + public minSizeToChop = 75 + public maxSize = 100 + public growSpeed + public health + public isReadyToChop = false + public isReserved = false constructor({ - id, - x, - y, - resource, - size, - health, - growSpeed, - variant, type - }: ITreeOptions) { - const objectId = id ?? createId(); - - super({ id: objectId, x, y, entity: "TREE" }); - - this.state = "IDLE"; - this.resource = resource ?? getRandomInRange(1, 5); - this.size = size ?? 100; - this.health = health ?? 100; - this.growSpeed = growSpeed ?? 0.01; - this.type = type ?? this.getNewType(); - this.variant = variant ?? this.getNewVariant(); + id, + x, + y, + resource, + size, + health, + growSpeed, + variant, + type, + }: ITreeOptions) { + const objectId = id ?? createId() + + super({ id: objectId, x, y, entity: "TREE" }) + + this.state = "IDLE" + this.resource = resource ?? getRandomInRange(1, 5) + this.size = size ?? 100 + this.health = health ?? 100 + this.growSpeed = growSpeed ?? 0.01 + this.type = type ?? this.getNewType() + this.variant = variant ?? this.getNewVariant() } live() { - this.checkHealth(); + this.checkHealth() switch (this.state) { case "IDLE": - this.handleIdleState(); - break; + this.handleIdleState() + break case "CHOPPING": - this.handleChoppingState(); - break; + this.handleChoppingState() + break case "DESTROYED": - break; + break } } checkHealth() { if (this.health <= 0) { - this.destroy(); + this.destroy() } } handleChange() { - this.sendMessageObjectUpdated(); + this.sendMessageObjectUpdated() } handleIdleState() { - this.grow(); + this.grow() - const random = getRandomInRange(1, 60); + const random = getRandomInRange(1, 60) if (random <= 1) { - this.handleChange(); + this.handleChange() } } handleChoppingState() { - const random = getRandomInRange(1, 20); + const random = getRandomInRange(1, 20) if (random <= 1) { - this.state = "IDLE"; - this.isReserved = false; + this.state = "IDLE" + this.isReserved = false } } grow() { if (this.size >= this.minSizeToChop && !this.isReadyToChop) { - this.isReadyToChop = true; + this.isReadyToChop = true } if (this.size >= this.maxSize) { - return; + return } - this.size += this.growSpeed; - this.handleChange(); + this.size += this.growSpeed + this.handleChange() } public chop() { - this.state = "CHOPPING"; - this.isReserved = true; - this.health -= 0.08; - this.handleChange(); + this.state = "CHOPPING" + this.isReserved = true + this.health -= 0.08 + this.handleChange() } destroy() { - this.size = 0; - this.health = 0; - this.state = "DESTROYED"; - this.handleChange(); + this.size = 0 + this.health = 0 + this.state = "DESTROYED" + this.handleChange() } getNewType(): IGameObjectTree["type"] { - const types: IGameObjectTree["type"][] = ["1", "2", "3", "4", "5"]; - const index = getRandomInRange(0, types.length - 1); - return types[index]; + const types: IGameObjectTree["type"][] = ["1", "2", "3", "4", "5"] + const index = getRandomInRange(0, types.length - 1) + return types[index] } getNewVariant(): IGameObjectTree["variant"] { - const variants: IGameObjectTree["variant"][] = ["GREEN", "BLUE", "STONE", "TEAL", "TOXIC", "VIOLET"]; - const index = getRandomInRange(0, variants.length - 1); - return variants[index]; + const variants: IGameObjectTree["variant"][] = [ + "GREEN", + "BLUE", + "STONE", + "TEAL", + "TOXIC", + "VIOLET", + ] + const index = getRandomInRange(0, variants.length - 1) + return variants[index] } } diff --git a/apps/api/src/game/objects/units/index.ts b/apps/api/src/game/objects/units/index.ts index f5071834..5f43e0ea 100644 --- a/apps/api/src/game/objects/units/index.ts +++ b/apps/api/src/game/objects/units/index.ts @@ -3,4 +3,4 @@ export { Player } from "./player" export { Raider } from "./raider" export { Unit } from "./unit" export { VillageCourier } from "./villageCourier" -export { VillageFarmer } from "./villageFarmer" \ No newline at end of file +export { VillageFarmer } from "./villageFarmer" diff --git a/apps/api/src/game/objects/units/mechanic.ts b/apps/api/src/game/objects/units/mechanic.ts index 02d3a4fa..2936b5bb 100644 --- a/apps/api/src/game/objects/units/mechanic.ts +++ b/apps/api/src/game/objects/units/mechanic.ts @@ -1,15 +1,15 @@ -import { createId } from "@paralleldrive/cuid2"; -import type { IGameObjectMechanic } from "../../../../../../packages/api-sdk/src"; -import { Unit } from "./unit"; +import { createId } from "@paralleldrive/cuid2" +import type { IGameObjectMechanic } from "../../../../../../packages/api-sdk/src" +import { Unit } from "./unit" interface IMechanicOptions { - x: number; - y: number; + x: number + y: number } export class Mechanic extends Unit implements IGameObjectMechanic { constructor({ x, y }: IMechanicOptions) { - const id = createId(); + const id = createId() super({ id, @@ -21,18 +21,18 @@ export class Mechanic extends Unit implements IGameObjectMechanic { hairstyle: "COAL_LONG", top: "DARK_SILVER_SHIRT", }, - }); + }) } live() { - this.handleChange(); + this.handleChange() } handleChange() { const prepared = { ...this, - }; + } - this.sendMessageObjectUpdated(prepared); + this.sendMessageObjectUpdated(prepared) } } diff --git a/apps/api/src/game/objects/units/player.ts b/apps/api/src/game/objects/units/player.ts index d5685d2f..40da7e30 100644 --- a/apps/api/src/game/objects/units/player.ts +++ b/apps/api/src/game/objects/units/player.ts @@ -1,262 +1,262 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import { type IGameObjectPlayer, type IGameSkill, type ItemType, getRandomInRange, -} from "../../../../../../packages/api-sdk/src"; -import { MAX_X, MAX_Y, MIN_X, MIN_Y } from "../../../config"; -import { db } from "../../../db/db.client"; -import { Inventory, Skill } from "../../common"; -import { Stone } from "../stone"; -import { Tree } from "../tree"; -import { Unit } from "./unit"; +} from "../../../../../../packages/api-sdk/src" +import { MAX_X, MAX_Y, MIN_X, MIN_Y } from "../../../config" +import { db } from "../../../db/db.client" +import { Inventory, Skill } from "../../common" +import { Stone } from "../stone" +import { Tree } from "../tree" +import { Unit } from "./unit" interface IPlayerOptions { - id?: string; - x?: number; - y?: number; + id?: string + x?: number + y?: number } export class Player extends Unit implements IGameObjectPlayer { - public coins = 0; - public reputation = 0; - public villainPoints = 0; - public refuellerPoints = 0; - public userName = "NPC"; - public health = 100; + public coins = 0 + public reputation = 0 + public villainPoints = 0 + public refuellerPoints = 0 + public userName = "NPC" + public health = 100 - public inventoryId?: string; + public inventoryId?: string - public skills: Skill[] = []; + public skills: Skill[] = [] constructor({ id, x, y }: IPlayerOptions) { - const objectId = id ?? createId(); + const objectId = id ?? createId() - const finalX = x ?? getRandomInRange(MIN_X, MAX_X); - const finalY = y ?? getRandomInRange(MIN_Y, MAX_Y); + const finalX = x ?? getRandomInRange(MIN_X, MAX_X) + const finalY = y ?? getRandomInRange(MIN_Y, MAX_Y) - super({ id: objectId, x: finalX, y: finalY, entity: "PLAYER" }); + super({ id: objectId, x: finalX, y: finalY, entity: "PLAYER" }) } async init() { - await this.readFromDB(); - await this.initSkillsFromDB(); + await this.readFromDB() + await this.initSkillsFromDB() super.initVisual({ head: "1", hairstyle: "CLASSIC", top: "VIOLET_SHIRT", - }); + }) } live() { if (this.state === "IDLE") { - this.handleChange(); - return; + this.handleChange() + return } if (this.state === "MOVING") { - const isMoving = this.move(2); - this.handleChange(); + const isMoving = this.move(2) + this.handleChange() if (!isMoving && this.target) { if (this.target instanceof Tree) { - void this.startChopping(); - return; + void this.startChopping() + return } if (this.target instanceof Stone) { - void this.startMining(); - return; + void this.startMining() + return } } - return; + return } if (this.state === "CHOPPING") { if (this.target instanceof Tree) { // Skill up on random - const random = getRandomInRange(1, 200); + const random = getRandomInRange(1, 200) if (random <= 1) { - const skill = this.skills.find((skill) => skill.type === "WOODSMAN"); + const skill = this.skills.find((skill) => skill.type === "WOODSMAN") if (skill) { - void skill.addXp(); + void skill.addXp() } } // Check instrument - const axe = this.inventory.items.find((item) => item.type === "AXE"); + const axe = this.inventory.items.find((item) => item.type === "AXE") if (axe) { - this.target.health -= 0.16; - const random = getRandomInRange(1, 40); + this.target.health -= 0.16 + const random = getRandomInRange(1, 40) if (random <= 1) { - void this.inventory.checkAndBreakItem(axe, 1); + void this.inventory.checkAndBreakItem(axe, 1) } } - this.target.chop(); - this.handleChange(); + this.target.chop() + this.handleChange() if (this.target.health <= 0) { - void this.stopChopping(this.target); + void this.stopChopping(this.target) } } - return; + return } if (this.state === "MINING") { if (this.target instanceof Stone) { // Skill up on random - const random = getRandomInRange(1, 200); + const random = getRandomInRange(1, 200) if (random <= 1) { - const skill = this.skills.find((skill) => skill.type === "MINER"); + const skill = this.skills.find((skill) => skill.type === "MINER") if (skill) { - void skill.addXp(); + void skill.addXp() } } // Check instrument const pickaxe = this.inventory.items.find( (item) => item.type === "PICKAXE", - ); + ) if (pickaxe) { - this.target.health -= 0.16; - const random = getRandomInRange(1, 40); + this.target.health -= 0.16 + const random = getRandomInRange(1, 40) if (random <= 1) { - void this.inventory.checkAndBreakItem(pickaxe, 1); + void this.inventory.checkAndBreakItem(pickaxe, 1) } } - this.target.mine(); - this.handleChange(); + this.target.mine() + this.handleChange() if (this.target.health <= 0) { - void this.stopMining(this.target); + void this.stopMining(this.target) } } - return; + return } } handleChange() { - this.sendMessageObjectUpdated(); + this.sendMessageObjectUpdated() } async startChopping() { - this.state = "CHOPPING"; - this.direction = "RIGHT"; + this.state = "CHOPPING" + this.direction = "RIGHT" - await this.findOrCreateSkillInDB("WOODSMAN"); + await this.findOrCreateSkillInDB("WOODSMAN") - await this.updateInDB(); - this.handleChange(); + await this.updateInDB() + this.handleChange() } async stopChopping(tree: Tree) { - this.state = "IDLE"; + this.state = "IDLE" // Reward - await this.inventory.addOrCreateItem("WOOD", tree.resource); - this.handleChange(); + await this.inventory.addOrCreateItem("WOOD", tree.resource) + this.handleChange() } async startMining() { - this.state = "MINING"; - this.direction = "RIGHT"; + this.state = "MINING" + this.direction = "RIGHT" - await this.findOrCreateSkillInDB("MINER"); + await this.findOrCreateSkillInDB("MINER") - await this.updateInDB(); - this.handleChange(); + await this.updateInDB() + this.handleChange() } async stopMining(stone: Stone) { - this.state = "IDLE"; + this.state = "IDLE" // Reward - await this.inventory.addOrCreateItem("STONE", stone.resource); - this.handleChange(); + await this.inventory.addOrCreateItem("STONE", stone.resource) + this.handleChange() } updateCoins(amount: number) { - this.coins = this.coins + amount; - this.handleChange(); + this.coins = this.coins + amount + this.handleChange() return db.player.update({ where: { id: this.id }, data: { coins: this.coins, }, - }); + }) } addReputation(amount: number) { - this.reputation += amount; - this.handleChange(); + this.reputation += amount + this.handleChange() return db.player.update({ where: { id: this.id }, data: { reputation: this.reputation, }, - }); + }) } addRefuellerPoints(amount: number) { - this.refuellerPoints += amount; - this.handleChange(); + this.refuellerPoints += amount + this.handleChange() return db.player.update({ where: { id: this.id }, data: { refuellerPoints: this.refuellerPoints, }, - }); + }) } addVillainPoints(amount: number) { - this.villainPoints += amount; - this.handleChange(); + this.villainPoints += amount + this.handleChange() return db.player.update({ where: { id: this.id }, data: { villainPoints: { increment: amount, - } + }, }, - }); + }) } async buyItemFromDealer(type: ItemType, price: number, amount: number) { - const item = await this.inventory.tryGetItemInDB(type); + const item = await this.inventory.tryGetItemInDB(type) if (item) { - return false; + return false } if (this.coins < price) { - return false; + return false } - await this.updateCoins(-price); - await this.inventory.addOrCreateItem(type, amount); - this.handleChange(); + await this.updateCoins(-price) + await this.inventory.addOrCreateItem(type, amount) + this.handleChange() - return true; + return true } public async readFromDB() { - const player = await db.player.findUnique({ where: { id: this.id } }); + const player = await db.player.findUnique({ where: { id: this.id } }) if (!player) { - return; + return } - this.userName = player.userName; - this.coins = player.coins; - this.reputation = player.reputation; - this.villainPoints = player.villainPoints; - this.refuellerPoints = player.refuellerPoints; - this.inventoryId = player.inventoryId; + this.userName = player.userName + this.coins = player.coins + this.reputation = player.reputation + this.villainPoints = player.villainPoints + this.refuellerPoints = player.refuellerPoints + this.inventoryId = player.inventoryId } public updateInDB() { @@ -265,41 +265,41 @@ export class Player extends Unit implements IGameObjectPlayer { data: { lastActionAt: new Date(), }, - }); + }) } public async initInventoryFromDB() { if (!this.inventoryId) { - return; + return } const inventory = new Inventory({ objectId: this.id, id: this.inventoryId, saveInDb: true, - }); - await inventory.init(); - this.inventory = inventory; + }) + await inventory.init() + this.inventory = inventory } public async initSkillsFromDB() { - this.skills = []; - const skills = await Skill.findAllInDB(this.id); + this.skills = [] + const skills = await Skill.findAllInDB(this.id) for (const skill of skills) { - const instance = new Skill({ id: skill.id }); - await instance.init(); - this.skills.push(instance); + const instance = new Skill({ id: skill.id }) + await instance.init() + this.skills.push(instance) } } async findOrCreateSkillInDB(type: IGameSkill["type"]) { - const skill = this.skills.find((skill) => skill.type === type); + const skill = this.skills.find((skill) => skill.type === type) if (!skill) { - await Skill.createInDB(this.id, type); - await this.initSkillsFromDB(); - return this.skills.find((skill) => skill.type === type) as Skill; + await Skill.createInDB(this.id, type) + await this.initSkillsFromDB() + return this.skills.find((skill) => skill.type === type) as Skill } - return skill; + return skill } } diff --git a/apps/api/src/game/objects/units/raider.ts b/apps/api/src/game/objects/units/raider.ts index 68073320..c10b02ff 100644 --- a/apps/api/src/game/objects/units/raider.ts +++ b/apps/api/src/game/objects/units/raider.ts @@ -1,26 +1,26 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import { type IGameObjectRaider, getRandomInRange, -} from "../../../../../../packages/api-sdk/src"; +} from "../../../../../../packages/api-sdk/src" import { RAIDER_CAMP_MAX_X, RAIDER_CAMP_MAX_Y, RAIDER_CAMP_MIN_X, RAIDER_CAMP_MIN_Y, -} from "../../../config"; -import type { GameObject } from "../gameObject"; -import { Unit } from "./unit"; +} from "../../../config" +import type { GameObject } from "../gameObject" +import { Unit } from "./unit" export class Raider extends Unit implements IGameObjectRaider { - public userName = "рейдер"; - public colorIndex = 0; + public userName = "рейдер" + public colorIndex = 0 constructor() { - const objectId = createId(); + const objectId = createId() - const finalX = getRandomInRange(RAIDER_CAMP_MIN_X, RAIDER_CAMP_MAX_X); - const finalY = getRandomInRange(RAIDER_CAMP_MIN_Y, RAIDER_CAMP_MAX_Y); + const finalX = getRandomInRange(RAIDER_CAMP_MIN_X, RAIDER_CAMP_MAX_X) + const finalY = getRandomInRange(RAIDER_CAMP_MIN_Y, RAIDER_CAMP_MAX_Y) super({ id: objectId, @@ -32,23 +32,23 @@ export class Raider extends Unit implements IGameObjectRaider { hairstyle: "BOLD", top: "BLACK_SHIRT", }, - }); + }) } live() { if (this.state === "IDLE") { - this.sendMessageObjectUpdated(); - return; + this.sendMessageObjectUpdated() + return } if (this.state === "MOVING") { - this.sendMessageObjectUpdated(); - return; + this.sendMessageObjectUpdated() + return } } moveOutOfScene(target: GameObject) { - this.target = target; - this.state = "MOVING"; + this.target = target + this.state = "MOVING" } } diff --git a/apps/api/src/game/objects/units/unit.ts b/apps/api/src/game/objects/units/unit.ts index 1100038e..22340702 100644 --- a/apps/api/src/game/objects/units/unit.ts +++ b/apps/api/src/game/objects/units/unit.ts @@ -1,37 +1,37 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import { type IGameObject, type IGameObjectUnit, getRandomInRange, -} from "../../../../../../packages/api-sdk/src"; -import { MAX_X, MAX_Y, MIN_X, MIN_Y } from "../../../config"; -import { Inventory } from "../../common"; -import { GameObject } from "../gameObject"; +} from "../../../../../../packages/api-sdk/src" +import { MAX_X, MAX_Y, MIN_X, MIN_Y } from "../../../config" +import { Inventory } from "../../common" +import { GameObject } from "../gameObject" interface IUnitOptions { - entity: IGameObject["entity"]; - id?: string; - x?: number; - y?: number; - visual?: IGameObjectUnit["visual"]; + entity: IGameObject["entity"] + id?: string + x?: number + y?: number + visual?: IGameObjectUnit["visual"] } export class Unit extends GameObject implements IGameObjectUnit { - public inventory!: Inventory; - public visual!: IGameObjectUnit["visual"]; - public coins: number; + public inventory!: Inventory + public visual!: IGameObjectUnit["visual"] + public coins: number constructor({ entity, id, x, y, visual }: IUnitOptions) { - const objectId = id ?? createId(); + const objectId = id ?? createId() - const finalX = x ?? getRandomInRange(MIN_X, MAX_X); - const finalY = y ?? getRandomInRange(MIN_Y, MAX_Y); + const finalX = x ?? getRandomInRange(MIN_X, MAX_X) + const finalY = y ?? getRandomInRange(MIN_Y, MAX_Y) - super({ id: objectId, x: finalX, y: finalY, entity }); + super({ id: objectId, x: finalX, y: finalY, entity }) - this.initInventory(); - this.initVisual(visual); - this.coins = 0; + this.initInventory() + this.initVisual(visual) + this.coins = 0 } public initInventory() { @@ -39,7 +39,7 @@ export class Unit extends GameObject implements IGameObjectUnit { objectId: this.id, id: createId(), saveInDb: false, - }); + }) } public initVisual(visual: IGameObjectUnit["visual"] | undefined) { @@ -47,6 +47,6 @@ export class Unit extends GameObject implements IGameObjectUnit { head: "1", hairstyle: "CLASSIC", top: "VIOLET_SHIRT", - }; + } } } diff --git a/apps/api/src/game/objects/units/villageCourier.ts b/apps/api/src/game/objects/units/villageCourier.ts index ac6de310..1b0e5b04 100644 --- a/apps/api/src/game/objects/units/villageCourier.ts +++ b/apps/api/src/game/objects/units/villageCourier.ts @@ -1,24 +1,24 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import { type IGameObjectCourier, type ItemType, getRandomInRange, -} from "../../../../../../packages/api-sdk/src"; -import type { Village } from "../../chunks"; -import { Building } from "../buildings/building"; -import { Unit } from "./unit"; +} from "../../../../../../packages/api-sdk/src" +import type { Village } from "../../chunks" +import { Building } from "../buildings/building" +import { Unit } from "./unit" interface ICourierOptions { - village: Village; - x: number; - y: number; + village: Village + x: number + y: number } export class VillageCourier extends Unit implements IGameObjectCourier { - private village: Village; + private village: Village constructor({ village, x, y }: ICourierOptions) { - const id = createId(); + const id = createId() super({ id, @@ -30,9 +30,9 @@ export class VillageCourier extends Unit implements IGameObjectCourier { hairstyle: "BOLD", top: "BLUE_SHIRT", }, - }); + }) - this.village = village; + this.village = village } async live() { @@ -49,22 +49,22 @@ export class VillageCourier extends Unit implements IGameObjectCourier { // return; // } - const random = getRandomInRange(1, 100); + const random = getRandomInRange(1, 100) if (random <= 1) { - const randObj = this.village.getRandomMovementFlagInVillage(); + const randObj = this.village.getRandomMovementFlagInVillage() if (!randObj) { - return; + return } - this.setTarget(randObj); + this.setTarget(randObj) } - this.handleChange(); - return; + this.handleChange() + return } if (this.state === "MOVING") { - const isMoving = this.move(2, 12); - this.handleChange(); + const isMoving = this.move(2, 12) + this.handleChange() if (!isMoving && this.target) { // if (this.target instanceof Player) { @@ -83,7 +83,7 @@ export class VillageCourier extends Unit implements IGameObjectCourier { // } } - return; + return } } @@ -91,36 +91,36 @@ export class VillageCourier extends Unit implements IGameObjectCourier { const prepared = { ...this, village: undefined, - }; + } - this.sendMessageObjectUpdated(prepared); + this.sendMessageObjectUpdated(prepared) } async takeItemFromUnit(type: ItemType) { if (this.target instanceof Unit) { - const item = this.target.inventory.transferItemWithType(type); + const item = this.target.inventory.transferItemWithType(type) if (item) { - await this.inventory.addOrCreateItem(item.type, item.amount); - this.target.inventory.destroyItem(item.id); + await this.inventory.addOrCreateItem(item.type, item.amount) + this.target.inventory.destroyItem(item.id) - return true; + return true } } - return false; + return false } async placeItemInBuilding(type: ItemType) { if (this.target instanceof Building) { - const item = this.inventory.transferItemWithType(type); + const item = this.inventory.transferItemWithType(type) if (item) { - await this.target.inventory.addOrCreateItem(item.type, item.amount); - this.inventory.destroyItem(item.id); + await this.target.inventory.addOrCreateItem(item.type, item.amount) + this.inventory.destroyItem(item.id) - return true; + return true } } - return false; + return false } } diff --git a/apps/api/src/game/objects/units/villageFarmer.ts b/apps/api/src/game/objects/units/villageFarmer.ts index 42da2118..39b1d3fd 100644 --- a/apps/api/src/game/objects/units/villageFarmer.ts +++ b/apps/api/src/game/objects/units/villageFarmer.ts @@ -1,24 +1,24 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import { type IGameObjectFarmer, getRandomInRange, -} from "../../../../../../packages/api-sdk/src"; -import type { Village } from "../../chunks"; -import { Flag } from "../flag"; -import { Tree } from "../tree"; -import { Unit } from "./unit"; +} from "../../../../../../packages/api-sdk/src" +import type { Village } from "../../chunks" +import { Flag } from "../flag" +import { Tree } from "../tree" +import { Unit } from "./unit" interface IVillageFarmerOptions { - village: Village; - x: number; - y: number; + village: Village + x: number + y: number } export class VillageFarmer extends Unit implements IGameObjectFarmer { - private village: Village; + private village: Village constructor({ village, x, y }: IVillageFarmerOptions) { - const id = createId(); + const id = createId() super({ id, @@ -30,37 +30,37 @@ export class VillageFarmer extends Unit implements IGameObjectFarmer { hairstyle: "CLASSIC", top: "GREEN_SHIRT", }, - }); + }) - this.village = village; + this.village = village } live() { if (this.state === "IDLE") { - const flagToPlantNewTree = this.village.checkIfNeedToPlantTree(); + const flagToPlantNewTree = this.village.checkIfNeedToPlantTree() if (flagToPlantNewTree) { - this.target = flagToPlantNewTree; - this.state = "MOVING"; + this.target = flagToPlantNewTree + this.state = "MOVING" - this.handleChange(); - return; + this.handleChange() + return } - const random = getRandomInRange(1, 300); + const random = getRandomInRange(1, 300) if (random <= 1) { - const randomObj = this.village.getRandomMovementFlagInVillage(); + const randomObj = this.village.getRandomMovementFlagInVillage() if (!randomObj) { - return; + return } - this.setTarget(randomObj); + this.setTarget(randomObj) } - this.handleChange(); - return; + this.handleChange() + return } if (this.state === "MOVING") { - const isMoving = this.move(1, 4); + const isMoving = this.move(1, 4) if (!isMoving && this.target) { if (this.target instanceof Flag && this.target.type === "RESOURCE") { @@ -69,17 +69,17 @@ export class VillageFarmer extends Unit implements IGameObjectFarmer { y: this.target.y, resource: 1, size: 12, - variant: this.village.theme - }); - this.village.plantNewTree(this.target, tree); + variant: this.village.theme, + }) + this.village.plantNewTree(this.target, tree) } - this.state = "IDLE"; - this.target = undefined; + this.state = "IDLE" + this.target = undefined } - this.handleChange(); - return; + this.handleChange() + return } } @@ -87,8 +87,8 @@ export class VillageFarmer extends Unit implements IGameObjectFarmer { const prepared = { ...this, village: undefined, - }; + } - this.sendMessageObjectUpdated(prepared); + this.sendMessageObjectUpdated(prepared) } } diff --git a/apps/api/src/game/objects/wagon.ts b/apps/api/src/game/objects/wagon.ts index 0c6398e7..0097f8c8 100644 --- a/apps/api/src/game/objects/wagon.ts +++ b/apps/api/src/game/objects/wagon.ts @@ -1,101 +1,101 @@ -import { createId } from "@paralleldrive/cuid2"; -import type { IGameObjectWagon } from "../../../../../packages/api-sdk/src"; -import { Flag } from "./flag"; -import { GameObject } from "./gameObject"; -import { Mechanic } from "./units"; +import { createId } from "@paralleldrive/cuid2" +import type { IGameObjectWagon } from "../../../../../packages/api-sdk/src" +import { Flag } from "./flag" +import { GameObject } from "./gameObject" +import { Mechanic } from "./units" interface IWagonOptions { - x: number; - y: number; + x: number + y: number } export class Wagon extends GameObject implements IGameObjectWagon { - public speed: number; - public fuel: number; - public visibilityArea!: IGameObjectWagon["visibilityArea"]; + public speed: number + public fuel: number + public visibilityArea!: IGameObjectWagon["visibilityArea"] - public mechanic!: Mechanic; - public serverDataArea!: IGameObjectWagon["visibilityArea"]; - public collisionArea!: IGameObjectWagon["visibilityArea"]; - public nearFlags: Flag[] = []; + public mechanic!: Mechanic + public serverDataArea!: IGameObjectWagon["visibilityArea"] + public collisionArea!: IGameObjectWagon["visibilityArea"] + public nearFlags: Flag[] = [] constructor({ x, y }: IWagonOptions) { - const finalId = createId(); + const finalId = createId() - super({ id: finalId, x, y, entity: "WAGON", isVisibleOnClient: true }); + super({ id: finalId, x, y, entity: "WAGON", isVisibleOnClient: true }) - this.speed = 0; - this.fuel = 2000; - this.updateVisibilityArea(); - this.updateServerDataArea(); - this.initNearFlags(); - this.initMechanic(); + this.speed = 0 + this.fuel = 2000 + this.updateVisibilityArea() + this.updateServerDataArea() + this.initNearFlags() + this.initMechanic() } live() { - this.updateVisibilityArea(); - this.updateServerDataArea(); - this.updateCollisionArea(); - this.updateNearFlags(); - this.updateMechanic(); - this.consumeFuel(); + this.updateVisibilityArea() + this.updateServerDataArea() + this.updateCollisionArea() + this.updateNearFlags() + this.updateMechanic() + this.consumeFuel() if (this.state === "IDLE") { - this.handleChange(); - return; + this.handleChange() + return } if (this.state === "WAITING") { - this.handleChange(); - return; + this.handleChange() + return } } handleChange() { - this.sendMessageObjectUpdated(); + this.sendMessageObjectUpdated() } consumeFuel() { if (this.speed <= 0) { - return; + return } - this.fuel -= this.speed * 2; + this.fuel -= this.speed * 2 } updateVisibilityArea() { - const offsetX = 2560 / 2; - const offsetY = 1440 / 2; + const offsetX = 2560 / 2 + const offsetY = 1440 / 2 this.visibilityArea = { startX: this.x - offsetX, endX: this.x + offsetX, startY: this.y - offsetY, endY: this.y + offsetY, - }; + } } updateServerDataArea() { - const offsetX = 2560 * 1.5; - const offsetY = 1440; + const offsetX = 2560 * 1.5 + const offsetY = 1440 this.serverDataArea = { startX: this.x - offsetX, endX: this.x + offsetX, startY: this.y - offsetY, endY: this.y + offsetY, - }; + } } updateCollisionArea() { - const offsetX = 250; - const offsetY = 180; + const offsetX = 250 + const offsetY = 180 this.collisionArea = { startX: this.x - offsetX, endX: this.x + offsetX, startY: this.y - offsetY, endY: this.y + offsetY, - }; + } } public checkIfPointInCollisionArea(point: { x: number; y: number }) { @@ -104,7 +104,7 @@ export class Wagon extends GameObject implements IGameObjectWagon { point.x < this.collisionArea.endX && this.collisionArea.startY < point.y && point.y < this.collisionArea.endY - ); + ) } public checkIfPointInVisibilityArea(point: { x: number; y: number }) { @@ -113,7 +113,7 @@ export class Wagon extends GameObject implements IGameObjectWagon { point.x < this.visibilityArea.endX && this.visibilityArea.startY < point.y && point.y < this.visibilityArea.endY - ); + ) } public checkIfPointInServerDataArea(point: { x: number; y: number }) { @@ -122,20 +122,20 @@ export class Wagon extends GameObject implements IGameObjectWagon { point.x < this.serverDataArea.endX && this.serverDataArea.startY < point.y && point.y < this.serverDataArea.endY - ); + ) } initMechanic() { - this.mechanic = new Mechanic({ x: this.x, y: this.y }); + this.mechanic = new Mechanic({ x: this.x, y: this.y }) } updateMechanic() { - this.mechanic.isVisibleOnClient = true; - this.mechanic.needToSendDataToClient = true; - this.mechanic.live(); - this.mechanic.direction = "LEFT"; - this.mechanic.x = this.x - 50; - this.mechanic.y = this.y - 48; + this.mechanic.isVisibleOnClient = true + this.mechanic.needToSendDataToClient = true + this.mechanic.live() + this.mechanic.direction = "LEFT" + this.mechanic.x = this.x - 50 + this.mechanic.y = this.y - 48 } initNearFlags() { @@ -145,28 +145,28 @@ export class Wagon extends GameObject implements IGameObjectWagon { y: this.y, offsetX: -300, offsetY: 0, - }); + }) const flag2 = new Flag({ type: "WAGON_NEAR_MOVEMENT", x: this.x - 100, y: this.y + 150, offsetX: -100, offsetY: 150, - }); + }) const flag3 = new Flag({ type: "WAGON_NEAR_MOVEMENT", x: this.x + 200, y: this.y + 150, offsetX: 200, offsetY: 150, - }); - this.nearFlags.push(flag1, flag2, flag3); + }) + this.nearFlags.push(flag1, flag2, flag3) } updateNearFlags() { for (const nearFlag of this.nearFlags) { - nearFlag.x = this.x + nearFlag.offsetX; - nearFlag.y = this.y + nearFlag.offsetY; + nearFlag.x = this.x + nearFlag.offsetX + nearFlag.y = this.y + nearFlag.offsetY } } } diff --git a/apps/api/src/game/objects/water.ts b/apps/api/src/game/objects/water.ts index 70857038..af5f2179 100644 --- a/apps/api/src/game/objects/water.ts +++ b/apps/api/src/game/objects/water.ts @@ -1,16 +1,16 @@ -import { GameObject } from "./gameObject"; -import { IGameObjectWater } from "../../../../../packages/api-sdk/src"; -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" +import type { IGameObjectWater } from "../../../../../packages/api-sdk/src" +import { GameObject } from "./gameObject" interface IWaterOptions { - x: number; - y: number; + x: number + y: number } export class Water extends GameObject implements IGameObjectWater { constructor({ x, y }: IWaterOptions) { - const id = createId(); + const id = createId() - super({ id, x, y, entity: "WATER" }); + super({ id, x, y, entity: "WATER" }) } -} \ No newline at end of file +} diff --git a/apps/api/src/game/objects/wolf.ts b/apps/api/src/game/objects/wolf.ts index bf8e97fa..3f9a5386 100644 --- a/apps/api/src/game/objects/wolf.ts +++ b/apps/api/src/game/objects/wolf.ts @@ -1,31 +1,31 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import { type IGameObjectWolf, getRandomInRange, -} from "../../../../../packages/api-sdk/src"; -import { MAX_X, MAX_Y, MIN_X, MIN_Y } from "../../config"; -import { GameObject } from "./gameObject"; +} from "../../../../../packages/api-sdk/src" +import { MAX_X, MAX_Y, MIN_X, MIN_Y } from "../../config" +import { GameObject } from "./gameObject" export class Wolf extends GameObject implements IGameObjectWolf { constructor() { - const id = createId(); - const x = getRandomInRange(MIN_X, MAX_X); - const y = getRandomInRange(MIN_Y, MAX_Y); + const id = createId() + const x = getRandomInRange(MIN_X, MAX_X) + const y = getRandomInRange(MIN_Y, MAX_Y) - super({ id, x, y, entity: "WOLF" }); + super({ id, x, y, entity: "WOLF" }) } live() { if (this.state === "IDLE") { - this.sendMessageObjectUpdated(); - return; + this.sendMessageObjectUpdated() + return } if (this.state === "MOVING") { - this.move(1); + this.move(1) - this.sendMessageObjectUpdated(); - return; + this.sendMessageObjectUpdated() + return } } } diff --git a/apps/api/src/game/scenes/defenceScene.ts b/apps/api/src/game/scenes/defenceScene.ts index c594962c..cb627411 100644 --- a/apps/api/src/game/scenes/defenceScene.ts +++ b/apps/api/src/game/scenes/defenceScene.ts @@ -1,18 +1,18 @@ -import { getRandomInRange } from "../../../../../packages/api-sdk/src"; -import type { Group } from "../common"; -import type { Game } from "../game"; -import { Stone, Tree } from "../objects"; -import { GameScene } from "./gameScene"; -import { Player } from "../objects/units"; +import { getRandomInRange } from "../../../../../packages/api-sdk/src" +import type { Group } from "../common" +import type { Game } from "../game" +import { Stone, Tree } from "../objects" +import { Player } from "../objects/units" +import { GameScene } from "./gameScene" interface IDefenceSceneOptions { - game: Game; - group: Group | undefined; + game: Game + group: Group | undefined } export class DefenceScene extends GameScene { - public wood!: number; - public stone!: number; + public wood!: number + public stone!: number constructor({ game, group }: IDefenceSceneOptions) { super({ @@ -26,77 +26,77 @@ export class DefenceScene extends GameScene { "HELP", "DONATE", ], - }); + }) - void this.init(); + void this.init() } public async init() { - await this.initGroupPlayers(); - this.initTrees(12); - this.initStones(8); + await this.initGroupPlayers() + this.initTrees(12) + this.initStones(8) - this.wood = 0; - this.stone = 0; + this.wood = 0 + this.stone = 0 this.initEvent({ type: "COUNTDOWN_NEXT_WAVE_STARTED", title: "Скоро будет волна", secondsToEnd: 60 * 5, - }); + }) - void this.play(); + void this.play() } async initGroupPlayers() { if (!this.group) { - return; + return } for (const player of this.group.players) { - const instance = await this.initPlayer(player.id); - this.objects.push(instance); + const instance = await this.initPlayer(player.id) + this.objects.push(instance) } } async initPlayer(id: string) { - const instance = new Player({ id }); - await instance.init(); + const instance = new Player({ id }) + await instance.init() - const spawnFlag = this.findSpawnFlag("SPAWN_LEFT"); + const spawnFlag = this.findSpawnFlag("SPAWN_LEFT") if (spawnFlag) { - instance.x = spawnFlag.x; - instance.y = spawnFlag.y; + instance.x = spawnFlag.x + instance.y = spawnFlag.y } - const targetFlag = this.findRandomMovementFlag(); + const targetFlag = this.findRandomMovementFlag() if (targetFlag) { - instance.target = targetFlag; - instance.state = "MOVING"; + instance.target = targetFlag + instance.state = "MOVING" } - return instance; + return instance } private initTrees(count: number) { for (let i = 0; i < count; i++) { - const flag = this.findRandomEmptyResourceFlag(); + const flag = this.findRandomEmptyResourceFlag() if (flag) { - const size = getRandomInRange(75, 90); - const tree = new Tree({ x: flag.x, y: flag.y, size, resource: 1 }); - flag.target = tree; - this.objects.push(tree); + const size = getRandomInRange(75, 90) + const tree = new Tree({ x: flag.x, y: flag.y, size, resource: 1 }) + flag.target = tree + this.objects.push(tree) } } } private initStones(count: number) { for (let i = 0; i < count; i++) { - const flag = this.findRandomEmptyResourceFlag(); + const flag = this.findRandomEmptyResourceFlag() if (flag) { - const stone = new Stone({ x: flag.x, y: flag.y, resource: 1 }); - flag.target = stone; - this.objects.push(stone); + const stone = new Stone({ x: flag.x, y: flag.y, resource: 1 }) + flag.target = stone + this.objects.push(stone) } } } diff --git a/apps/api/src/game/scenes/gameScene.ts b/apps/api/src/game/scenes/gameScene.ts index 7bdf475d..cf575114 100644 --- a/apps/api/src/game/scenes/gameScene.ts +++ b/apps/api/src/game/scenes/gameScene.ts @@ -1,24 +1,24 @@ -import { createId } from "@paralleldrive/cuid2"; +import { createId } from "@paralleldrive/cuid2" import { type GameSceneType, type GetSceneResponse, type IGameChunk, + type IGameChunkTheme, type IGameEvent, type IGameRoute, type IGameSceneAction, type ItemType, getRandomInRange, - IGameChunkTheme, -} from "../../../../../packages/api-sdk/src"; +} from "../../../../../packages/api-sdk/src" import { ADMIN_PLAYER_ID, DISCORD_SERVER_INVITE_URL, DONATE_URL, SERVER_TICK_MS, -} from "../../config"; -import { Forest, type GameChunk, Village, LakeChunk } from "../chunks"; -import { Event, Group, Route } from "../common"; -import type { Game } from "../game"; +} from "../../config" +import { Forest, type GameChunk, LakeChunk, Village } from "../chunks" +import { Event, Group, Route } from "../common" +import type { Game } from "../game" import { Flag, type GameObject, @@ -27,47 +27,47 @@ import { Tree, Wagon, type Wolf, -} from "../objects"; -import { Player, Raider } from "../objects/units"; +} from "../objects" +import { Player, Raider } from "../objects/units" interface IGameSceneOptions { - game: Game; - group: Group | undefined; - possibleActions: IGameSceneAction[]; + game: Game + group: Group | undefined + possibleActions: IGameSceneAction[] } export class GameScene { - public id: string; - public game: Game; - public objects: GameObject[] = []; - public group: Group | undefined; - public events: Event[] = []; - public chunks: GameChunk[] = []; - public chunkNow: GameChunk | undefined; - public route: Route | undefined; - public possibleActions: IGameSceneAction[] = []; + public id: string + public game: Game + public objects: GameObject[] = [] + public group: Group | undefined + public events: Event[] = [] + public chunks: GameChunk[] = [] + public chunkNow: GameChunk | undefined + public route: Route | undefined + public possibleActions: IGameSceneAction[] = [] constructor({ game, group, possibleActions }: IGameSceneOptions) { - this.id = createId(); - this.game = game; - this.group = group; - this.possibleActions = possibleActions; + this.id = createId() + this.game = game + this.group = group + this.possibleActions = possibleActions - this.initSpawnFlags(); + this.initSpawnFlags() } public async play() { return setInterval(() => { - this.updateEvents(); - this.updateObjects(); - this.updateRoute(); - this.updateChunks(); - this.updateChunkNow(); - }, SERVER_TICK_MS); + this.updateEvents() + this.updateObjects() + this.updateRoute() + this.updateChunks() + this.updateChunkNow() + }, SERVER_TICK_MS) } destroy() { - this.objects = []; + this.objects = [] } public async handleAction( @@ -75,22 +75,22 @@ export class GameScene { playerId: string, params?: string[], ) { - const player = await this.findOrCreatePlayer(playerId); + const player = await this.findOrCreatePlayer(playerId) if (!player) { return { ok: false, message: "Тебя нет в активной игре :(", - }; + } } if (action === "REFUEL") { - return this.refuelAction(player, params); + return this.refuelAction(player, params) } if (action === "CHOP") { - return this.chopAction(player); + return this.chopAction(player) } if (action === "MINE") { - return this.mineAction(player); + return this.mineAction(player) } if (action === "START_CHANGING_SCENE") { // Admin only @@ -98,9 +98,9 @@ export class GameScene { return { ok: false, message: null, - }; + } } - return this.startChangingSceneAction(player, params); + return this.startChangingSceneAction(player, params) } if (action === "START_GROUP_BUILD") { // Admin only @@ -108,9 +108,9 @@ export class GameScene { return { ok: false, message: null, - }; + } } - return this.startGroupBuildAction(player, params); + return this.startGroupBuildAction(player, params) } if (action === "DISBAND_GROUP") { // Admin only @@ -118,9 +118,9 @@ export class GameScene { return { ok: false, message: null, - }; + } } - return this.disbandGroupAction(); + return this.disbandGroupAction() } if (action === "START_CREATING_NEW_ADVENTURE") { // Admin only @@ -128,53 +128,53 @@ export class GameScene { return { ok: false, message: null, - }; + } } - return this.startCreatingNewAdventureAction(); + return this.startCreatingNewAdventureAction() } if (action === "JOIN_GROUP") { - return this.joinGroupAction(player); + return this.joinGroupAction(player) } if (action === "HELP") { - return this.helpAction(player); + return this.helpAction(player) } if (action === "DONATE") { - return this.donateAction(player); + return this.donateAction(player) } if (action === "GIFT") { - return this.giftAction(player, params); + return this.giftAction(player, params) } if (action === "SELL") { - return this.sellAction(player, params); + return this.sellAction(player, params) } if (action === "BUY") { - return this.buyAction(player, params); + return this.buyAction(player, params) } return { ok: false, message: null, - }; + } } checkIfActionIsPossible(action: IGameSceneAction) { - return this.possibleActions.find((a) => a === action); + return this.possibleActions.find((a) => a === action) } initEvent({ - title, - type, - secondsToEnd, - scene, - }: { - title: string; - type: IGameEvent["type"]; - secondsToEnd: number; - scene?: GameSceneType; + title, + type, + secondsToEnd, + scene, + }: { + title: string + type: IGameEvent["type"] + secondsToEnd: number + scene?: GameSceneType }) { this.events.push( new Event({ game: this.game, title, type, secondsToEnd, scene }), - ); + ) } getEvents(): IGameEvent[] { @@ -184,12 +184,12 @@ export class GameScene { type: event.type, status: event.status, endsAt: event.endsAt, - })); + })) } getChunkNow(): IGameChunk | null { if (!this.chunkNow) { - return null; + return null } return { @@ -200,19 +200,19 @@ export class GameScene { center: this.chunkNow.center, area: this.chunkNow.area, isVisibleOnClient: this.chunkNow.isVisibleOnClient, - }; + } } getRoute(): IGameRoute | null { if (!this.route) { - return null; + return null } return { startPoint: this.route.startPoint, endPoint: this.route.endPoint, chunks: this.route.chunks, - }; + } } getInfo(): GetSceneResponse { @@ -224,294 +224,294 @@ export class GameScene { wagon: this.getWagon(), chunk: this.getChunkNow(), route: this.getRoute(), - }; + } } updateEvents() { for (const event of this.events) { - const status = event.checkStatus(); + const status = event.checkStatus() if (status === "STOPPED") { - event.handleEnding(); + event.handleEnding() - const index = this.events.indexOf(event); - this.events.splice(index, 1); + const index = this.events.indexOf(event) + this.events.splice(index, 1) } } } updateObjects() { - const wagon = this.getWagon(); + const wagon = this.getWagon() for (const obj of this.objects) { obj.isVisibleOnClient = wagon.checkIfPointInVisibilityArea({ x: obj.x, y: obj.y, - }); + }) obj.needToSendDataToClient = wagon.checkIfPointInServerDataArea({ x: obj.x, y: obj.y, - }); + }) if (obj instanceof Wagon) { - this.updateWagon(obj); - continue; + this.updateWagon(obj) + continue } if (obj instanceof Player) { - this.updatePlayer(obj); - continue; + this.updatePlayer(obj) + continue } - void obj.live(); + void obj.live() } } updateRoute() { if (!this.route?.flags) { - return; + return } for (const flag of this.route.flags) { - void flag.live(); + void flag.live() } } updateChunks() { - const wagon = this.getWagon(); + const wagon = this.getWagon() for (const chunk of this.chunks) { chunk.isVisibleOnClient = wagon.checkIfPointInVisibilityArea({ x: chunk.center.x, y: chunk.center.y, - }); + }) chunk.needToSendDataToClient = wagon.checkIfPointInServerDataArea({ x: chunk.center.x, y: chunk.center.y, - }); + }) - chunk.live(); + chunk.live() } } updateChunkNow() { - this.chunkNow = undefined; + this.chunkNow = undefined - const wagon = this.getWagon(); + const wagon = this.getWagon() for (const chunk of this.chunks) { const isWagonOnThisChunk = chunk.checkIfPointIsInArea({ x: wagon.x, y: wagon.y, - }); + }) if (isWagonOnThisChunk) { - this.chunkNow = chunk; + this.chunkNow = chunk } } } getWagon() { - return this.objects.find((obj) => obj instanceof Wagon) as Wagon; + return this.objects.find((obj) => obj instanceof Wagon) as Wagon } updateWagon(object: Wagon) { const collisionObjects = this.chunkNow?.objects.filter( (obj) => obj.isOnWagonPath && obj.state !== "DESTROYED", - ) ?? []; + ) ?? [] for (const collisionObject of collisionObjects) { const isInArea = object.checkIfPointInCollisionArea({ x: collisionObject.x, y: collisionObject.y, - }); + }) if (isInArea) { - object.state = "WAITING"; - object.speed = 0; - object.handleChange(); - return; + object.state = "WAITING" + object.speed = 0 + object.handleChange() + return } } if (object.fuel <= 1) { - object.state = "WAITING"; - object.speed = 0; - object.handleChange(); - return; + object.state = "WAITING" + object.speed = 0 + object.handleChange() + return } if (object.state === "WAITING") { - object.state = "IDLE"; + object.state = "IDLE" } if (object.state === "IDLE") { - const target = this.route?.getNextFlag(); + const target = this.route?.getNextFlag() if (target) { - object.target = target; - object.state = "MOVING"; + object.target = target + object.state = "MOVING" } } if (object.state === "MOVING") { - object.speed = 0.5; - const isMoving = object.move(object.speed); - object.handleChange(); + object.speed = 0.5 + const isMoving = object.move(object.speed) + object.handleChange() if (!isMoving) { if ( object.target instanceof Flag && object.target.type === "WAGON_MOVEMENT" ) { - this.route?.removeFlag(object.target); - object.target = undefined; - object.state = "IDLE"; - object.speed = 0; + this.route?.removeFlag(object.target) + object.target = undefined + object.state = "IDLE" + object.speed = 0 } } } - object.live(); + object.live() } updatePlayer(object: Player) { - object.live(); + object.live() if (object.state === "IDLE") { - const random = getRandomInRange(1, 120); + const random = getRandomInRange(1, 120) if (random <= 1) { - const randObj = this.findRandomNearWagonFlag(); + const randObj = this.findRandomNearWagonFlag() if (!randObj) { - return; + return } - object.setTarget(randObj); + object.setTarget(randObj) } } } updateRabbit(object: Rabbit) { - object.live(); + object.live() if (object.state === "IDLE") { - const random = getRandomInRange(1, 100); + const random = getRandomInRange(1, 100) if (random <= 1) { - const randomObj = this.findRandomMovementFlag(); + const randomObj = this.findRandomMovementFlag() if (!randomObj) { - return; + return } - object.setTarget(randomObj); + object.setTarget(randomObj) } } } updateWolf(object: Wolf) { - object.live(); + object.live() if (object.state === "IDLE") { - const random = getRandomInRange(1, 100); + const random = getRandomInRange(1, 100) if (random <= 1) { - const randomObj = this.findRandomMovementFlag(); + const randomObj = this.findRandomMovementFlag() if (!randomObj) { - return; + return } - object.setTarget(randomObj); + object.setTarget(randomObj) } } } updateRaider(object: Raider) { - object.live(); + object.live() if (object.state === "IDLE") { - const random = getRandomInRange(1, 100); + const random = getRandomInRange(1, 100) if (random <= 1) { - const randomObj = this.findRandomMovementFlag(); + const randomObj = this.findRandomMovementFlag() if (!randomObj) { - return; + return } - object.setTarget(randomObj); + object.setTarget(randomObj) } } if (object.state === "MOVING") { - const isMoving = object.move(1); + const isMoving = object.move(1) if (!isMoving) { if (object.target?.id === "SPAWN_RIGHT") { // Destroy - const index = this.objects.indexOf(object); - this.objects.splice(index, 1); + const index = this.objects.indexOf(object) + this.objects.splice(index, 1) } - object.state = "IDLE"; - return; + object.state = "IDLE" + return } } } getAvailableCommands() { - const commands: string[] = []; + const commands: string[] = [] for (const action of this.possibleActions) { if (action === "HELP") { - commands.push("!помощь"); + commands.push("!помощь") } if (action === "REFUEL") { - commands.push("!заправить [кол-во]"); + commands.push("!заправить [кол-во]") } if (action === "CHOP") { - commands.push("!рубить"); + commands.push("!рубить") } if (action === "MINE") { - commands.push("!добыть"); + commands.push("!добыть") } if (action === "BUY") { - commands.push("!купить [название]"); + commands.push("!купить [название]") } if (action === "SELL") { - commands.push("!продать [название]"); + commands.push("!продать [название]") } if (action === "GIFT") { - commands.push("!подарить [название]"); + commands.push("!подарить [название]") } if (action === "DONATE") { - commands.push("!донат"); + commands.push("!донат") } } - return commands; + return commands } async findOrCreatePlayer(id: string) { - const player = this.findPlayer(id); + const player = this.findPlayer(id) if (!player && this.checkIfActionIsPossible("CREATE_NEW_PLAYER")) { - return this.createPlayer(id); + return this.createPlayer(id) } - return player; + return player } public findPlayer(id: string) { - const player = this.objects.find((p) => p.id === id); + const player = this.objects.find((p) => p.id === id) if (player instanceof Player) { - return player; + return player } } async initPlayer(id: string) { - const instance = new Player({ id }); - await instance.init(); - await instance.initInventoryFromDB(); + const instance = new Player({ id }) + await instance.init() + await instance.initInventoryFromDB() - const wagon = this.getWagon(); + const wagon = this.getWagon() if (wagon) { - instance.x = wagon.x - 250; - instance.y = wagon.y; + instance.x = wagon.x - 250 + instance.y = wagon.y } - return instance; + return instance } public async createPlayer(id: string): Promise { - const player = this.findPlayer(id); + const player = this.findPlayer(id) if (!player) { - const instance = await this.initPlayer(id); - this.objects.push(instance); - return instance; + const instance = await this.initPlayer(id) + this.objects.push(instance) + return instance } - return player; + return player } async refuelAction(player: Player, params?: string[]) { @@ -519,65 +519,68 @@ export class GameScene { return { ok: false, message: "Сейчас этого сделать нельзя.", - }; + } } if (!params) { return { ok: false, message: "Не указана цель.", - }; + } } - const count = this.getCountFromChatCommand(params[0]); + const count = this.getCountFromChatCommand(params[0]) if (!count) { return { ok: false, message: "Неверно указано количество.", - }; + } } - const items = player.inventory?.items ?? []; - const itemExist = items.find((item) => item.type === "WOOD"); + const items = player.inventory?.items ?? [] + const itemExist = items.find((item) => item.type === "WOOD") if (!itemExist) { return { ok: false, message: `${player.userName}, у тебя нет древесины.`, - }; + } } - const isSuccess = await player.inventory?.reduceOrDestroyItem(itemExist.type, count); + const isSuccess = await player.inventory?.reduceOrDestroyItem( + itemExist.type, + count, + ) if (!isSuccess) { return { ok: false, message: `${player.userName}, недостаточно древесины.`, - }; + } } - await player.addRefuellerPoints(count); + await player.addRefuellerPoints(count) - this.refuelWagon(count); + this.refuelWagon(count) return { ok: true, message: `${player.userName}, ты помог заправить Машину.`, - }; + } } async stealFuelAction(playerId: string) { - this.emptyWagonFuel(); + this.emptyWagonFuel() - const player = await this.findOrCreatePlayer(playerId); + const player = await this.findOrCreatePlayer(playerId) if (!player) { - return; + return } - await player.addVillainPoints(1); + await player.addVillainPoints(1) return { ok: true, message: `${player.userName}, а ты Злодей!`, - }; + } } async chopAction(player: Player) { @@ -585,29 +588,29 @@ export class GameScene { return { ok: false, message: "Сейчас этого сделать нельзя.", - }; + } } if (player.state === "CHOPPING") { return { ok: false, message: `${player.userName}, ты пока занят(а).`, - }; + } } - const tree = this.getTreeToChop(); + const tree = this.getTreeToChop() if (!tree) { return { ok: false, message: `${player.userName}, нет свободного дерева.`, - }; + } } - player.setTarget(tree); + player.setTarget(tree) return { ok: true, message: null, - }; + } } async mineAction(player: Player) { @@ -615,29 +618,29 @@ export class GameScene { return { ok: false, message: "Сейчас этого сделать нельзя.", - }; + } } if (player.state === "MINING") { return { ok: false, message: `${player.userName}, ты пока занят(а).`, - }; + } } - const stone = this.getStoneToMine(); + const stone = this.getStoneToMine() if (!stone) { return { ok: false, message: `${player.userName}, нет свободного камня.`, - }; + } } - player.setTarget(stone); + player.setTarget(stone) return { ok: true, message: null, - }; + } } disbandGroupAction() { @@ -645,16 +648,16 @@ export class GameScene { return { ok: false, message: "Сейчас этого сделать нельзя.", - }; + } } - this.group?.disband(); - this.group = undefined; + this.group?.disband() + this.group = undefined return { ok: true, message: "Группа расформирована!", - }; + } } startCreatingNewAdventureAction() { @@ -662,19 +665,19 @@ export class GameScene { return { ok: false, message: "Сейчас этого сделать нельзя.", - }; + } } this.initEvent({ type: "CREATING_NEW_ADVENTURE_STARTED", title: "Генерируем приключение", secondsToEnd: 15, - }); + }) return { ok: true, message: "Началось создание новых локаций...", - }; + } } startChangingSceneAction(_: Player, params?: string[]) { @@ -682,22 +685,22 @@ export class GameScene { return { ok: false, message: "Сейчас этого сделать нельзя.", - }; + } } if (!params) { return { ok: false, message: "Не указана цель.", - }; + } } - const scene = this.getSceneTypeFromChatCommand(params[1]); + const scene = this.getSceneTypeFromChatCommand(params[1]) if (!scene) { return { ok: false, message: "Неверно указана цель. В деревню, на защиту.", - }; + } } this.initEvent({ @@ -705,12 +708,12 @@ export class GameScene { title: "Меняем локацию", scene, secondsToEnd: 10, - }); + }) return { ok: true, message: "Переходим в другую локацию...", - }; + } } startGroupBuildAction(player: Player, params?: string[]) { @@ -718,56 +721,56 @@ export class GameScene { return { ok: false, message: "Сейчас этого сделать нельзя.", - }; + } } if (!params) { return { ok: false, message: "Не указана цель.", - }; + } } - const scene = this.getSceneTypeFromChatCommand(params[1]); + const scene = this.getSceneTypeFromChatCommand(params[1]) if (!scene) { return { ok: false, message: "Неверно указана цель. В деревню, на защиту.", - }; + } } - this.group = new Group({ creator: player, target: scene }); + this.group = new Group({ creator: player, target: scene }) this.initEvent({ type: "GROUP_FORM_STARTED", title: "Идет набор в группу!", scene, secondsToEnd: 120, - }); + }) return { ok: true, message: "Начинаем собирать группу!", - }; + } } getSceneTypeFromChatCommand(text: string): GameSceneType | null { if (text === "деревня" || text === "деревню") { - return "VILLAGE"; + return "VILLAGE" } if (text === "защиту" || text === "защита") { - return "DEFENCE"; + return "DEFENCE" } - return null; + return null } getCountFromChatCommand(text: string): number | null { if (typeof Number(text) === "number") { - return Number(text); + return Number(text) } - return null; + return null } joinGroupAction(player: Player) { @@ -775,38 +778,38 @@ export class GameScene { return { ok: false, message: "Сейчас этого сделать нельзя.", - }; + } } if (!this.group) { return { ok: false, message: "Нет группы.", - }; + } } - const joined = this.group.join(player); + const joined = this.group.join(player) if (!joined) { return { ok: false, message: "Ты уже в группе.", - }; + } } return { ok: true, message: `${player.userName}, ты вступил(а) в группу!`, - }; + } } refuelWagon(woodAmount: number) { - const wagon = this.getWagon(); - wagon.fuel += woodAmount * 5 * 40; + const wagon = this.getWagon() + wagon.fuel += woodAmount * 5 * 40 } emptyWagonFuel() { - const wagon = this.getWagon(); - wagon.fuel = 0; + const wagon = this.getWagon() + wagon.fuel = 0 } getTreeToChop() { @@ -817,10 +820,10 @@ export class GameScene { obj.state !== "DESTROYED" && !obj.isReserved && obj.isOnWagonPath, - ); + ) if (onlyOnPath && onlyOnPath.length > 0) { - const wagon = this.getWagon(); - return this.determineNearestObject(wagon, onlyOnPath) as Tree; + const wagon = this.getWagon() + return this.determineNearestObject(wagon, onlyOnPath) as Tree } // Part 2: Check nearest free tree @@ -830,10 +833,10 @@ export class GameScene { obj.state !== "DESTROYED" && !obj.isReserved && obj.isReadyToChop, - ); + ) if (other && other.length > 0) { - const wagon = this.getWagon(); - return this.determineNearestObject(wagon, other) as Tree; + const wagon = this.getWagon() + return this.determineNearestObject(wagon, other) as Tree } } @@ -845,49 +848,47 @@ export class GameScene { obj.state !== "DESTROYED" && !obj.isReserved && obj.isOnWagonPath, - ); + ) if (onlyOnPath && onlyOnPath.length > 0) { - const wagon = this.getWagon(); - return this.determineNearestObject(wagon, onlyOnPath) as Stone; + const wagon = this.getWagon() + return this.determineNearestObject(wagon, onlyOnPath) as Stone } // Part 2: Check nearest free const other = this.chunkNow?.objects.filter( (obj) => - obj instanceof Stone && - obj.state !== "DESTROYED" && - !obj.isReserved, - ); + obj instanceof Stone && obj.state !== "DESTROYED" && !obj.isReserved, + ) if (other && other.length > 0) { - const wagon = this.getWagon(); - return this.determineNearestObject(wagon, other) as Stone; + const wagon = this.getWagon() + return this.determineNearestObject(wagon, other) as Stone } } determineNearestObject( point: { - x: number; - y: number; + x: number + y: number }, objects: GameObject[], ) { - let closestObject = objects[0]; - let shortestDistance = undefined; + let closestObject = objects[0] + let shortestDistance = undefined for (const object of objects) { - const distance = Route.getDistanceBetween2Points(point, object); + const distance = Route.getDistanceBetween2Points(point, object) if (!shortestDistance || distance < shortestDistance) { - shortestDistance = distance; - closestObject = object; + shortestDistance = distance + closestObject = object } } - return closestObject; + return closestObject } initRaiders(count: number) { for (let i = 0; i < count; i++) { - this.objects.push(new Raider()); + this.objects.push(new Raider()) } } @@ -896,24 +897,24 @@ export class GameScene { title: "Начался рейд!", type: "RAID_STARTED", secondsToEnd: 60 * 10, - }); - this.initRaiders(raidersCount); + }) + this.initRaiders(raidersCount) return { ok: true, message: null, - }; + } } public stopRaid() { - const flag = this.findSpawnFlag("SPAWN_RIGHT"); + const flag = this.findSpawnFlag("SPAWN_RIGHT") if (!flag) { - return; + return } for (const obj of this.objects) { if (obj instanceof Raider) { - obj.moveOutOfScene(flag); + obj.moveOutOfScene(flag) } } } @@ -923,12 +924,12 @@ export class GameScene { return { ok: false, message: null, - }; + } } return { ok: true, message: `${player.userName}, это интерактивная игра-чат, в которой может участвовать любой зритель! Пиши команды (примеры на экране) для управления своим героем. Вступай в наше комьюнити: ${DISCORD_SERVER_INVITE_URL}`, - }; + } } public donateAction(player: Player) { @@ -936,12 +937,12 @@ export class GameScene { return { ok: false, message: null, - }; + } } return { ok: true, message: `${player.userName}, поддержи игру: ${DONATE_URL}`, - }; + } } public async giftAction(player: Player, params: string[] | undefined) { @@ -949,67 +950,67 @@ export class GameScene { return { ok: false, message: null, - }; + } } if (!params) { return { ok: false, message: `${player.userName}, укажи конкретнее, например: !подарить древесину`, - }; + } } - const item = this.getItemTypeFromChatCommand(params[0]); + const item = this.getItemTypeFromChatCommand(params[0]) if (!item) { return { ok: false, message: `${player.userName}, укажи конкретнее, например: !подарить древесину`, - }; + } } - const items = player.inventory?.items ?? []; + const items = player.inventory?.items ?? [] if (item === "WOOD") { - const itemExist = items.find((item) => item.type === "WOOD"); + const itemExist = items.find((item) => item.type === "WOOD") if (!itemExist) { return { ok: false, message: `${player.userName}, у тебя нет древесины.`, - }; + } } - await this.game.repository.addWoodToVillage(itemExist.amount); - await player.addReputation(itemExist.amount); - await player.inventory?.destroyItemInDB(itemExist.id); + await this.game.repository.addWoodToVillage(itemExist.amount) + await player.addReputation(itemExist.amount) + await player.inventory?.destroyItemInDB(itemExist.id) return { ok: true, message: `${player.userName}, ты подарил(а) деревне всю древесину! Твоя репутация возросла.`, - }; + } } if (item === "STONE") { - const itemExist = items.find((item) => item.type === "STONE"); + const itemExist = items.find((item) => item.type === "STONE") if (!itemExist) { return { ok: false, message: `${player.userName}, у тебя нет камня.`, - }; + } } - await this.game.repository.addStoneToVillage(itemExist.amount); - await player.addReputation(itemExist.amount); - await player.inventory?.destroyItemInDB(itemExist.id); + await this.game.repository.addStoneToVillage(itemExist.amount) + await player.addReputation(itemExist.amount) + await player.inventory?.destroyItemInDB(itemExist.id) return { ok: true, message: `${player.userName}, ты подарил(а) деревне все камни! Твоя репутация возросла.`, - }; + } } return { ok: false, message: `${player.userName}, укажи конкретнее, например: !подарить древесину`, - }; + } } async sellAction(player: Player, params: string[] | undefined) { @@ -1017,65 +1018,65 @@ export class GameScene { return { ok: false, message: null, - }; + } } if (!params) { return { ok: false, message: `${player.userName}, укажи конкретнее, например: !продать древесину`, - }; + } } - const item = this.getItemTypeFromChatCommand(params[0]); + const item = this.getItemTypeFromChatCommand(params[0]) if (!item) { return { ok: false, message: `${player.userName}, укажи конкретнее, например: !продать древесину`, - }; + } } - const items = player.inventory?.items ?? []; + const items = player.inventory?.items ?? [] if (item === "WOOD") { - const itemExist = items.find((item) => item.type === "WOOD"); + const itemExist = items.find((item) => item.type === "WOOD") if (!itemExist) { return { ok: false, message: `${player.userName}, у тебя нет древесины.`, - }; + } } - await player.updateCoins(itemExist.amount); - await player.inventory?.destroyItemInDB(itemExist.id); + await player.updateCoins(itemExist.amount) + await player.inventory?.destroyItemInDB(itemExist.id) return { ok: true, message: `${player.userName}, ты продал(а) всю древесину торговцу!`, - }; + } } if (item === "STONE") { - const itemExist = items.find((item) => item.type === "STONE"); + const itemExist = items.find((item) => item.type === "STONE") if (!itemExist) { return { ok: false, message: `${player.userName}, у тебя нет камня.`, - }; + } } - await player.updateCoins(itemExist.amount); - await player.inventory?.destroyItemInDB(itemExist.id); + await player.updateCoins(itemExist.amount) + await player.inventory?.destroyItemInDB(itemExist.id) return { ok: true, message: `${player.userName}, ты продал(а) все камни торговцу!`, - }; + } } return { ok: false, message: `${player.userName}, укажи конкретнее, например: !продать древесину`, - }; + } } async buyAction(player: Player, params: string[] | undefined) { @@ -1083,163 +1084,163 @@ export class GameScene { return { ok: false, message: null, - }; + } } if (!params) { return { ok: false, message: `${player.userName}, укажи конкретнее, например: !купить топор`, - }; + } } - const item = this.getItemTypeFromChatCommand(params[0]); + const item = this.getItemTypeFromChatCommand(params[0]) if (!item) { return { ok: false, message: `${player.userName}, укажи конкретнее, например: !купить топор`, - }; + } } - const items = player.inventory?.items ?? []; + const items = player.inventory?.items ?? [] if (item === "AXE") { - const itemExist = items.find((item) => item.type === "AXE"); + const itemExist = items.find((item) => item.type === "AXE") if (itemExist) { return { ok: false, message: `${player.userName}, у тебя уже есть топор.`, - }; + } } - const result = await player.buyItemFromDealer("AXE", 10, 1); + const result = await player.buyItemFromDealer("AXE", 10, 1) if (!result) { return { ok: false, message: `${player.userName}, неа.`, - }; + } } return { ok: true, message: `${player.userName}, ты купил(а) топор у торговца!`, - }; + } } if (item === "PICKAXE") { - const itemExist = items.find((item) => item.type === "PICKAXE"); + const itemExist = items.find((item) => item.type === "PICKAXE") if (itemExist) { return { ok: false, message: `${player.userName}, у тебя уже есть кирка.`, - }; + } } - const result = await player.buyItemFromDealer("PICKAXE", 10, 1); + const result = await player.buyItemFromDealer("PICKAXE", 10, 1) if (!result) { return { ok: false, message: `${player.userName}, неа.`, - }; + } } return { ok: true, message: `${player.userName}, ты купил(а) кирку у торговца!`, - }; + } } return { ok: false, message: `${player.userName}, укажи конкретнее, например: !купить топор`, - }; + } } getItemTypeFromChatCommand(text: string): ItemType | null { if (text === "древесину" || text === "древесина") { - return "WOOD"; + return "WOOD" } if (text === "камень" || text === "камни") { - return "STONE"; + return "STONE" } if (text === "топор") { - return "AXE"; + return "AXE" } if (text === "кирка" || text === "кирку") { - return "PICKAXE"; + return "PICKAXE" } - return null; + return null } generateRandomVillage({ - center, - width, - height, - theme - }: { - center: { x: number; y: number }; - width: number; - height: number; - theme: IGameChunkTheme; + center, + width, + height, + theme, + }: { + center: { x: number; y: number } + width: number + height: number + theme: IGameChunkTheme }) { - const village = new Village({ width, height, center, theme }); - this.chunks.push(village); - return village; + const village = new Village({ width, height, center, theme }) + this.chunks.push(village) + return village } generateRandomForest({ - center, - width, - height, - }: { - center: { x: number; y: number }; - width: number; - height: number; + center, + width, + height, + }: { + center: { x: number; y: number } + width: number + height: number }) { - const forest = new Forest({ width, height, center }); - this.chunks.push(forest); - return forest; + const forest = new Forest({ width, height, center }) + this.chunks.push(forest) + return forest } generateRandomLake({ - center, - width, - height, - }: { - center: { x: number; y: number }; - width: number; - height: number; + center, + width, + height, + }: { + center: { x: number; y: number } + width: number + height: number }) { - const lake = new LakeChunk({ width, height, center }); - this.chunks.push(lake); - return lake; + const lake = new LakeChunk({ width, height, center }) + this.chunks.push(lake) + return lake } generateAdventure(village: Village) { - const wagonStartPoint = village.getWagonStopPoint(); - const villageOutPoint = village.getRandomOutPointOnRight(); + const wagonStartPoint = village.getWagonStopPoint() + const villageOutPoint = village.getRandomOutPointOnRight() - this.route = new Route(); - this.route.addGlobalFlag(wagonStartPoint); - this.route.startPoint = wagonStartPoint; - this.route.addChunk(village); + this.route = new Route() + this.route.addGlobalFlag(wagonStartPoint) + this.route.startPoint = wagonStartPoint + this.route.addChunk(village) - this.generateChunks({ x: villageOutPoint.x, y: villageOutPoint.y }, 3); - this.markObjectsAsOnWagonPath(this.route); + this.generateChunks({ x: villageOutPoint.x, y: villageOutPoint.y }, 3) + this.markObjectsAsOnWagonPath(this.route) } generateChunks(startPoint: { x: number; y: number }, amount: number) { - let outPoint = startPoint; + let outPoint = startPoint for (let i = 1; i <= amount; i++) { - const chunk = this.generateRandomChunk(outPoint); + const chunk = this.generateRandomChunk(outPoint) if (!chunk) { - continue; + continue } - outPoint = chunk.getRandomOutPointOnRight(); - this.route?.addGlobalFlag(outPoint); - this.route?.addChunk(chunk); + outPoint = chunk.getRandomOutPointOnRight() + this.route?.addGlobalFlag(outPoint) + this.route?.addChunk(chunk) } // Generate last chunk @@ -1247,23 +1248,23 @@ export class GameScene { center: { x: outPoint.x + 2500 / 2, y: outPoint.y }, width: 2500, height: 2000, - theme: "GREEN" - }); - const stopPoint = finalVillage.getWagonStopPoint(); - this.route?.addGlobalFlag(stopPoint); - this.route?.addChunk(finalVillage); - this.route?.setEndPoint(stopPoint); + theme: "GREEN", + }) + const stopPoint = finalVillage.getWagonStopPoint() + this.route?.addGlobalFlag(stopPoint) + this.route?.addChunk(finalVillage) + this.route?.setEndPoint(stopPoint) } generateRandomChunk(startPoint: { x: number; y: number }) { - const random = getRandomInRange(1, 2); + const random = getRandomInRange(1, 2) - const width = getRandomInRange(1500, 2500); - const height = getRandomInRange(2200, 3000); + const width = getRandomInRange(1500, 2500) + const height = getRandomInRange(2200, 3000) const center = { x: startPoint.x + width / 2, y: startPoint.y, - }; + } switch (random) { case 1: @@ -1279,7 +1280,7 @@ export class GameScene { height: height, }) default: - return undefined; + return undefined } } @@ -1290,9 +1291,9 @@ export class GameScene { const isOnPath = route.checkIfPointIsOnWagonPath({ x: object.x, y: object.y, - }); + }) if (isOnPath) { - object.isOnWagonPath = true; + object.isOnWagonPath = true } } } @@ -1300,30 +1301,30 @@ export class GameScene { } findRandomNearWagonFlag() { - const wagon = this.getWagon(); + const wagon = this.getWagon() if (!wagon) { - return undefined; + return undefined } - return wagon.nearFlags[Math.floor(Math.random() * wagon.nearFlags.length)]; + return wagon.nearFlags[Math.floor(Math.random() * wagon.nearFlags.length)] } findRandomMovementFlag() { const flags = this.objects.filter( (f) => f instanceof Flag && f.type === "MOVEMENT", - ); + ) return flags.length > 0 ? flags[Math.floor(Math.random() * flags.length)] - : undefined; + : undefined } findRandomEmptyResourceFlag() { const flags = this.objects.filter( (f) => f instanceof Flag && f.type === "RESOURCE" && !f.target, - ); + ) return flags.length > 0 ? flags[Math.floor(Math.random() * flags.length)] - : undefined; + : undefined } initSpawnFlags() { @@ -1332,17 +1333,17 @@ export class GameScene { y: 620, id: "SPAWN_LEFT", type: "SPAWN_LEFT", - }); + }) const spawnRightFlag = new Flag({ x: 2700, y: 620, id: "SPAWN_RIGHT", type: "SPAWN_RIGHT", - }); - this.objects.push(spawnLeftFlag, spawnRightFlag); + }) + this.objects.push(spawnLeftFlag, spawnRightFlag) } findSpawnFlag(id: "SPAWN_LEFT" | "SPAWN_RIGHT") { - return this.objects.find((f) => f.id === id); + return this.objects.find((f) => f.id === id) } } diff --git a/apps/api/src/game/scenes/index.ts b/apps/api/src/game/scenes/index.ts index d3409e76..f31f4a72 100644 --- a/apps/api/src/game/scenes/index.ts +++ b/apps/api/src/game/scenes/index.ts @@ -1,4 +1,4 @@ -export { GameScene } from "./gameScene"; -export { VillageScene } from "./villageScene"; -export { DefenceScene } from "./defenceScene"; -export { MovingScene } from "./movingScene"; +export { GameScene } from "./gameScene" +export { VillageScene } from "./villageScene" +export { DefenceScene } from "./defenceScene" +export { MovingScene } from "./movingScene" diff --git a/apps/api/src/game/scenes/movingScene.ts b/apps/api/src/game/scenes/movingScene.ts index 87ea7578..2241ea91 100644 --- a/apps/api/src/game/scenes/movingScene.ts +++ b/apps/api/src/game/scenes/movingScene.ts @@ -1,11 +1,11 @@ -import type { Group } from "../common"; -import type { Game } from "../game"; -import { Wagon } from "../objects"; -import { GameScene } from "./gameScene"; +import type { Group } from "../common" +import type { Game } from "../game" +import { Wagon } from "../objects" +import { GameScene } from "./gameScene" interface IMovingSceneOptions { - game: Game; - group: Group | undefined; + game: Game + group: Group | undefined } export class MovingScene extends GameScene { @@ -26,19 +26,19 @@ export class MovingScene extends GameScene { "CREATE_NEW_PLAYER", "START_CREATING_NEW_ADVENTURE", ], - }); + }) - void this.init(); + void this.init() } public async init() { - const village = this.initStartingVillage(); - const wagonStartPoint = village.getWagonStopPoint(); + const village = this.initStartingVillage() + const wagonStartPoint = village.getWagonStopPoint() - this.initWagon(wagonStartPoint); - await this.initGroupPlayers(); + this.initWagon(wagonStartPoint) + await this.initGroupPlayers() - void this.play(); + void this.play() } initStartingVillage() { @@ -49,28 +49,28 @@ export class MovingScene extends GameScene { x: Math.round(2500 / 2), y: Math.round(2000 / 2), }, - }; + } return this.generateRandomVillage({ center: area.center, width: area.width, height: area.height, - theme: "GREEN" - }); + theme: "GREEN", + }) } async initGroupPlayers() { if (!this.group) { - return; + return } for (const player of this.group.players) { - const instance = await this.initPlayer(player.id); - this.objects.push(instance); + const instance = await this.initPlayer(player.id) + this.objects.push(instance) } } initWagon({ x, y }: { x: number; y: number }) { - const wagon = new Wagon({ x, y }); - this.objects.push(wagon); + const wagon = new Wagon({ x, y }) + this.objects.push(wagon) } } diff --git a/apps/api/src/game/scenes/villageScene.ts b/apps/api/src/game/scenes/villageScene.ts index 59638dcb..8d7f9b70 100644 --- a/apps/api/src/game/scenes/villageScene.ts +++ b/apps/api/src/game/scenes/villageScene.ts @@ -1,11 +1,11 @@ -import type { Group } from "../common"; -import type { Game } from "../game"; -import { Rabbit, Wolf } from "../objects"; -import { GameScene } from "./gameScene"; +import type { Group } from "../common" +import type { Game } from "../game" +import { Rabbit, Wolf } from "../objects" +import { GameScene } from "./gameScene" interface IVillageSceneOptions { - game: Game; - group: Group | undefined; + game: Game + group: Group | undefined } export class VillageScene extends GameScene { @@ -27,39 +27,39 @@ export class VillageScene extends GameScene { "START_CHANGING_SCENE", "CREATE_NEW_PLAYER", ], - }); + }) - void this.init(); + void this.init() } public async init() { - await this.initGroupPlayers(); - this.initRabbits(8); - this.initWolfs(4); + await this.initGroupPlayers() + this.initRabbits(8) + this.initWolfs(4) - void this.play(); + void this.play() } async initGroupPlayers() { if (!this.group) { - return; + return } for (const player of this.group.players) { - const instance = await this.initPlayer(player.id); - this.objects.push(instance); + const instance = await this.initPlayer(player.id) + this.objects.push(instance) } } private initRabbits(count: number) { for (let i = 0; i < count; i++) { - this.objects.push(new Rabbit()); + this.objects.push(new Rabbit()) } } private initWolfs(count: number) { for (let i = 0; i < count; i++) { - this.objects.push(new Wolf()); + this.objects.push(new Wolf()) } } } diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 04d853a5..d413b402 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -1,37 +1,37 @@ -import { Hono } from "hono"; -import { cors } from "hono/cors"; -import { BotController } from "./bot/bot.controller"; -import { Game } from "./game/game"; +import { Hono } from "hono" +import { cors } from "hono/cors" +import { BotController } from "./bot/bot.controller" +import { Game } from "./game/game" // Go-go! -const game = new Game(); +const game = new Game() -const app = new Hono(); +const app = new Hono() -app.use("/*", cors()); +app.use("/*", cors()) app.get("/players/top", async (c) => { - const players = await game.repository.findTopPlayers(); - return c.json(players); -}); + const players = await game.repository.findTopPlayers() + return c.json(players) +}) app.get("/village", async (c) => { - const village = await game.repository.findVillage(); - return c.json(village); -}); + const village = await game.repository.findVillage() + return c.json(village) +}) app.get("/scene", (c) => { - const scene = game.scene.getInfo(); - return c.json(scene); -}); + const scene = game.scene.getInfo() + return c.json(scene) +}) -const port = 4001; -console.log(`HTTP server: listening on localhost:${port}`); +const port = 4001 +console.log(`HTTP server: listening on localhost:${port}`) // Getting messages from Chat and reacting to them -void new BotController(game).serve(); +void new BotController(game).serve() export default { port, fetch: app.fetch, -}; +} diff --git a/apps/api/src/websocket/websocket.server.ts b/apps/api/src/websocket/websocket.server.ts index db55eeeb..a777a3b1 100644 --- a/apps/api/src/websocket/websocket.server.ts +++ b/apps/api/src/websocket/websocket.server.ts @@ -1,5 +1,5 @@ -import { createId } from "@paralleldrive/cuid2"; -import type { WebSocketMessage } from "../../../../packages/api-sdk/src"; +import { createId } from "@paralleldrive/cuid2" +import type { WebSocketMessage } from "../../../../packages/api-sdk/src" export const server = Bun.serve({ port: 4002, @@ -7,14 +7,14 @@ export const server = Bun.serve({ // const cookies = req.headers.get("cookie"); // const username = getUsernameFromCookies(cookies); //const success = server.upgrade(req, { data: { username: '123' } }); - if (server.upgrade(req)) return undefined; + if (server.upgrade(req)) return undefined - return new Response("Hello world"); + return new Response("Hello world") }, websocket: { open(ws) { - ws.subscribe("game"); - console.log("smb connected"); + ws.subscribe("game") + console.log("smb connected") }, message() { //const action = MessageController.parseMessage(message.toString()); @@ -25,16 +25,16 @@ export const server = Bun.serve({ // server.publish("game", `${message}`); }, close(ws) { - ws.unsubscribe("game"); + ws.unsubscribe("game") }, }, -}); +}) export function sendMessage( event: WebSocketMessage["event"], object?: WebSocketMessage["object"], ) { - server.publish("game", JSON.stringify({ id: createId(), event, object })); + server.publish("game", JSON.stringify({ id: createId(), event, object })) } -console.log(`WebSocket server: listening on ${server.hostname}:${server.port}`); +console.log(`WebSocket server: listening on ${server.hostname}:${server.port}`) diff --git a/apps/client/src/components/chunkBlock.tsx b/apps/client/src/components/chunkBlock.tsx index 9d2597e4..7e794582 100644 --- a/apps/client/src/components/chunkBlock.tsx +++ b/apps/client/src/components/chunkBlock.tsx @@ -1,31 +1,30 @@ -import type { IGameChunk } from "../../../../packages/api-sdk/src"; +import type { IGameChunk } from "../../../../packages/api-sdk/src" export const ChunkBlock = ({ - chunk, - }: { - chunk: IGameChunk | null | undefined; + chunk, +}: { + chunk: IGameChunk | null | undefined }) => { if (!chunk) { - return null; + return null } - const description = getChunkTypeDescription(chunk.type); + const description = getChunkTypeDescription(chunk.type) return ( -
+

{description}

{chunk.title}

- ); -}; + ) +} function getChunkTypeDescription(type: IGameChunk["type"]) { if (type === "VILLAGE") { - return "Деревня"; + return "Деревня" } if (type === "FOREST") { - return "Лес"; + return "Лес" } if (type === "LAKE") { return "Озеро" diff --git a/apps/client/src/components/dealer.tsx b/apps/client/src/components/dealer.tsx index cfc18d96..eda4ea30 100644 --- a/apps/client/src/components/dealer.tsx +++ b/apps/client/src/components/dealer.tsx @@ -1,23 +1,23 @@ -import type { ItemType } from "../../../../packages/api-sdk/src"; +import type { ItemType } from "../../../../packages/api-sdk/src" interface Dealer { - x: number; - y: number; + x: number + y: number } interface Deal { - command: string; - type: "SELL" | "BUY"; - item: ItemType; - amount: number; - price: number; - isOver?: boolean; + command: string + type: "SELL" | "BUY" + item: ItemType + amount: number + price: number + isOver?: boolean } export const DealerBlock = ({ dealer }: { dealer: Dealer }) => { - const size = 100; - const height = (size * 64) / 100; - const width = height; + const size = 100 + const height = (size * 64) / 100 + const width = height return (
{
-
+
Торговец
- ); -}; + ) +} const DealBlock = ({ - deal, - }: { - deal: Deal; + deal, +}: { + deal: Deal }) => { - const item = getDealItem(deal.item, deal.amount); + const item = getDealItem(deal.item, deal.amount) return (

{deal.price}

-
+
- ); -}; + ) +} function getDealItem(type: ItemType, amount: number) { if (type === "WOOD") { return (
- -
+ +
{amount}
- ); + ) } if (type === "STONE") { return ( @@ -138,19 +135,18 @@ function getDealItem(type: ItemType, amount: number) { alt="" className="mx-auto w-12 h-auto" /> -
+
{amount}
- ); + ) } if (type === "AXE") { return (
- +
- ); + ) } if (type === "PICKAXE") { return ( @@ -161,6 +157,6 @@ function getDealItem(type: ItemType, amount: number) { className="-ml-2 w-18 h-auto" />
- ); + ) } } diff --git a/apps/client/src/components/eventCard.tsx b/apps/client/src/components/eventCard.tsx index 16ea8bec..4d61a42d 100644 --- a/apps/client/src/components/eventCard.tsx +++ b/apps/client/src/components/eventCard.tsx @@ -1,27 +1,26 @@ -import type { IGameEvent } from "../../../../packages/api-sdk/src"; -import { useCountdown } from "../hooks/useCountdown"; +import type { IGameEvent } from "../../../../packages/api-sdk/src" +import { useCountdown } from "../hooks/useCountdown" export const EventCard = ({ event }: { event: IGameEvent }) => { - const [_days, _hours, minutes, seconds] = useCountdown(event.endsAt); + const [_days, _hours, minutes, seconds] = useCountdown(event.endsAt) - let secondsWithZero: string = seconds.toString(); + let secondsWithZero: string = seconds.toString() if (seconds < 10) { - secondsWithZero = `0${seconds}`; + secondsWithZero = `0${seconds}` } - const description = getEventDescriptionByType(event.type); + const description = getEventDescriptionByType(event.type) return ( -
+

{event.title}

{description}

Заканчивается через {minutes}:{secondsWithZero}

- ); -}; + ) +} function getEventDescriptionByType(type: IGameEvent["type"]) { if (type === "GROUP_FORM_STARTED") { @@ -32,6 +31,6 @@ function getEventDescriptionByType(type: IGameEvent["type"]) {

!го

- ); + ) } } diff --git a/apps/client/src/components/eventsBlock.tsx b/apps/client/src/components/eventsBlock.tsx index 3866e110..225b6ef6 100644 --- a/apps/client/src/components/eventsBlock.tsx +++ b/apps/client/src/components/eventsBlock.tsx @@ -1,18 +1,18 @@ -import type { IGameEvent } from "../../../../packages/api-sdk/src"; -import { EventCard } from "./eventCard"; +import type { IGameEvent } from "../../../../packages/api-sdk/src" +import { EventCard } from "./eventCard" export const EventsBlock = ({ events, }: { events: IGameEvent[] | undefined }) => { if (!events) { - return null; + return null } - const showEvents = events.map((e) => ); + const showEvents = events.map((e) => ) return (
{showEvents}
- ); -}; + ) +} diff --git a/apps/client/src/components/groupPlayerCard.tsx b/apps/client/src/components/groupPlayerCard.tsx index 021a74e8..045c36d4 100644 --- a/apps/client/src/components/groupPlayerCard.tsx +++ b/apps/client/src/components/groupPlayerCard.tsx @@ -1,19 +1,18 @@ -import type { IGameObjectPlayer } from "../../../../packages/api-sdk/src"; -import { PlayerFullBody } from "./player-full-body"; +import type { IGameObjectPlayer } from "../../../../packages/api-sdk/src" +import { PlayerFullBody } from "./player-full-body" export const GroupPlayerCard = ({ - player, - }: { - player: IGameObjectPlayer; + player, +}: { + player: IGameObjectPlayer }) => { return ( -
+
- +

{player.userName}

❤️ {player.health}

- ); -}; + ) +} diff --git a/apps/client/src/components/groupPlayers.tsx b/apps/client/src/components/groupPlayers.tsx index f71b8840..265a7007 100644 --- a/apps/client/src/components/groupPlayers.tsx +++ b/apps/client/src/components/groupPlayers.tsx @@ -1,26 +1,25 @@ -import type { IGameGroup } from "../../../../packages/api-sdk/src"; -import { GroupPlayerCard } from "./groupPlayerCard"; +import type { IGameGroup } from "../../../../packages/api-sdk/src" +import { GroupPlayerCard } from "./groupPlayerCard" export const GroupPlayersBlock = ({ - group, - }: { group: IGameGroup | undefined }) => { + group, +}: { group: IGameGroup | undefined }) => { if (!group) { - return null; + return null } const showPlayers = group.players.map((p) => ( - - )); + + )) return (
-
+
Группа
{showPlayers}
- ); -}; + ) +} diff --git a/apps/client/src/components/interface.tsx b/apps/client/src/components/interface.tsx index ec113ab0..34bfba8d 100644 --- a/apps/client/src/components/interface.tsx +++ b/apps/client/src/components/interface.tsx @@ -1,73 +1,72 @@ -import { useEffect, useState } from "react"; -import { useScene } from "../hooks/useScene"; -import { ChunkBlock } from "./chunkBlock"; -import { EventsBlock } from "./eventsBlock"; -import { GroupPlayersBlock } from "./groupPlayers"; -import { Loader } from "./loader"; -import { TopPlayersBlock } from "./topPlayers"; -import { WagonStatsBlock } from "./wagonStatsBlock"; -import { RouteBlock } from "./routeBlock"; +import { useEffect, useState } from "react" +import { useScene } from "../hooks/useScene" +import { ChunkBlock } from "./chunkBlock" +import { EventsBlock } from "./eventsBlock" +import { GroupPlayersBlock } from "./groupPlayers" +import { Loader } from "./loader" +import { RouteBlock } from "./routeBlock" +import { TopPlayersBlock } from "./topPlayers" +import { WagonStatsBlock } from "./wagonStatsBlock" export const InterfaceLayer = () => { - const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); + const [mousePos, setMousePos] = useState({ x: 0, y: 0 }) useEffect(() => { const handleMouseMove = (event: { clientX: number; clientY: number }) => { - setMousePos({ x: event.clientX, y: event.clientY }); - }; + setMousePos({ x: event.clientX, y: event.clientY }) + } - window.addEventListener("mousemove", handleMouseMove); + window.addEventListener("mousemove", handleMouseMove) return () => { - window.removeEventListener("mousemove", handleMouseMove); - }; - }, []); + window.removeEventListener("mousemove", handleMouseMove) + } + }, []) - const scene = useScene(); + const scene = useScene() const showCommands = scene?.commands?.map((command) => (

{command}

- )); + )) - const [showLoader, setShowLoader] = useState(false); + const [showLoader, setShowLoader] = useState(false) useEffect(() => { if (!scene?.id) { - return; + return } - setShowLoader(true); + setShowLoader(true) const timer = setTimeout(() => { - setShowLoader(false); - }, 5000); + setShowLoader(false) + }, 5000) - return () => clearInterval(timer); - }, [scene?.id]); + return () => clearInterval(timer) + }, [scene?.id]) - const [showPlayersGroup, setShowPlayersGroup] = useState(false); + const [showPlayersGroup, setShowPlayersGroup] = useState(false) useEffect(() => { - scene?.group ? setShowPlayersGroup(true) : setShowPlayersGroup(false); - }, [scene?.group]); + scene?.group ? setShowPlayersGroup(true) : setShowPlayersGroup(false) + }, [scene?.group]) return ( <> - +
{showPlayersGroup ? ( - + ) : ( - + )}
-
+
{ className="-ml-2 -mt-2 w-32 h-32" /> -

- Есть идеи? Присоединяйся к нашему Discord серверу -

+

Есть идеи? Присоединяйся к нашему Discord серверу

Пиши команды в чат:

{showCommands}
- - + +
({mousePos.x}, {mousePos.y}) @@ -93,12 +90,12 @@ export const InterfaceLayer = () => {
- +
- +
- ); -}; + ) +} diff --git a/apps/client/src/components/loader.tsx b/apps/client/src/components/loader.tsx index 804fbd96..23c8271a 100644 --- a/apps/client/src/components/loader.tsx +++ b/apps/client/src/components/loader.tsx @@ -9,5 +9,5 @@ export const Loader = ({ isVisible }: { isVisible: boolean }) => {
- ); -}; + ) +} diff --git a/apps/client/src/components/player-full-body.tsx b/apps/client/src/components/player-full-body.tsx index 628ae4c9..3116a3ef 100644 --- a/apps/client/src/components/player-full-body.tsx +++ b/apps/client/src/components/player-full-body.tsx @@ -1,9 +1,9 @@ -import type { IGameObjectPlayer } from "packages/api-sdk/src"; -import { PlayerTopBlock } from "./player-top"; +import type { IGameObjectPlayer } from "packages/api-sdk/src" +import { PlayerTopBlock } from "./player-top" export const PlayerFullBody = ({ player }: { player: IGameObjectPlayer }) => { - const size = 100; - const height = (size * 64) / 100; + const size = 100 + const height = (size * 64) / 100 return (
@@ -15,5 +15,5 @@ export const PlayerFullBody = ({ player }: { player: IGameObjectPlayer }) => { />
- ); -}; + ) +} diff --git a/apps/client/src/components/player-skill.tsx b/apps/client/src/components/player-skill.tsx index e6f7f4bf..f65597da 100644 --- a/apps/client/src/components/player-skill.tsx +++ b/apps/client/src/components/player-skill.tsx @@ -1,39 +1,36 @@ -import type { IGameSkill } from "../../../../packages/api-sdk/src"; +import type { IGameSkill } from "../../../../packages/api-sdk/src" export const PlayerSkillBlock = ({ - skill, - isVisible, - }: { - skill: IGameSkill | undefined; - isVisible: boolean; + skill, + isVisible, +}: { + skill: IGameSkill | undefined + isVisible: boolean }) => { if (!skill) { - return null; + return null } - const width = skill.xp / (skill.xpNextLvl / 100); - const description = getSkillTypeDescription(skill.type); + const width = skill.xp / (skill.xpNextLvl / 100) + const description = getSkillTypeDescription(skill.type) return (
{skill.lvl}
-
+
-
- {description} -
+
{description}
- ); -}; + ) +} function getSkillTypeDescription(type: IGameSkill["type"] | null) { - if (type === "WOODSMAN") return "лесоруб"; - if (type === "MINER") return "шахтер"; + if (type === "WOODSMAN") return "лесоруб" + if (type === "MINER") return "шахтер" } diff --git a/apps/client/src/components/player-top.tsx b/apps/client/src/components/player-top.tsx index 29988f0c..430c07b5 100644 --- a/apps/client/src/components/player-top.tsx +++ b/apps/client/src/components/player-top.tsx @@ -2,7 +2,7 @@ export const PlayerTopBlock = ({ top, colorIndex, }: { top: "BASIC"; colorIndex: number }) => { - const color = colorIndex / 100; // from 0 to 100 => 0 to 1 + const color = colorIndex / 100 // from 0 to 100 => 0 to 1 switch (top) { case "BASIC": @@ -17,6 +17,6 @@ export const PlayerTopBlock = ({ filter: `hue-rotate(${color}turn)`, }} /> - ); + ) } -}; +} diff --git a/apps/client/src/components/routeBlock.tsx b/apps/client/src/components/routeBlock.tsx index 6e651a59..84f1a751 100644 --- a/apps/client/src/components/routeBlock.tsx +++ b/apps/client/src/components/routeBlock.tsx @@ -1,42 +1,41 @@ import type { IGameObjectWagon, IGameRoute, -} from "../../../../packages/api-sdk/src"; +} from "../../../../packages/api-sdk/src" export const RouteBlock = ({ - wagon, - route, - }: { - wagon: IGameObjectWagon | undefined; - route: IGameRoute | null | undefined; + wagon, + route, +}: { + wagon: IGameObjectWagon | undefined + route: IGameRoute | null | undefined }) => { if (!wagon || !route) { - return null; + return null } - const nowX = wagon.x; - const startX = route.startPoint.x; - const finishX = route.endPoint.x; + const nowX = wagon.x + const startX = route.startPoint.x + const finishX = route.endPoint.x - const distanceAll = Math.abs(finishX - startX); - const onePercent = Math.round(distanceAll / 100); + const distanceAll = Math.abs(finishX - startX) + const onePercent = Math.round(distanceAll / 100) - const distanceNowInPercent = Math.round((nowX - startX) / onePercent); + const distanceNowInPercent = Math.round((nowX - startX) / onePercent) const distanceAllChunks = Math.round( route.chunks[route.chunks.length - 1].area.endX - - route.chunks[0].area.startX, - ); - const onePercentAllChunks = Math.round(distanceAllChunks / 100); + route.chunks[0].area.startX, + ) + const onePercentAllChunks = Math.round(distanceAllChunks / 100) return (
-
+
{route.chunks?.map((chunk) => { const widthInPercent = - (chunk.area.endX - chunk.area.startX) / onePercentAllChunks; + (chunk.area.endX - chunk.area.startX) / onePercentAllChunks return (
{chunk.title}
- ); + ) })}
- ); -}; + ) +} diff --git a/apps/client/src/components/tool.tsx b/apps/client/src/components/tool.tsx index 0d3565fb..2a036993 100644 --- a/apps/client/src/components/tool.tsx +++ b/apps/client/src/components/tool.tsx @@ -1,16 +1,16 @@ -import { Howl } from "howler"; -import { useEffect, useMemo } from "react"; -import type { IGameObjectPlayer } from "../../../../packages/api-sdk/src"; +import { Howl } from "howler" +import { useEffect, useMemo } from "react" +import type { IGameObjectPlayer } from "../../../../packages/api-sdk/src" export const ToolBlock = ({ object, }: { - object: IGameObjectPlayer; + object: IGameObjectPlayer }) => { - const axe = object.inventory?.items.find((item) => item.type === "AXE"); + const axe = object.inventory?.items.find((item) => item.type === "AXE") const pickaxe = object.inventory?.items.find( (item) => item.type === "PICKAXE", - ); + ) const soundChopping = useMemo( () => @@ -20,7 +20,7 @@ export const ToolBlock = ({ volume: 0.3, }), [], - ); + ) const soundPunch = useMemo( () => @@ -31,7 +31,7 @@ export const ToolBlock = ({ rate: 0.5, }), [], - ); + ) const soundMining = useMemo( () => @@ -42,43 +42,43 @@ export const ToolBlock = ({ rate: 0.7, }), [], - ); + ) - const isChoppingWithAxe = object.state === "CHOPPING" && !!axe; - const isMiningWithPickaxe = object.state === "MINING" && !!pickaxe; + const isChoppingWithAxe = object.state === "CHOPPING" && !!axe + const isMiningWithPickaxe = object.state === "MINING" && !!pickaxe useEffect(() => { if (object.state === "CHOPPING") { if (isChoppingWithAxe) { - soundPunch.stop(); - soundChopping.play(); + soundPunch.stop() + soundChopping.play() } else { - soundChopping.stop(); - soundPunch.play(); + soundChopping.stop() + soundPunch.play() } - return; + return } if (object.state === "MINING") { if (isMiningWithPickaxe) { - soundPunch.stop(); - soundMining.play(); + soundPunch.stop() + soundMining.play() } else { - soundMining.stop(); - soundPunch.play(); + soundMining.stop() + soundPunch.play() } - return; + return } - soundChopping.stop(); - soundMining.stop(); - soundPunch.stop(); + soundChopping.stop() + soundMining.stop() + soundPunch.stop() return () => { - soundChopping.stop(); - soundMining.stop(); - soundPunch.stop(); - }; + soundChopping.stop() + soundMining.stop() + soundPunch.stop() + } }, [ object.state, isChoppingWithAxe, @@ -86,7 +86,7 @@ export const ToolBlock = ({ soundChopping, soundMining, soundPunch, - ]); + ]) return ( <> @@ -108,5 +108,5 @@ export const ToolBlock = ({ /> )} - ); -}; + ) +} diff --git a/apps/client/src/components/topPlayerCard.tsx b/apps/client/src/components/topPlayerCard.tsx index 6b22a0d0..c3e9fdcf 100644 --- a/apps/client/src/components/topPlayerCard.tsx +++ b/apps/client/src/components/topPlayerCard.tsx @@ -1,23 +1,23 @@ import type { IGameObjectPlayer, PlayerTitle, -} from "../../../../packages/api-sdk/src"; -import { PlayerFullBody } from "./player-full-body"; +} from "../../../../packages/api-sdk/src" +import { PlayerFullBody } from "./player-full-body" export const TopPlayerCard = ({ - player, - title, - points, - }: { - player: IGameObjectPlayer | undefined; - title: PlayerTitle; - points: string; + player, + title, + points, +}: { + player: IGameObjectPlayer | undefined + title: PlayerTitle + points: string }) => { if (!player) { - return null; + return null } - const borderColor = getBorderColorByType(title.type); + const borderColor = getBorderColorByType(title.type) return (
- +

{player.userName}

-

+

{title.title}! {points}

- ); -}; + ) +} function getBorderColorByType(type: PlayerTitle["type"]) { if (type === "RICH") { - return "border-teal-4"; + return "border-teal-4" } if (type === "FAMOUS") { - return "border-blue-4"; + return "border-blue-4" } if (type === "VIEWER") { - return "border-violet-4"; + return "border-violet-4" } if (type === "VILLAIN") { - return "border-red-4"; + return "border-red-4" } if (type === "REFUELLER") { - return "border-coal-4"; + return "border-coal-4" } if (type === "WOODSMAN") { - return "border-green-4"; + return "border-green-4" } if (type === "MINER") { - return "border-silver-4"; + return "border-silver-4" } } diff --git a/apps/client/src/components/topPlayers.tsx b/apps/client/src/components/topPlayers.tsx index bcbf0ae3..04e4a8b1 100644 --- a/apps/client/src/components/topPlayers.tsx +++ b/apps/client/src/components/topPlayers.tsx @@ -1,17 +1,16 @@ -import { useTopPlayers } from "../hooks/useTopPlayers"; -import { TopPlayerCard } from "./topPlayerCard"; +import { useTopPlayers } from "../hooks/useTopPlayers" +import { TopPlayerCard } from "./topPlayerCard" export const TopPlayersBlock = () => { - const playersWithResult = useTopPlayers(); + const playersWithResult = useTopPlayers() if (!playersWithResult) { - return null; + return null } return (
-
+
Топ игроков
@@ -53,5 +52,5 @@ export const TopPlayersBlock = () => {
- ); -}; + ) +} diff --git a/apps/client/src/components/wagonStatsBlock.tsx b/apps/client/src/components/wagonStatsBlock.tsx index 6cddba60..9bb0722a 100644 --- a/apps/client/src/components/wagonStatsBlock.tsx +++ b/apps/client/src/components/wagonStatsBlock.tsx @@ -1,36 +1,38 @@ -import type { IGameObjectWagon } from "../../../../packages/api-sdk/src"; -import speed1 from "../game/assets/images/icons/speed-1.png" +import type { IGameObjectWagon } from "../../../../packages/api-sdk/src" import fuel1 from "../game/assets/images/icons/fuel-1.png" +import speed1 from "../game/assets/images/icons/speed-1.png" -export const WagonStatsBlock = ({ wagon }: { - wagon: IGameObjectWagon | undefined; +export const WagonStatsBlock = ({ + wagon, +}: { + wagon: IGameObjectWagon | undefined }) => { if (!wagon) { - return null; + return null } - const speedInMeters = wagon.speed; - const fuelInSeconds = Math.round(wagon.fuel / 40); - const fuelInMinutes = Math.round(fuelInSeconds / 60); + const speedInMeters = wagon.speed + const fuelInSeconds = Math.round(wagon.fuel / 40) + const fuelInMinutes = Math.round(fuelInSeconds / 60) - const showSpeed = speedInMeters > 0 ? `${speedInMeters} м/сек` : '[стоп]'; - const showFuelTime = fuelInSeconds > 0 ? fuelInMinutes <= 3 ? `${fuelInSeconds} сек` : `≈ ${fuelInMinutes} мин` : '[нет топлива]'; + const showSpeed = speedInMeters > 0 ? `${speedInMeters} м/сек` : "[стоп]" + const showFuelTime = + fuelInSeconds > 0 + ? fuelInMinutes <= 3 + ? `${fuelInSeconds} сек` + : `≈ ${fuelInMinutes} мин` + : "[нет топлива]" return ( -
-
- +
+
+

{showSpeed}

-
- +
+

{showFuelTime}

) -} \ No newline at end of file +} diff --git a/apps/client/src/game/components/buildingInterface.ts b/apps/client/src/game/components/buildingInterface.ts index d6d883a3..f4edab24 100644 --- a/apps/client/src/game/components/buildingInterface.ts +++ b/apps/client/src/game/components/buildingInterface.ts @@ -1,75 +1,75 @@ -import { Sprite, Text } from "pixi.js"; -import type { IGameObjectBuilding } from "../../../../../packages/api-sdk/src"; -import { GraphicsContainer } from "./graphicsContainer"; +import { Sprite, Text } from "pixi.js" +import type { IGameObjectBuilding } from "../../../../../packages/api-sdk/src" +import { GraphicsContainer } from "./graphicsContainer" export class BuildingInterface extends GraphicsContainer { - public building: IGameObjectBuilding; + public building: IGameObjectBuilding - public wood = 0; - public stone = 0; + public wood = 0 + public stone = 0 constructor(building: IGameObjectBuilding) { - super({ type: "INTERFACE" }); + super({ type: "INTERFACE" }) - this.x = 0; - this.y = 0; + this.x = 0 + this.y = 0 - this.building = building; + this.building = building - this.init(); + this.init() } init() { this.wood = this.building.inventory.items.find((item) => item.type === "WOOD") - ?.amount ?? 0; + ?.amount ?? 0 this.stone = this.building.inventory.items.find((item) => item.type === "STONE") - ?.amount ?? 0; + ?.amount ?? 0 - this.drawWood(); - this.drawStone(); + this.drawWood() + this.drawStone() } rebuild() { - this.children = []; - this.drawWood(); - this.drawStone(); + this.children = [] + this.drawWood() + this.drawStone() } animate() { - this.visible = true; - this.update(); + this.visible = true + this.update() } update() { const wood = this.building.inventory.items.find( (item) => item.type === "WOOD", - )?.amount; + )?.amount const stone = this.building.inventory.items.find( (item) => item.type === "STONE", - )?.amount; + )?.amount if (wood !== this.wood || stone !== this.stone) { - this.wood = wood ?? 0; - this.stone = stone ?? 0; - this.rebuild(); + this.wood = wood ?? 0 + this.stone = stone ?? 0 + this.rebuild() } - this.wood = wood ?? 0; - this.stone = stone ?? 0; + this.wood = wood ?? 0 + this.stone = stone ?? 0 } drawWood() { if (this.wood <= 0) { - return; + return } - const container = new GraphicsContainer({ type: "PLAYER_COINS" }); + const container = new GraphicsContainer({ type: "PLAYER_COINS" }) - const woodSprite = Sprite.from("wood1"); - woodSprite.width = 48; - woodSprite.height = 48; + const woodSprite = Sprite.from("wood1") + woodSprite.width = 48 + woodSprite.height = 48 const basicText = new Text({ text: this.wood, @@ -78,29 +78,29 @@ export class BuildingInterface extends GraphicsContainer { fill: 0xfef3c7, align: "left", }, - }); + }) - basicText.x = 14; - basicText.y = 26; + basicText.x = 14 + basicText.y = 26 - container.addChild(woodSprite, basicText); + container.addChild(woodSprite, basicText) - container.x = -50; - container.y = -74; + container.x = -50 + container.y = -74 - this.addChild(container); + this.addChild(container) } drawStone() { if (this.stone <= 0) { - return; + return } - const container = new GraphicsContainer({ type: "PLAYER_COINS" }); + const container = new GraphicsContainer({ type: "PLAYER_COINS" }) - const sprite = Sprite.from("stoneRes1"); - sprite.width = 48; - sprite.height = 48; + const sprite = Sprite.from("stoneRes1") + sprite.width = 48 + sprite.height = 48 const basicText = new Text({ text: this.stone, @@ -109,16 +109,16 @@ export class BuildingInterface extends GraphicsContainer { fill: 0xfef3c7, align: "left", }, - }); + }) - basicText.x = 14; - basicText.y = 26; + basicText.x = 14 + basicText.y = 26 - container.addChild(sprite, basicText); + container.addChild(sprite, basicText) - container.x = 4; - container.y = -74; + container.x = 4 + container.y = -74 - this.addChild(container); + this.addChild(container) } } diff --git a/apps/client/src/game/components/fireParticlesContainer.ts b/apps/client/src/game/components/fireParticlesContainer.ts index d64d4233..172ceab4 100644 --- a/apps/client/src/game/components/fireParticlesContainer.ts +++ b/apps/client/src/game/components/fireParticlesContainer.ts @@ -1,69 +1,69 @@ -import { type Container, Sprite } from "pixi.js"; -import { getRandomInRange } from "../../../../../packages/api-sdk/src"; -import { GraphicsContainer } from "./graphicsContainer"; +import { type Container, Sprite } from "pixi.js" +import { getRandomInRange } from "../../../../../packages/api-sdk/src" +import { GraphicsContainer } from "./graphicsContainer" interface IFireParticlesContainerOptions { - x: number; - y: number; - areaWidth: number; + x: number + y: number + areaWidth: number } export class FireParticlesContainer extends GraphicsContainer { - public areaWidth: number; - public offset = 0; + public areaWidth: number + public offset = 0 constructor({ x, y, areaWidth }: IFireParticlesContainerOptions) { - super({ type: "FIRE_PARTICLE", direction: "LEFT" }); + super({ type: "FIRE_PARTICLE", direction: "LEFT" }) - this.x = x; - this.y = y; - this.areaWidth = areaWidth; + this.x = x + this.y = y + this.areaWidth = areaWidth } createRandom() { - const sprite = Sprite.from(this.getRandomSpriteIndex()); - sprite.anchor.set(0.5, 1); + const sprite = Sprite.from(this.getRandomSpriteIndex()) + sprite.anchor.set(0.5, 1) - const half = this.width / 2; - sprite.x = getRandomInRange(-half, half); - sprite.scale = getRandomInRange(10, 20) / 10; + const half = this.width / 2 + sprite.x = getRandomInRange(-half, half) + sprite.scale = getRandomInRange(10, 20) / 10 - this.addChild(sprite); + this.addChild(sprite) } getRandomSpriteIndex() { - const random = getRandomInRange(1, 1000); + const random = getRandomInRange(1, 1000) if (random <= 500) { - return "fireParticle1"; + return "fireParticle1" } if (random <= 750) { - return "fireParticle2"; + return "fireParticle2" } - return "fireParticle3"; + return "fireParticle3" } remove(container: Container) { - return this.removeChild(container); + return this.removeChild(container) } animate(power = 1) { - this.offset -= power + 1; + this.offset -= power + 1 - const activeNow = power * 8 + 1; - const canCreate = this.children.length < activeNow && this.offset <= 0; + const activeNow = power * 8 + 1 + const canCreate = this.children.length < activeNow && this.offset <= 0 if (canCreate) { - this.createRandom(); - this.offset = power * getRandomInRange(90, 110) + 3; + this.createRandom() + this.offset = power * getRandomInRange(90, 110) + 3 } for (const container of this.children) { - container.visible = true; + container.visible = true - container.y -= 0.28; - container.alpha -= 0.008; + container.y -= 0.28 + container.alpha -= 0.008 if (container.alpha <= 0) { - this.remove(container); + this.remove(container) } } } diff --git a/apps/client/src/game/components/graphicsContainer.ts b/apps/client/src/game/components/graphicsContainer.ts index 8ea5efcd..804fe7e4 100644 --- a/apps/client/src/game/components/graphicsContainer.ts +++ b/apps/client/src/game/components/graphicsContainer.ts @@ -1,24 +1,24 @@ -import { ColorMatrixFilter, Container, Sprite } from "pixi.js"; +import { ColorMatrixFilter, Container, Sprite } from "pixi.js" import type { GraphicsContainerType, IGameObjectDirection, -} from "../../../../../packages/api-sdk/src"; +} from "../../../../../packages/api-sdk/src" interface IGraphicsContainerOptions { - type: GraphicsContainerType; - direction?: IGameObjectDirection; + type: GraphicsContainerType + direction?: IGameObjectDirection } export class GraphicsContainer extends Container { - public type: GraphicsContainerType; - public direction: IGameObjectDirection = "RIGHT"; + public type: GraphicsContainerType + public direction: IGameObjectDirection = "RIGHT" constructor({ type, direction }: IGraphicsContainerOptions) { - super(); - this.type = type; + super() + this.type = type if (direction) { - this.direction = direction; + this.direction = direction } } @@ -27,24 +27,24 @@ export class GraphicsContainer extends Container { direction: IGameObjectDirection, type: GraphicsContainerType, ) { - const sprite = Sprite.from(spriteIndex); - sprite.anchor.set(0.5, 1); + const sprite = Sprite.from(spriteIndex) + sprite.anchor.set(0.5, 1) - const container = new GraphicsContainer({ type, direction }); - container.addChild(sprite); + const container = new GraphicsContainer({ type, direction }) + container.addChild(sprite) - return container; + return container } static addFiltersToPlayersTop( container: GraphicsContainer, colorIndex: number, ) { - const filterHue = new ColorMatrixFilter(); - filterHue.hue(colorIndex, false); - const filterBrightness = new ColorMatrixFilter(); - filterBrightness.brightness(0.9, false); + const filterHue = new ColorMatrixFilter() + filterHue.hue(colorIndex, false) + const filterBrightness = new ColorMatrixFilter() + filterBrightness.brightness(0.9, false) - container.filters = [filterHue, filterBrightness]; + container.filters = [filterHue, filterBrightness] } } diff --git a/apps/client/src/game/components/playerInterface.ts b/apps/client/src/game/components/playerInterface.ts index 605487aa..6289a6e6 100644 --- a/apps/client/src/game/components/playerInterface.ts +++ b/apps/client/src/game/components/playerInterface.ts @@ -1,33 +1,33 @@ -import { Graphics, Text } from "pixi.js"; -import type { IGameObjectPlayer } from "../../../../../packages/api-sdk/src"; -import { GraphicsContainer } from "./graphicsContainer"; -import { UnitInterface } from "./unitInterface"; +import { Graphics, Text } from "pixi.js" +import type { IGameObjectPlayer } from "../../../../../packages/api-sdk/src" +import { GraphicsContainer } from "./graphicsContainer" +import { UnitInterface } from "./unitInterface" export class PlayerInterface extends UnitInterface { - public userName: string; + public userName: string constructor(player: IGameObjectPlayer) { - super(player); + super(player) - this.userName = player.userName; + this.userName = player.userName - this.init(); + this.init() } init() { - super.init(); + super.init() - this.drawUserName(this.userName); + this.drawUserName(this.userName) } rebuild() { - super.rebuild(); + super.rebuild() - this.drawUserName(this.userName); + this.drawUserName(this.userName) } drawUserName(userName: string) { - const container = new GraphicsContainer({ type: "INTERFACE" }); + const container = new GraphicsContainer({ type: "INTERFACE" }) const basicText = new Text({ text: userName, @@ -38,17 +38,17 @@ export class PlayerInterface extends UnitInterface { fill: 0x2e222f, align: "center", }, - }); + }) - const graphics = new Graphics(); - graphics.roundRect(-6, -2, basicText.width + 12, basicText.height + 4, 8); - graphics.fill(0xffffff); + const graphics = new Graphics() + graphics.roundRect(-6, -2, basicText.width + 12, basicText.height + 4, 8) + graphics.fill(0xffffff) - container.addChild(graphics, basicText); + container.addChild(graphics, basicText) - container.x = -container.width / 2 + 24; - container.y = -84; + container.x = -container.width / 2 + 24 + container.y = -84 - this.addChild(container); + this.addChild(container) } } diff --git a/apps/client/src/game/components/unitHairContainer.ts b/apps/client/src/game/components/unitHairContainer.ts index cc4d80f6..a0655cdb 100644 --- a/apps/client/src/game/components/unitHairContainer.ts +++ b/apps/client/src/game/components/unitHairContainer.ts @@ -1,21 +1,21 @@ -import { Sprite } from "pixi.js"; +import { Sprite } from "pixi.js" import type { IGameObjectDirection, IGameObjectUnit, -} from "../../../../../packages/api-sdk/src"; -import { GraphicsContainer } from "./graphicsContainer"; +} from "../../../../../packages/api-sdk/src" +import { GraphicsContainer } from "./graphicsContainer" interface IUnitHairContainerOptions { - direction: IGameObjectDirection; - visual: IGameObjectUnit["visual"]["hairstyle"]; + direction: IGameObjectDirection + visual: IGameObjectUnit["visual"]["hairstyle"] } export class UnitHairContainer extends GraphicsContainer { - public visual: IGameObjectUnit["visual"]["hairstyle"]; + public visual: IGameObjectUnit["visual"]["hairstyle"] constructor({ direction, visual }: IUnitHairContainerOptions) { - super({ type: "UNIT_HAIR", direction }); - this.visual = visual; + super({ type: "UNIT_HAIR", direction }) + this.visual = visual } static create( @@ -23,13 +23,13 @@ export class UnitHairContainer extends GraphicsContainer { direction: IGameObjectDirection, visual: IGameObjectUnit["visual"]["hairstyle"], ) { - const sprite = Sprite.from(spriteIndex); - sprite.anchor.set(0.5, 1); + const sprite = Sprite.from(spriteIndex) + sprite.anchor.set(0.5, 1) - const container = new UnitHairContainer({ direction, visual }); - container.addChild(sprite); + const container = new UnitHairContainer({ direction, visual }) + container.addChild(sprite) - return container; + return container } static getAll() { @@ -38,6 +38,6 @@ export class UnitHairContainer extends GraphicsContainer { UnitHairContainer.create("unitHairClassicRight", "RIGHT", "CLASSIC"), UnitHairContainer.create("unitHairCoalLongLeft", "LEFT", "COAL_LONG"), UnitHairContainer.create("unitHairCoalLongRight", "RIGHT", "COAL_LONG"), - ]; + ] } } diff --git a/apps/client/src/game/components/unitHeadContainer.ts b/apps/client/src/game/components/unitHeadContainer.ts index 6b3bddfa..1909c9e7 100644 --- a/apps/client/src/game/components/unitHeadContainer.ts +++ b/apps/client/src/game/components/unitHeadContainer.ts @@ -1,21 +1,21 @@ -import { Sprite } from "pixi.js"; +import { Sprite } from "pixi.js" import type { IGameObjectDirection, IGameObjectUnit, -} from "../../../../../packages/api-sdk/src"; -import { GraphicsContainer } from "./graphicsContainer"; +} from "../../../../../packages/api-sdk/src" +import { GraphicsContainer } from "./graphicsContainer" interface IUnitHeadContainerOptions { - direction: IGameObjectDirection; - visual: IGameObjectUnit["visual"]["head"]; + direction: IGameObjectDirection + visual: IGameObjectUnit["visual"]["head"] } export class UnitHeadContainer extends GraphicsContainer { - public visual: IGameObjectUnit["visual"]["head"]; + public visual: IGameObjectUnit["visual"]["head"] constructor({ direction, visual }: IUnitHeadContainerOptions) { - super({ type: "UNIT_HEAD", direction }); - this.visual = visual; + super({ type: "UNIT_HEAD", direction }) + this.visual = visual } static create( @@ -23,19 +23,19 @@ export class UnitHeadContainer extends GraphicsContainer { direction: IGameObjectDirection, visual: IGameObjectUnit["visual"]["head"], ) { - const sprite = Sprite.from(spriteIndex); - sprite.anchor.set(0.5, 1); + const sprite = Sprite.from(spriteIndex) + sprite.anchor.set(0.5, 1) - const container = new UnitHeadContainer({ direction, visual }); - container.addChild(sprite); + const container = new UnitHeadContainer({ direction, visual }) + container.addChild(sprite) - return container; + return container } static getAll() { return [ UnitHeadContainer.create("unitHead1Left", "LEFT", "1"), UnitHeadContainer.create("unitHead1Right", "RIGHT", "1"), - ]; + ] } } diff --git a/apps/client/src/game/components/unitInterface.ts b/apps/client/src/game/components/unitInterface.ts index c5ae817b..e07419a8 100644 --- a/apps/client/src/game/components/unitInterface.ts +++ b/apps/client/src/game/components/unitInterface.ts @@ -1,86 +1,86 @@ -import { Sprite, Text, Graphics } from "pixi.js"; -import type { IGameObjectUnit } from "../../../../../packages/api-sdk/src"; -import { GraphicsContainer } from "./graphicsContainer"; +import { Graphics, Sprite, Text } from "pixi.js" +import type { IGameObjectUnit } from "../../../../../packages/api-sdk/src" +import { GraphicsContainer } from "./graphicsContainer" export class UnitInterface extends GraphicsContainer { - public children: GraphicsContainer[] = []; - public unit: IGameObjectUnit; + public children: GraphicsContainer[] = [] + public unit: IGameObjectUnit - public coins = 0; - public wood = 0; - public stone = 0; + public coins = 0 + public wood = 0 + public stone = 0 - public showInHandItemIndex = 0; - public showInHandTimerSeconds = 0; - public showToolTimerSeconds = 0; - public showWood = false; - public showStone = false; + public showInHandItemIndex = 0 + public showInHandTimerSeconds = 0 + public showToolTimerSeconds = 0 + public showWood = false + public showStone = false - public haveAxe = false; - public showAxe = false; - public havePickaxe = false; - public showPickaxe = false; + public haveAxe = false + public showAxe = false + public havePickaxe = false + public showPickaxe = false constructor(unit: IGameObjectUnit) { - super({ type: "INTERFACE" }); + super({ type: "INTERFACE" }) - this.x = -15; - this.y = 5; + this.x = -15 + this.y = 5 - this.unit = unit; + this.unit = unit - this.init(); + this.init() } init() { - this.coins = this.unit.coins; + this.coins = this.unit.coins this.wood = this.unit.inventory.items.find((item) => item.type === "WOOD")?.amount ?? - 0; + 0 this.stone = this.unit.inventory.items.find((item) => item.type === "STONE")?.amount ?? - 0; + 0 this.haveAxe = !!this.unit.inventory.items.find( (item) => item.type === "AXE", - ); + ) this.havePickaxe = !!this.unit.inventory.items.find( (item) => item.type === "PICKAXE", - ); + ) - this.drawCoins(); - this.drawWood(); - this.drawStone(); - this.drawAxe(); - this.drawPickaxe(); + this.drawCoins() + this.drawWood() + this.drawStone() + this.drawAxe() + this.drawPickaxe() - this.setShowInHandTimer(); - this.setShowToolTimer(); + this.setShowInHandTimer() + this.setShowToolTimer() } rebuild() { - this.children = []; - this.drawCoins(); - this.drawWood(); - this.drawStone(); - this.drawAxe(); - this.drawPickaxe(); - this.showInHandTimerSeconds = 0; + this.children = [] + this.drawCoins() + this.drawWood() + this.drawStone() + this.drawAxe() + this.drawPickaxe() + this.showInHandTimerSeconds = 0 } update() { const wood = this.unit.inventory.items.find((item) => item.type === "WOOD")?.amount ?? - 0; + 0 const stone = this.unit.inventory.items.find((item) => item.type === "STONE")?.amount ?? - 0; + 0 const haveAxe = !!this.unit.inventory.items.find( (item) => item.type === "AXE", - ); + ) const havePickaxe = !!this.unit.inventory.items.find( (item) => item.type === "PICKAXE", - ); + ) if ( this.unit.coins !== this.coins || @@ -89,68 +89,68 @@ export class UnitInterface extends GraphicsContainer { haveAxe !== this.haveAxe || havePickaxe !== this.havePickaxe ) { - this.coins = this.unit.coins; - this.wood = wood; - this.stone = stone; - this.haveAxe = haveAxe; - this.havePickaxe = havePickaxe; - this.rebuild(); + this.coins = this.unit.coins + this.wood = wood + this.stone = stone + this.haveAxe = haveAxe + this.havePickaxe = havePickaxe + this.rebuild() } - this.coins = this.unit.coins; - this.wood = wood; - this.stone = stone; - this.haveAxe = haveAxe; - this.havePickaxe = havePickaxe; + this.coins = this.unit.coins + this.wood = wood + this.stone = stone + this.haveAxe = haveAxe + this.havePickaxe = havePickaxe } animate() { - this.visible = true; - this.update(); + this.visible = true + this.update() for (const container of this.children) { - container.visible = true; + container.visible = true if (container.type === "PLAYER_COINS") { if (!this.coins) { - container.visible = false; + container.visible = false } } if (container.type === "PLAYER_WOOD") { if (this.wood <= 0 || !this.showWood) { - container.visible = false; + container.visible = false } } if (container.type === "PLAYER_STONE") { if (this.stone <= 0 || !this.showStone) { - container.visible = false; + container.visible = false } } if (container.type === "PLAYER_AXE") { if (!this.haveAxe || !this.showAxe) { - container.visible = false; + container.visible = false } } if (container.type === "PLAYER_PICKAXE") { if (!this.havePickaxe || !this.showPickaxe) { - container.visible = false; + container.visible = false } } } } drawCoins() { - const container = new GraphicsContainer({ type: "PLAYER_COINS" }); + const container = new GraphicsContainer({ type: "PLAYER_COINS" }) - const sprite = Sprite.from("coin1"); + const sprite = Sprite.from("coin1") sprite.width = 32 - sprite.height = 32; - sprite.x = -32; - sprite.y = -9; + sprite.height = 32 + sprite.x = -32 + sprite.y = -9 const basicText = new Text({ text: this.coins, @@ -158,29 +158,29 @@ export class UnitInterface extends GraphicsContainer { fontFamily: "Noto Serif", fontSize: 12, fontWeight: "700", - fill: 0x0B5E65, + fill: 0x0b5e65, align: "center", }, - }); + }) - const graphics = new Graphics(); - graphics.roundRect(-16, -4, basicText.width + 20, basicText.height + 8, 10); - graphics.fill(0x8FF8E2); + const graphics = new Graphics() + graphics.roundRect(-16, -4, basicText.width + 20, basicText.height + 8, 10) + graphics.fill(0x8ff8e2) - container.addChild(graphics, sprite, basicText); + container.addChild(graphics, sprite, basicText) - container.x = 70; - container.y = -56; + container.x = 70 + container.y = -56 - this.addChild(container); + this.addChild(container) } drawWood() { - const container = new GraphicsContainer({ type: "PLAYER_WOOD" }); + const container = new GraphicsContainer({ type: "PLAYER_WOOD" }) - const woodSprite = Sprite.from("wood1"); - woodSprite.width = 32; - woodSprite.height = 32; + const woodSprite = Sprite.from("wood1") + woodSprite.width = 32 + woodSprite.height = 32 const basicText = new Text({ text: this.wood, @@ -189,25 +189,25 @@ export class UnitInterface extends GraphicsContainer { fill: 0xfef3c7, align: "left", }, - }); + }) - basicText.x = 6; - basicText.y = 16; + basicText.x = 6 + basicText.y = 16 - container.addChild(woodSprite, basicText); + container.addChild(woodSprite, basicText) - container.x = -18; - container.y = -48; + container.x = -18 + container.y = -48 - this.addChild(container); + this.addChild(container) } drawStone() { - const container = new GraphicsContainer({ type: "PLAYER_STONE" }); + const container = new GraphicsContainer({ type: "PLAYER_STONE" }) - const woodSprite = Sprite.from("stoneRes1"); - woodSprite.width = 32; - woodSprite.height = 32; + const woodSprite = Sprite.from("stoneRes1") + woodSprite.width = 32 + woodSprite.height = 32 const basicText = new Text({ text: this.stone, @@ -216,123 +216,123 @@ export class UnitInterface extends GraphicsContainer { fill: 0xfef3c7, align: "left", }, - }); + }) - basicText.x = 6; - basicText.y = 16; + basicText.x = 6 + basicText.y = 16 - container.addChild(woodSprite, basicText); + container.addChild(woodSprite, basicText) - container.x = -18; - container.y = -48; + container.x = -18 + container.y = -48 - this.addChild(container); + this.addChild(container) } drawAxe() { - const container = new GraphicsContainer({ type: "PLAYER_AXE" }); + const container = new GraphicsContainer({ type: "PLAYER_AXE" }) - const sprite = Sprite.from("toolAxe1"); - sprite.width = 64; - sprite.height = 64; + const sprite = Sprite.from("toolAxe1") + sprite.width = 64 + sprite.height = 64 - container.addChild(sprite); + container.addChild(sprite) - container.x = -10; - container.y = -68; + container.x = -10 + container.y = -68 - this.addChild(container); + this.addChild(container) } drawPickaxe() { - const container = new GraphicsContainer({ type: "PLAYER_PICKAXE" }); + const container = new GraphicsContainer({ type: "PLAYER_PICKAXE" }) - const sprite = Sprite.from("toolPickaxe1"); - sprite.width = 64; - sprite.height = 64; + const sprite = Sprite.from("toolPickaxe1") + sprite.width = 64 + sprite.height = 64 - container.addChild(sprite); + container.addChild(sprite) - container.x = -10; - container.y = -68; + container.x = -10 + container.y = -68 - this.addChild(container); + this.addChild(container) } showWoodInHand() { - this.showWood = true; + this.showWood = true } showStoneInHand() { - this.showStone = true; + this.showStone = true } showAxeInHand() { - this.showAxe = true; - this.showToolTimerSeconds = 5; + this.showAxe = true + this.showToolTimerSeconds = 5 } showPickaxeInHand() { - this.showPickaxe = true; - this.showToolTimerSeconds = 5; + this.showPickaxe = true + this.showToolTimerSeconds = 5 } setShowInHandTimer() { return setInterval(() => { if (this.showInHandTimerSeconds <= 0) { - this.showNextItem(); - return; + this.showNextItem() + return } - this.showInHandTimerSeconds -= 1; - }, 1000); + this.showInHandTimerSeconds -= 1 + }, 1000) } setShowToolTimer() { return setInterval(() => { if (this.showToolTimerSeconds <= 0) { - this.showAxe = false; - this.showPickaxe = false; - return; + this.showAxe = false + this.showPickaxe = false + return } - this.showToolTimerSeconds -= 1; - }); + this.showToolTimerSeconds -= 1 + }) } getResourcesArray() { return this.unit.inventory.items.filter( (item) => item.type === "WOOD" || item.type === "STONE", - ); + ) } showNextItem() { - const items = this.getResourcesArray(); + const items = this.getResourcesArray() if (!items) { - return; + return } if (items.length < this.showInHandItemIndex + 1) { - this.showInHandItemIndex = 0; + this.showInHandItemIndex = 0 } - this.showWood = false; - this.showStone = false; - this.showInHandTimerSeconds = 5; + this.showWood = false + this.showStone = false + this.showInHandTimerSeconds = 5 if (!items[this.showInHandItemIndex]?.type) { - return; + return } switch (items[this.showInHandItemIndex].type) { case "WOOD": - this.showWoodInHand(); - break; + this.showWoodInHand() + break case "STONE": - this.showStoneInHand(); - break; + this.showStoneInHand() + break } - this.showInHandItemIndex += 1; + this.showInHandItemIndex += 1 } } diff --git a/apps/client/src/game/components/unitTopContainer.ts b/apps/client/src/game/components/unitTopContainer.ts index 5642f6ec..4a7ef386 100644 --- a/apps/client/src/game/components/unitTopContainer.ts +++ b/apps/client/src/game/components/unitTopContainer.ts @@ -1,21 +1,21 @@ -import { Sprite } from "pixi.js"; +import { Sprite } from "pixi.js" import type { IGameObjectDirection, IGameObjectUnit, -} from "../../../../../packages/api-sdk/src"; -import { GraphicsContainer } from "./graphicsContainer"; +} from "../../../../../packages/api-sdk/src" +import { GraphicsContainer } from "./graphicsContainer" interface IUnitTopContainerOptions { - direction: IGameObjectDirection; - visual: IGameObjectUnit["visual"]["top"]; + direction: IGameObjectDirection + visual: IGameObjectUnit["visual"]["top"] } export class UnitTopContainer extends GraphicsContainer { - public visual: IGameObjectUnit["visual"]["top"]; + public visual: IGameObjectUnit["visual"]["top"] constructor({ direction, visual }: IUnitTopContainerOptions) { - super({ type: "UNIT_TOP", direction }); - this.visual = visual; + super({ type: "UNIT_TOP", direction }) + this.visual = visual } static create( @@ -23,13 +23,13 @@ export class UnitTopContainer extends GraphicsContainer { direction: IGameObjectDirection, visual: IGameObjectUnit["visual"]["top"], ) { - const sprite = Sprite.from(spriteIndex); - sprite.anchor.set(0.5, 1); + const sprite = Sprite.from(spriteIndex) + sprite.anchor.set(0.5, 1) - const container = new UnitTopContainer({ direction, visual }); - container.addChild(sprite); + const container = new UnitTopContainer({ direction, visual }) + container.addChild(sprite) - return container; + return container } static getAll() { @@ -48,6 +48,6 @@ export class UnitTopContainer extends GraphicsContainer { "RIGHT", "DARK_SILVER_SHIRT", ), - ]; + ] } } diff --git a/apps/client/src/game/components/wagonEngineCloudsContainer.ts b/apps/client/src/game/components/wagonEngineCloudsContainer.ts index 63ed70b8..5c690636 100644 --- a/apps/client/src/game/components/wagonEngineCloudsContainer.ts +++ b/apps/client/src/game/components/wagonEngineCloudsContainer.ts @@ -1,65 +1,65 @@ -import { type Container, Sprite } from "pixi.js"; -import { getRandomInRange } from "../../../../../packages/api-sdk/src"; -import { GraphicsContainer } from "./graphicsContainer"; +import { type Container, Sprite } from "pixi.js" +import { getRandomInRange } from "../../../../../packages/api-sdk/src" +import { GraphicsContainer } from "./graphicsContainer" export class WagonEngineCloudsContainer extends GraphicsContainer { - public offset = 0; + public offset = 0 constructor() { - super({ type: "WAGON_ENGINE_CLOUD", direction: "LEFT" }); + super({ type: "WAGON_ENGINE_CLOUD", direction: "LEFT" }) - this.x = -106; - this.y = -118; + this.x = -106 + this.y = -118 } createRandom() { - const sprite = Sprite.from(this.getRandomSpriteIndex()); - sprite.anchor.set(0.5, 1); - sprite.scale = 0.75; - sprite.visible = false; + const sprite = Sprite.from(this.getRandomSpriteIndex()) + sprite.anchor.set(0.5, 1) + sprite.scale = 0.75 + sprite.visible = false - this.addChild(sprite); + this.addChild(sprite) } getRandomSpriteIndex() { - const random = getRandomInRange(1, 1000); + const random = getRandomInRange(1, 1000) if (random <= 500) { - return "wagonEngineCloud1"; + return "wagonEngineCloud1" } if (random <= 750) { - return "wagonEngineCloud2"; + return "wagonEngineCloud2" } if (random <= 995) { - return "wagonEngineCloud3"; + return "wagonEngineCloud3" } - return "wagonEngineCloud4"; + return "wagonEngineCloud4" } remove(container: Container) { - return this.removeChild(container); + return this.removeChild(container) } animate(speed: number) { - this.offset -= speed + 1; + this.offset -= speed + 1 - const cloudsActive = speed * 8 + 1; + const cloudsActive = speed * 8 + 1 const canCreateCloud = - this.children.length < cloudsActive && this.offset <= 0; + this.children.length < cloudsActive && this.offset <= 0 if (canCreateCloud) { - this.createRandom(); - this.offset = speed * getRandomInRange(170, 190) + 3; + this.createRandom() + this.offset = speed * getRandomInRange(170, 190) + 3 } for (const container of this.children) { - container.visible = true; + container.visible = true - container.x -= speed / 3 + 0.07; - container.y -= 0.06; - container.scale = 0.75; - container.alpha -= 0.005; + container.x -= speed / 3 + 0.07 + container.y -= 0.06 + container.scale = 0.75 + container.alpha -= 0.005 if (container.alpha <= 0) { - this.remove(container); + this.remove(container) } } } diff --git a/apps/client/src/game/components/wagonEngineContainer.ts b/apps/client/src/game/components/wagonEngineContainer.ts index 95d7bf68..e3089ec2 100644 --- a/apps/client/src/game/components/wagonEngineContainer.ts +++ b/apps/client/src/game/components/wagonEngineContainer.ts @@ -1,23 +1,23 @@ -import { Sprite } from "pixi.js"; -import type { IGameObjectDirection } from "../../../../../packages/api-sdk/src"; -import { GraphicsContainer } from "./graphicsContainer"; +import { Sprite } from "pixi.js" +import type { IGameObjectDirection } from "../../../../../packages/api-sdk/src" +import { GraphicsContainer } from "./graphicsContainer" interface IWagonEngineContainerOptions { - direction: IGameObjectDirection; + direction: IGameObjectDirection } export class WagonEngineContainer extends GraphicsContainer { constructor({ direction }: IWagonEngineContainerOptions) { - super({ type: "WAGON_ENGINE", direction }); + super({ type: "WAGON_ENGINE", direction }) } static create(spriteIndex: string, direction: IGameObjectDirection) { - const sprite = Sprite.from(spriteIndex); - sprite.anchor.set(0.5, 1); + const sprite = Sprite.from(spriteIndex) + sprite.anchor.set(0.5, 1) - const container = new WagonEngineContainer({ direction }); - container.addChild(sprite); + const container = new WagonEngineContainer({ direction }) + container.addChild(sprite) - return container; + return container } } diff --git a/apps/client/src/game/components/wagonWheelContainer.ts b/apps/client/src/game/components/wagonWheelContainer.ts index 1d3ae814..10fdb078 100644 --- a/apps/client/src/game/components/wagonWheelContainer.ts +++ b/apps/client/src/game/components/wagonWheelContainer.ts @@ -1,18 +1,18 @@ -import { Sprite } from "pixi.js"; -import type { IGameObjectDirection } from "../../../../../packages/api-sdk/src"; -import { GraphicsContainer } from "./graphicsContainer"; +import { Sprite } from "pixi.js" +import type { IGameObjectDirection } from "../../../../../packages/api-sdk/src" +import { GraphicsContainer } from "./graphicsContainer" interface IWagonWheelContainerOptions { - direction: IGameObjectDirection; - side: "LEFT" | "RIGHT"; + direction: IGameObjectDirection + side: "LEFT" | "RIGHT" } export class WagonWheelContainer extends GraphicsContainer { - public side: IWagonWheelContainerOptions["side"]; + public side: IWagonWheelContainerOptions["side"] constructor({ direction, side }: IWagonWheelContainerOptions) { - super({ type: "WAGON_WHEEL", direction }); - this.side = side; + super({ type: "WAGON_WHEEL", direction }) + this.side = side } static create( @@ -20,12 +20,12 @@ export class WagonWheelContainer extends GraphicsContainer { direction: IGameObjectDirection, side: IWagonWheelContainerOptions["side"], ) { - const sprite = Sprite.from(spriteIndex); - sprite.anchor.set(0.5, 0.5); + const sprite = Sprite.from(spriteIndex) + sprite.anchor.set(0.5, 0.5) - const container = new WagonWheelContainer({ direction, side }); - container.addChild(sprite); + const container = new WagonWheelContainer({ direction, side }) + container.addChild(sprite) - return container; + return container } } diff --git a/apps/client/src/game/game.ts b/apps/client/src/game/game.ts index d51073ce..261007ec 100644 --- a/apps/client/src/game/game.ts +++ b/apps/client/src/game/game.ts @@ -1,4 +1,4 @@ -import { Container } from "pixi.js"; +import { Container } from "pixi.js" import type { IGameBuildingCampfire, IGameBuildingWagonStop, @@ -7,6 +7,7 @@ import type { IGameObjectCourier, IGameObjectFarmer, IGameObjectFlag, + IGameObjectLake, IGameObjectMechanic, IGameObjectPlayer, IGameObjectRabbit, @@ -16,466 +17,465 @@ import type { IGameObjectWagon, IGameObjectWolf, WebSocketMessage, - IGameObjectLake, -} from "../../../../packages/api-sdk/src"; +} from "../../../../packages/api-sdk/src" import { Flag, type GameObjectContainer, + Lake, Rabbit, Stone, Tree, Wolf, - Lake, -} from "./objects"; -import { Campfire } from "./objects/buildings/campfire"; -import { WagonStop } from "./objects/buildings/wagonStop"; -import { Warehouse } from "./objects/buildings/warehouse"; -import { Wagon } from "./objects/wagon"; +} from "./objects" +import { Campfire } from "./objects/buildings/campfire" +import { WagonStop } from "./objects/buildings/wagonStop" +import { Warehouse } from "./objects/buildings/warehouse" +import { Courier, Farmer, Mechanic, Player, Raider } from "./objects/units" +import { Wagon } from "./objects/wagon" import { AssetsManager, AudioManager, SceneManager, WebSocketManager, -} from "./utils"; -import { Player, Courier, Farmer, Mechanic, Raider } from "./objects/units"; -import { BackgroundGenerator } from "./utils/generators/background.ts"; +} from "./utils" +import { BackgroundGenerator } from "./utils/generators/background.ts" export class Game extends Container { - public children: GameObjectContainer[] = []; - public audio: AudioManager; - public scene: SceneManager; - public bg: BackgroundGenerator; - - public cameraOffsetX = 0; - public cameraMovementSpeedX = 0.008; - public cameraOffsetY = 0; - public cameraMovementSpeedY = 0.008; - public cameraX = 0; - public cameraY = 0; - public cameraPerfectX = 0; - public cameraPerfectY = 0; + public children: GameObjectContainer[] = [] + public audio: AudioManager + public scene: SceneManager + public bg: BackgroundGenerator + + public cameraOffsetX = 0 + public cameraMovementSpeedX = 0.008 + public cameraOffsetY = 0 + public cameraMovementSpeedY = 0.008 + public cameraX = 0 + public cameraY = 0 + public cameraPerfectX = 0 + public cameraPerfectY = 0 constructor() { - super(); + super() - this.audio = new AudioManager(); - this.scene = new SceneManager(); - this.bg = new BackgroundGenerator(this.scene.app); + this.audio = new AudioManager() + this.scene = new SceneManager() + this.bg = new BackgroundGenerator(this.scene.app) } async play() { - await AssetsManager.init(); + await AssetsManager.init() - this.audio.playBackgroundSound(); + this.audio.playBackgroundSound() - const bg = await this.bg.getGeneratedBackgroundTilingSprite(); - bg.x = -10000; - bg.y = -10000; - bg.width = 50000; - bg.height = 50000; - this.scene.app.stage.addChild(bg); + const bg = await this.bg.getGeneratedBackgroundTilingSprite() + bg.x = -10000 + bg.y = -10000 + bg.width = 50000 + bg.height = 50000 + this.scene.app.stage.addChild(bg) - this.scene.app.stage.addChild(this); + this.scene.app.stage.addChild(this) this.scene.app.ticker.add(() => { - this.animateObjects(); + this.animateObjects() - const wagon = this.children.find((child) => child instanceof Wagon); + const wagon = this.children.find((child) => child instanceof Wagon) if (wagon) { - this.moveCameraToWagon(wagon as Wagon); + this.moveCameraToWagon(wagon as Wagon) } - }); + }) - WebSocketManager.init(this); + WebSocketManager.init(this) setInterval(() => { - console.log("FPS", this.scene.app.ticker.FPS); - console.log("Objects", this.children.length); - }, 1000); + console.log("FPS", this.scene.app.ticker.FPS) + console.log("Objects", this.children.length) + }, 1000) } moveCameraToWagon(wagon: Wagon) { - const columnWidth = this.scene.app.screen.width / 6; + const columnWidth = this.scene.app.screen.width / 6 const leftPadding = - wagon.direction === "LEFT" ? columnWidth * 5 : columnWidth * 2; + wagon.direction === "LEFT" ? columnWidth * 5 : columnWidth * 2 - const topPadding = this.scene.app.screen.height / 2; + const topPadding = this.scene.app.screen.height / 2 - this.cameraPerfectX = -wagon.x + this.cameraOffsetX + leftPadding; - this.cameraPerfectY = -wagon.y + this.cameraOffsetY + topPadding; + this.cameraPerfectX = -wagon.x + this.cameraOffsetX + leftPadding + this.cameraPerfectY = -wagon.y + this.cameraOffsetY + topPadding - this.cameraX = this.cameraPerfectX; - this.cameraY = this.cameraPerfectY; + this.cameraX = this.cameraPerfectX + this.cameraY = this.cameraPerfectY if (Math.abs(this.cameraOffsetX) >= 20) { - this.cameraMovementSpeedX *= -1; + this.cameraMovementSpeedX *= -1 } - this.cameraOffsetX += this.cameraMovementSpeedX; + this.cameraOffsetX += this.cameraMovementSpeedX if (Math.abs(this.cameraOffsetY) >= 30) { - this.cameraMovementSpeedY *= -1; + this.cameraMovementSpeedY *= -1 } - this.cameraOffsetY += this.cameraMovementSpeedY; + this.cameraOffsetY += this.cameraMovementSpeedY - this.parent.x = this.cameraX; - this.parent.y = this.cameraY; + this.parent.x = this.cameraX + this.parent.y = this.cameraY } rebuildScene() { - this.children = []; + this.children = [] } findObject(id: string) { - return this.children.find((obj) => obj.id === id); + return this.children.find((obj) => obj.id === id) } initWagon(object: IGameObjectWagon) { - const wagon = new Wagon({ game: this, object }); - this.addChild(wagon); + const wagon = new Wagon({ game: this, object }) + this.addChild(wagon) } updateWagon(object: IGameObjectWagon) { - const wagon = this.findObject(object.id); + const wagon = this.findObject(object.id) if (wagon instanceof Wagon) { - wagon.update(object); + wagon.update(object) } } initTree(object: IGameObjectTree) { - const tree = new Tree({ game: this, object }); - this.addChild(tree); + const tree = new Tree({ game: this, object }) + this.addChild(tree) } updateTree(object: IGameObjectTree) { - const tree = this.findObject(object.id); + const tree = this.findObject(object.id) if (tree instanceof Tree) { - tree.update(object); + tree.update(object) } } initStone(object: IGameObjectStone) { - const stone = new Stone({ game: this, object }); - this.addChild(stone); + const stone = new Stone({ game: this, object }) + this.addChild(stone) } updateStone(object: IGameObjectStone) { - const stone = this.findObject(object.id); + const stone = this.findObject(object.id) if (stone instanceof Stone) { - stone.update(object); + stone.update(object) } } initPlayer(object: IGameObjectPlayer) { - const player = new Player({ game: this, object }); - this.addChild(player); + const player = new Player({ game: this, object }) + this.addChild(player) } updatePlayer(object: IGameObjectPlayer) { - const player = this.findObject(object.id); + const player = this.findObject(object.id) if (player instanceof Player) { - player.update(object); + player.update(object) } } initCourier(object: IGameObjectCourier) { - const courier = new Courier({ game: this, object }); - this.addChild(courier); + const courier = new Courier({ game: this, object }) + this.addChild(courier) } updateCourier(object: IGameObjectCourier) { - const courier = this.findObject(object.id); + const courier = this.findObject(object.id) if (courier instanceof Courier) { - courier.update(object); + courier.update(object) } } initFarmer(object: IGameObjectFarmer) { - const farmer = new Farmer({ game: this, object }); - this.addChild(farmer); + const farmer = new Farmer({ game: this, object }) + this.addChild(farmer) } updateFarmer(object: IGameObjectFarmer) { - const farmer = this.findObject(object.id); + const farmer = this.findObject(object.id) if (farmer instanceof Farmer) { - farmer.update(object); + farmer.update(object) } } initMechanic(object: IGameObjectMechanic) { - const unit = new Mechanic({ game: this, object }); - this.addChild(unit); + const unit = new Mechanic({ game: this, object }) + this.addChild(unit) } updateMechanic(object: IGameObjectMechanic) { - const unit = this.findObject(object.id); + const unit = this.findObject(object.id) if (unit instanceof Mechanic) { - unit.update(object); + unit.update(object) } } initRaider(object: IGameObjectRaider) { - const raider = new Raider({ game: this, object }); - this.addChild(raider); + const raider = new Raider({ game: this, object }) + this.addChild(raider) } updateRaider(object: IGameObjectRaider) { - const raider = this.findObject(object.id); + const raider = this.findObject(object.id) if (raider instanceof Raider) { - raider.update(object); + raider.update(object) } } initRabbit(object: IGameObjectRabbit) { - const rabbit = new Rabbit({ game: this, object }); - this.addChild(rabbit); + const rabbit = new Rabbit({ game: this, object }) + this.addChild(rabbit) } updateRabbit(object: IGameObjectRabbit) { - const rabbit = this.findObject(object.id); + const rabbit = this.findObject(object.id) if (rabbit instanceof Rabbit) { - rabbit.update(object); + rabbit.update(object) } } initWolf(object: IGameObjectWolf) { - const wolf = new Wolf({ game: this, object }); - this.addChild(wolf); + const wolf = new Wolf({ game: this, object }) + this.addChild(wolf) } updateWolf(object: IGameObjectWolf) { - const wolf = this.findObject(object.id); + const wolf = this.findObject(object.id) if (wolf instanceof Wolf) { - wolf.update(object); + wolf.update(object) } } initLake(object: IGameObjectLake) { - const lake = new Lake({ game: this, object }); - this.addChild(lake); + const lake = new Lake({ game: this, object }) + this.addChild(lake) } updateLake(object: IGameObjectLake) { - const lake = this.findObject(object.id); + const lake = this.findObject(object.id) if (lake instanceof Lake) { - lake.update(object); + lake.update(object) } } initCampfire(object: IGameBuildingCampfire) { - const building = new Campfire({ game: this, object }); - this.addChild(building); + const building = new Campfire({ game: this, object }) + this.addChild(building) } updateCampfire(object: IGameBuildingCampfire) { - const building = this.findObject(object.id); + const building = this.findObject(object.id) if (building instanceof Campfire) { - building.update(object); + building.update(object) } } initWarehouse(object: IGameBuildingWarehouse) { - const building = new Warehouse({ game: this, object }); - this.addChild(building); + const building = new Warehouse({ game: this, object }) + this.addChild(building) } updateWarehouse(object: IGameBuildingWarehouse) { - const building = this.findObject(object.id); + const building = this.findObject(object.id) if (building instanceof Warehouse) { - building.update(object); + building.update(object) } } initWagonStop(object: IGameBuildingWagonStop) { - const building = new WagonStop({ game: this, object }); - this.addChild(building); + const building = new WagonStop({ game: this, object }) + this.addChild(building) } updateWagonStop(object: IGameBuildingWagonStop) { - const building = this.findObject(object.id); + const building = this.findObject(object.id) if (building instanceof WagonStop) { - building.update(object); + building.update(object) } } initFlag(object: IGameObjectFlag) { - const flag = new Flag({ game: this, object }); - this.addChild(flag); + const flag = new Flag({ game: this, object }) + this.addChild(flag) } updateFlag(object: IGameObjectFlag) { - const flag = this.findObject(object.id); + const flag = this.findObject(object.id) if (flag instanceof Flag) { - flag.update(object); + flag.update(object) } } checkIfThisFlagIsTarget(id: string) { for (const obj of this.children) { if (obj.target?.id === id) { - return true; + return true } } } animateObjects() { for (const object of this.children) { - object.animate(); + object.animate() } } handleMessage(message: WebSocketMessage) { if (message.object) { - this.handleMessageObject(message.object); + this.handleMessageObject(message.object) } if (message.event) { - this.handleMessageEvent(message.event); + this.handleMessageEvent(message.event) } } handleMessageObject(object: Partial) { if (!object.id) { - return; + return } - const obj = this.findObject(object.id); + const obj = this.findObject(object.id) if (!obj) { if (object.entity === "WAGON") { - this.initWagon(object as IGameObjectWagon); - return; + this.initWagon(object as IGameObjectWagon) + return } if (object.entity === "TREE") { - this.initTree(object as IGameObjectTree); - return; + this.initTree(object as IGameObjectTree) + return } if (object.entity === "STONE") { - this.initStone(object as IGameObjectStone); - return; + this.initStone(object as IGameObjectStone) + return } if (object.entity === "PLAYER") { - this.initPlayer(object as IGameObjectPlayer); - return; + this.initPlayer(object as IGameObjectPlayer) + return } if (object.entity === "COURIER") { - this.initCourier(object as IGameObjectCourier); - return; + this.initCourier(object as IGameObjectCourier) + return } if (object.entity === "FARMER") { - this.initFarmer(object as IGameObjectFarmer); - return; + this.initFarmer(object as IGameObjectFarmer) + return } if (object.entity === "MECHANIC") { - this.initMechanic(object as IGameObjectMechanic); - return; + this.initMechanic(object as IGameObjectMechanic) + return } if (object.entity === "RAIDER") { - this.initRaider(object as IGameObjectRaider); - return; + this.initRaider(object as IGameObjectRaider) + return } if (object.entity === "RABBIT") { - this.initRabbit(object as IGameObjectRabbit); - return; + this.initRabbit(object as IGameObjectRabbit) + return } if (object.entity === "WOLF") { - this.initWolf(object as IGameObjectWolf); - return; + this.initWolf(object as IGameObjectWolf) + return } if (object.entity === "LAKE") { - this.initLake(object as IGameObjectLake); - return; + this.initLake(object as IGameObjectLake) + return } if (object.entity === "CAMPFIRE") { - this.initCampfire(object as IGameBuildingCampfire); - return; + this.initCampfire(object as IGameBuildingCampfire) + return } if (object.entity === "WAREHOUSE") { - this.initWarehouse(object as IGameBuildingWarehouse); - return; + this.initWarehouse(object as IGameBuildingWarehouse) + return } if (object.entity === "WAGON_STOP") { - this.initWagonStop(object as IGameBuildingWagonStop); - return; + this.initWagonStop(object as IGameBuildingWagonStop) + return } if (object.entity === "FLAG") { - this.initFlag(object as IGameObjectFlag); - return; + this.initFlag(object as IGameObjectFlag) + return } - return; + return } if (object.entity === "WAGON") { - this.updateWagon(object as IGameObjectWagon); - return; + this.updateWagon(object as IGameObjectWagon) + return } if (object.entity === "TREE") { - this.updateTree(object as IGameObjectTree); - return; + this.updateTree(object as IGameObjectTree) + return } if (object.entity === "STONE") { - this.updateStone(object as IGameObjectStone); - return; + this.updateStone(object as IGameObjectStone) + return } if (object.entity === "PLAYER") { - this.updatePlayer(object as IGameObjectPlayer); - return; + this.updatePlayer(object as IGameObjectPlayer) + return } if (object.entity === "COURIER") { - this.updateCourier(object as IGameObjectCourier); - return; + this.updateCourier(object as IGameObjectCourier) + return } if (object.entity === "FARMER") { - this.updateFarmer(object as IGameObjectFarmer); - return; + this.updateFarmer(object as IGameObjectFarmer) + return } if (object.entity === "MECHANIC") { - this.updateMechanic(object as IGameObjectMechanic); - return; + this.updateMechanic(object as IGameObjectMechanic) + return } if (object.entity === "RAIDER") { - this.updateRaider(object as IGameObjectRaider); - return; + this.updateRaider(object as IGameObjectRaider) + return } if (object.entity === "RABBIT") { - this.updateRabbit(object as IGameObjectRabbit); - return; + this.updateRabbit(object as IGameObjectRabbit) + return } if (object.entity === "WOLF") { - this.updateWolf(object as IGameObjectWolf); - return; + this.updateWolf(object as IGameObjectWolf) + return } if (object.entity === "LAKE") { - this.updateLake(object as IGameObjectLake); - return; + this.updateLake(object as IGameObjectLake) + return } if (object.entity === "CAMPFIRE") { - this.updateCampfire(object as IGameBuildingCampfire); - return; + this.updateCampfire(object as IGameBuildingCampfire) + return } if (object.entity === "WAREHOUSE") { - this.updateWarehouse(object as IGameBuildingWarehouse); - return; + this.updateWarehouse(object as IGameBuildingWarehouse) + return } if (object.entity === "WAGON_STOP") { - this.updateWagonStop(object as IGameBuildingWagonStop); - return; + this.updateWagonStop(object as IGameBuildingWagonStop) + return } if (object.entity === "FLAG") { - this.updateFlag(object as IGameObjectFlag); - return; + this.updateFlag(object as IGameObjectFlag) + return } } handleMessageEvent(event: WebSocketMessage["event"]) { if (event === "RAID_STARTED") { - this.audio.playRaidSound(); + this.audio.playRaidSound() } if (event === "GROUP_FORM_STARTED") { - this.audio.playRaidSound(); + this.audio.playRaidSound() } if (event === "CREATING_NEW_ADVENTURE_STARTED") { - this.audio.playRaidSound(); + this.audio.playRaidSound() } if (event === "SCENE_CHANGED") { - this.rebuildScene(); + this.rebuildScene() } } } diff --git a/apps/client/src/game/index.ts b/apps/client/src/game/index.ts index 176c6cb8..4b77dae5 100644 --- a/apps/client/src/game/index.ts +++ b/apps/client/src/game/index.ts @@ -1,5 +1,5 @@ -import { Game } from "./game"; +import { Game } from "./game" -const game = new Game(); +const game = new Game() -void game.play(); +void game.play() diff --git a/apps/client/src/game/objects/buildings/building.ts b/apps/client/src/game/objects/buildings/building.ts index 977d46ef..c1f55d86 100644 --- a/apps/client/src/game/objects/buildings/building.ts +++ b/apps/client/src/game/objects/buildings/building.ts @@ -1,33 +1,33 @@ -import type { IGameObjectBuilding } from "../../../../../../packages/api-sdk/src"; -import type { Game } from "../../game"; -import { GameObjectContainer } from "../gameObjectContainer"; +import type { IGameObjectBuilding } from "../../../../../../packages/api-sdk/src" +import type { Game } from "../../game" +import { GameObjectContainer } from "../gameObjectContainer" interface IBuildingOptions { - game: Game; - object: IGameObjectBuilding; + game: Game + object: IGameObjectBuilding } export class Building extends GameObjectContainer implements IGameObjectBuilding { - public inventory!: IGameObjectBuilding["inventory"]; + public inventory!: IGameObjectBuilding["inventory"] constructor({ game, object }: IBuildingOptions) { - super({ game, ...object }); + super({ game, ...object }) - this.update(object); + this.update(object) } animate() { if (this.state === "DESTROYED") { - this.visible = false; + this.visible = false } } update(object: IGameObjectBuilding) { - super.update(object); + super.update(object) - this.inventory = object.inventory; + this.inventory = object.inventory } } diff --git a/apps/client/src/game/objects/buildings/campfire.ts b/apps/client/src/game/objects/buildings/campfire.ts index 704e3b73..b74a1f7a 100644 --- a/apps/client/src/game/objects/buildings/campfire.ts +++ b/apps/client/src/game/objects/buildings/campfire.ts @@ -1,57 +1,57 @@ -import { type AnimatedSprite, Sprite } from "pixi.js"; -import type { IGameBuildingCampfire } from "../../../../../../packages/api-sdk/src"; -import { FireParticlesContainer } from "../../components/fireParticlesContainer"; -import type { Game } from "../../game"; -import { AssetsManager } from "../../utils"; -import { Building } from "./building"; +import { type AnimatedSprite, Sprite } from "pixi.js" +import type { IGameBuildingCampfire } from "../../../../../../packages/api-sdk/src" +import { FireParticlesContainer } from "../../components/fireParticlesContainer" +import type { Game } from "../../game" +import { AssetsManager } from "../../utils" +import { Building } from "./building" interface ICampfireOptions { - game: Game; - object: IGameBuildingCampfire; + game: Game + object: IGameBuildingCampfire } export class Campfire extends Building implements IGameBuildingCampfire { - private fireAnimation!: AnimatedSprite; - private fireParticles!: FireParticlesContainer; + private fireAnimation!: AnimatedSprite + private fireParticles!: FireParticlesContainer constructor({ game, object }: ICampfireOptions) { - super({ game, object }); + super({ game, object }) - this.init(); + this.init() } init() { - const sprite = Sprite.from("campfire1"); - sprite.anchor.set(0.5, 1); + const sprite = Sprite.from("campfire1") + sprite.anchor.set(0.5, 1) - this.fireAnimation = AssetsManager.getAnimatedSpriteCampfire(); + this.fireAnimation = AssetsManager.getAnimatedSpriteCampfire() this.fireParticles = new FireParticlesContainer({ x: 0, y: -40, areaWidth: 40, - }); + }) - this.addChild(sprite, this.fireAnimation, this.fireParticles); + this.addChild(sprite, this.fireAnimation, this.fireParticles) } animate() { - super.animate(); + super.animate() - this.fireAnimation.animationSpeed = 0.08; - this.fireAnimation.play(); + this.fireAnimation.animationSpeed = 0.08 + this.fireAnimation.play() - this.fireParticles.animate(1); + this.fireParticles.animate(1) - this.handleSoundByState(); + this.handleSoundByState() } handleSoundByState() { if (!this.isVisibleOnClient) { - return; + return } if (this.state === "IDLE") { - this.game.audio.playCampfireSound(); + this.game.audio.playCampfireSound() } } } diff --git a/apps/client/src/game/objects/buildings/wagonStop.ts b/apps/client/src/game/objects/buildings/wagonStop.ts index bfc0cf3e..bec8b16b 100644 --- a/apps/client/src/game/objects/buildings/wagonStop.ts +++ b/apps/client/src/game/objects/buildings/wagonStop.ts @@ -1,34 +1,34 @@ -import { Sprite } from "pixi.js"; +import { Sprite } from "pixi.js" import type { IGameBuildingWagonStop, IGameObjectBuilding, -} from "../../../../../../packages/api-sdk/src"; -import type { Game } from "../../game"; -import { Building } from "./building"; +} from "../../../../../../packages/api-sdk/src" +import type { Game } from "../../game" +import { Building } from "./building" interface IWagonStopOptions { - game: Game; - object: IGameBuildingWagonStop; + game: Game + object: IGameBuildingWagonStop } export class WagonStop extends Building implements IGameBuildingWagonStop { constructor({ game, object }: IWagonStopOptions) { - super({ game, object }); + super({ game, object }) - this.init(); + this.init() } init() { - const sprite = Sprite.from("wagonStop1"); + const sprite = Sprite.from("wagonStop1") if (sprite) { - sprite.anchor.set(0.5, 0.92); - this.addChild(sprite); + sprite.anchor.set(0.5, 0.92) + this.addChild(sprite) } } update(object: IGameObjectBuilding) { - super.update(object); + super.update(object) - this.zIndex = Math.round(object.y - 100); + this.zIndex = Math.round(object.y - 100) } } diff --git a/apps/client/src/game/objects/buildings/warehouse.ts b/apps/client/src/game/objects/buildings/warehouse.ts index 3505b1ea..2e768cca 100644 --- a/apps/client/src/game/objects/buildings/warehouse.ts +++ b/apps/client/src/game/objects/buildings/warehouse.ts @@ -1,40 +1,40 @@ -import { Sprite } from "pixi.js"; -import type { IGameBuildingWarehouse } from "../../../../../../packages/api-sdk/src"; -import { BuildingInterface } from "../../components/buildingInterface"; -import type { Game } from "../../game"; -import { Building } from "./building"; +import { Sprite } from "pixi.js" +import type { IGameBuildingWarehouse } from "../../../../../../packages/api-sdk/src" +import { BuildingInterface } from "../../components/buildingInterface" +import type { Game } from "../../game" +import { Building } from "./building" interface IWarehouseOptions { - game: Game; - object: IGameBuildingWarehouse; + game: Game + object: IGameBuildingWarehouse } export class Warehouse extends Building implements IGameBuildingWarehouse { - public interface!: BuildingInterface; + public interface!: BuildingInterface constructor({ game, object }: IWarehouseOptions) { - super({ game, object }); + super({ game, object }) - this.init(); - this.initInterface(); + this.init() + this.initInterface() } init() { - const sprite = Sprite.from("warehouse1"); + const sprite = Sprite.from("warehouse1") if (sprite) { - sprite.anchor.set(0.5, 1); - this.addChild(sprite); + sprite.anchor.set(0.5, 1) + this.addChild(sprite) } } initInterface() { - this.interface = new BuildingInterface(this); - this.addChild(this.interface); + this.interface = new BuildingInterface(this) + this.addChild(this.interface) } animate() { - super.animate(); + super.animate() - this.interface.animate(); + this.interface.animate() } } diff --git a/apps/client/src/game/objects/flag.ts b/apps/client/src/game/objects/flag.ts index 11d16ed9..b4967af0 100644 --- a/apps/client/src/game/objects/flag.ts +++ b/apps/client/src/game/objects/flag.ts @@ -1,28 +1,28 @@ -import { Sprite } from "pixi.js"; -import type { IGameObjectFlag } from "../../../../../packages/api-sdk/src"; -import type { Game } from "../game"; -import { GameObjectContainer } from "./gameObjectContainer"; +import { Sprite } from "pixi.js" +import type { IGameObjectFlag } from "../../../../../packages/api-sdk/src" +import type { Game } from "../game" +import { GameObjectContainer } from "./gameObjectContainer" interface IFlagOptions { - game: Game; - object: IGameObjectFlag; + game: Game + object: IGameObjectFlag } export class Flag extends GameObjectContainer implements IGameObjectFlag { - public type!: IGameObjectFlag["type"]; + public type!: IGameObjectFlag["type"] constructor({ game, object }: IFlagOptions) { - super({ game, ...object }); + super({ game, ...object }) - this.update(object); - this.init(); + this.update(object) + this.init() } init() { - const sprite = this.getSpriteByType(); + const sprite = this.getSpriteByType() if (sprite) { - sprite.anchor.set(0.5, 1); - this.addChild(sprite); + sprite.anchor.set(0.5, 1) + this.addChild(sprite) } } @@ -32,35 +32,35 @@ export class Flag extends GameObjectContainer implements IGameObjectFlag { this.type === "WAGON_NEAR_MOVEMENT" || this.type === "WAGON_MOVEMENT" ) { - return Sprite.from("flag1"); + return Sprite.from("flag1") } if (this.type === "RESOURCE") { - return Sprite.from("flag2"); + return Sprite.from("flag2") } } animate() { - this.visible = false; + this.visible = false if ( this.type === "RESOURCE" && this.game.checkIfThisFlagIsTarget(this.id) ) { - this.visible = true; + this.visible = true } if (this.type === "WAGON_MOVEMENT" || this.type === "WAGON_NEAR_MOVEMENT") { - this.visible = true; + this.visible = true } if (this.state === "DESTROYED") { - this.visible = false; + this.visible = false } } update(object: IGameObjectFlag) { - super.update(object); + super.update(object) - this.type = object.type; + this.type = object.type } } diff --git a/apps/client/src/game/objects/gameObjectContainer.ts b/apps/client/src/game/objects/gameObjectContainer.ts index 2a75905b..7136db61 100644 --- a/apps/client/src/game/objects/gameObjectContainer.ts +++ b/apps/client/src/game/objects/gameObjectContainer.ts @@ -1,44 +1,42 @@ -import { Container } from "pixi.js"; -import type { - IGameObject -} from "../../../../../packages/api-sdk/src"; -import type { Game } from "../game"; +import { Container } from "pixi.js" +import type { IGameObject } from "../../../../../packages/api-sdk/src" +import type { Game } from "../game" interface IGameObjectContainerOptions extends IGameObject { - game: Game; + game: Game } export class GameObjectContainer extends Container implements IGameObject { - public id!: string; - public state!: IGameObject["state"]; - public direction!: IGameObject["direction"]; - public entity!: IGameObject["entity"]; - public target: IGameObject["target"]; - public health!: IGameObject["health"]; - public isVisibleOnClient!: IGameObject["isVisibleOnClient"]; + public id!: string + public state!: IGameObject["state"] + public direction!: IGameObject["direction"] + public entity!: IGameObject["entity"] + public target: IGameObject["target"] + public health!: IGameObject["health"] + public isVisibleOnClient!: IGameObject["isVisibleOnClient"] - public game: Game; + public game: Game constructor({ game, ...object }: IGameObjectContainerOptions) { - super(); + super() - this.game = game; - this.update(object); + this.game = game + this.update(object) } animate(): void {} update(object: IGameObject) { - this.x = object.x; - this.y = object.y; - this.zIndex = Math.round(object.y); - - this.id = object.id; - this.entity = object.entity; - this.state = object.state; - this.direction = object.direction; - this.health = object.health; - this.target = object.target; - this.isVisibleOnClient = object.isVisibleOnClient; + this.x = object.x + this.y = object.y + this.zIndex = Math.round(object.y) + + this.id = object.id + this.entity = object.entity + this.state = object.state + this.direction = object.direction + this.health = object.health + this.target = object.target + this.isVisibleOnClient = object.isVisibleOnClient } } diff --git a/apps/client/src/game/objects/index.ts b/apps/client/src/game/objects/index.ts index f332375c..c8cbdd56 100644 --- a/apps/client/src/game/objects/index.ts +++ b/apps/client/src/game/objects/index.ts @@ -1,7 +1,7 @@ -export { GameObjectContainer } from "./gameObjectContainer"; -export { Rabbit } from "./rabbit"; -export { Stone } from "./stone"; -export { Tree } from "./tree"; -export { Wolf } from "./wolf"; -export { Flag } from "./flag"; +export { GameObjectContainer } from "./gameObjectContainer" +export { Rabbit } from "./rabbit" +export { Stone } from "./stone" +export { Tree } from "./tree" +export { Wolf } from "./wolf" +export { Flag } from "./flag" export { Lake } from "./lake" diff --git a/apps/client/src/game/objects/lake.ts b/apps/client/src/game/objects/lake.ts index 17823675..026ec154 100644 --- a/apps/client/src/game/objects/lake.ts +++ b/apps/client/src/game/objects/lake.ts @@ -1,37 +1,37 @@ -import { GameObjectContainer } from "./gameObjectContainer"; -import type { IGameObjectLake, } from "../../../../../packages/api-sdk/src"; -import type { Game } from "../game"; -import { AssetsManager } from "../utils"; +import type { IGameObjectLake } from "../../../../../packages/api-sdk/src" +import type { Game } from "../game" +import { AssetsManager } from "../utils" +import { GameObjectContainer } from "./gameObjectContainer" interface ILakeOptions { - game: Game; - object: IGameObjectLake; + game: Game + object: IGameObjectLake } export class Lake extends GameObjectContainer implements IGameObjectLake { - public water!: IGameObjectLake["water"]; + public water!: IGameObjectLake["water"] constructor({ game, object }: ILakeOptions) { - super({ game, ...object }); + super({ game, ...object }) - this.update(object); - this.water = object.water; - this.init(); + this.update(object) + this.water = object.water + this.init() } init() { for (const w of this.water) { - const sprite = AssetsManager.getRandomSpriteForWater(); - sprite.anchor.set(0.5, 1); - sprite.x = w.x; - sprite.y = w.y; - this.addChild(sprite); + const sprite = AssetsManager.getRandomSpriteForWater() + sprite.anchor.set(0.5, 1) + sprite.x = w.x + sprite.y = w.y + this.addChild(sprite) } } update(object: IGameObjectLake) { - super.update(object); + super.update(object) - this.zIndex = 0; + this.zIndex = 0 } -} \ No newline at end of file +} diff --git a/apps/client/src/game/objects/rabbit.ts b/apps/client/src/game/objects/rabbit.ts index 181b46d2..63afc90b 100644 --- a/apps/client/src/game/objects/rabbit.ts +++ b/apps/client/src/game/objects/rabbit.ts @@ -1,59 +1,59 @@ -import { Sprite } from "pixi.js"; -import type { IGameObjectRabbit } from "../../../../../packages/api-sdk/src"; -import type { Game } from "../game"; -import { GameObjectContainer } from "./gameObjectContainer"; +import { Sprite } from "pixi.js" +import type { IGameObjectRabbit } from "../../../../../packages/api-sdk/src" +import type { Game } from "../game" +import { GameObjectContainer } from "./gameObjectContainer" interface IRabbitOptions { - game: Game; - object: IGameObjectRabbit; + game: Game + object: IGameObjectRabbit } export class Rabbit extends GameObjectContainer implements IGameObjectRabbit { - public animationAngle = 0; + public animationAngle = 0 constructor({ game, object }: IRabbitOptions) { - super({ game, ...object }); + super({ game, ...object }) - this.update(object); - this.init(); + this.update(object) + this.init() } init() { - const spriteRight = Sprite.from("rabbitRight"); - const spriteLeft = Sprite.from("rabbitLeft"); + const spriteRight = Sprite.from("rabbitRight") + const spriteLeft = Sprite.from("rabbitLeft") - spriteRight.anchor.set(0.5, 1); - spriteLeft.anchor.set(0.5, 1); + spriteRight.anchor.set(0.5, 1) + spriteLeft.anchor.set(0.5, 1) - spriteLeft.direction = "LEFT"; - spriteRight.direction = "RIGHT"; + spriteLeft.direction = "LEFT" + spriteRight.direction = "RIGHT" - this.addChild(spriteRight, spriteLeft); + this.addChild(spriteRight, spriteLeft) } animate() { // Hide all for (const t of this.children) { - t.visible = false; + t.visible = false } // Visible only 1 - const sprite = this.children.find((t) => t.direction === this.direction); + const sprite = this.children.find((t) => t.direction === this.direction) if (sprite) { - sprite.visible = true; + sprite.visible = true } if (this.state === "MOVING") { - this.angle = this.animationAngle; - this.shakeAnimation(); + this.angle = this.animationAngle + this.shakeAnimation() } } shakeAnimation() { if (this.animationAngle >= 4) { - this.animationAngle = 0; - return; + this.animationAngle = 0 + return } - this.animationAngle += 0.08; + this.animationAngle += 0.08 } } diff --git a/apps/client/src/game/objects/stone.ts b/apps/client/src/game/objects/stone.ts index 91a65fd4..ca526863 100644 --- a/apps/client/src/game/objects/stone.ts +++ b/apps/client/src/game/objects/stone.ts @@ -1,66 +1,66 @@ -import { Sprite } from "pixi.js"; -import type { IGameObjectStone } from "../../../../../packages/api-sdk/src"; -import type { Game } from "../game"; -import { GameObjectContainer } from "./gameObjectContainer"; +import { Sprite } from "pixi.js" +import type { IGameObjectStone } from "../../../../../packages/api-sdk/src" +import type { Game } from "../game" +import { GameObjectContainer } from "./gameObjectContainer" interface IStoneOptions { - game: Game; - object: IGameObjectStone; + game: Game + object: IGameObjectStone } export class Stone extends GameObjectContainer implements IGameObjectStone { - public type!: IGameObjectStone["type"]; - public resource!: number; - public size!: number; + public type!: IGameObjectStone["type"] + public resource!: number + public size!: number - public animationAngle = 0; - public animationHighSpeed = 0.05; + public animationAngle = 0 + public animationHighSpeed = 0.05 constructor({ game, object }: IStoneOptions) { - super({ game, ...object }); + super({ game, ...object }) - this.update(object); - this.init(); + this.update(object) + this.init() } init() { - const sprite = this.getSpriteByType(); + const sprite = this.getSpriteByType() if (sprite) { - sprite.anchor.set(0.5, 1); - this.addChild(sprite); + sprite.anchor.set(0.5, 1) + this.addChild(sprite) } } getSpriteByType() { if (this.type === "1") { - return Sprite.from("stone1"); + return Sprite.from("stone1") } } animate() { if (this.state === "DESTROYED") { - this.visible = false; + this.visible = false } if (this.state === "MINING") { - this.scale = 0.98; - this.shakeAnimation(); + this.scale = 0.98 + this.shakeAnimation() } } shakeAnimation() { if (Math.abs(this.animationAngle) >= 0.5) { - this.animationHighSpeed *= -1; + this.animationHighSpeed *= -1 } - this.animationAngle += this.animationHighSpeed; - this.angle = this.animationAngle; + this.animationAngle += this.animationHighSpeed + this.angle = this.animationAngle } update(object: IGameObjectStone) { - super.update(object); + super.update(object) - this.type = object.type; - this.resource = object.resource; - this.size = object.size; + this.type = object.type + this.resource = object.resource + this.size = object.size } } diff --git a/apps/client/src/game/objects/tree.ts b/apps/client/src/game/objects/tree.ts index 1a08a2ab..68fc763f 100644 --- a/apps/client/src/game/objects/tree.ts +++ b/apps/client/src/game/objects/tree.ts @@ -1,125 +1,125 @@ -import { Sprite } from "pixi.js"; +import { Sprite } from "pixi.js" import { type IGameObjectTree, getRandomInRange, -} from "../../../../../packages/api-sdk/src"; -import type { Game } from "../game"; -import { GameObjectContainer } from "./gameObjectContainer"; +} from "../../../../../packages/api-sdk/src" +import type { Game } from "../game" +import { GameObjectContainer } from "./gameObjectContainer" interface ITreeOptions { - game: Game; - object: IGameObjectTree; + game: Game + object: IGameObjectTree } export class Tree extends GameObjectContainer implements IGameObjectTree { - public type!: IGameObjectTree["type"]; - public variant!: IGameObjectTree["variant"]; - public resource!: number; - public size!: number; - public isReadyToChop!: boolean; + public type!: IGameObjectTree["type"] + public variant!: IGameObjectTree["variant"] + public resource!: number + public size!: number + public isReadyToChop!: boolean - public animationAngle = getRandomInRange(-1, 1); - public animationSlowSpeed = 0.04; - public animationHighSpeed = 0.15; + public animationAngle = getRandomInRange(-1, 1) + public animationSlowSpeed = 0.04 + public animationHighSpeed = 0.15 constructor({ game, object }: ITreeOptions) { - super({ game, ...object }); + super({ game, ...object }) - this.update(object); - this.init(); + this.update(object) + this.init() } init() { - const sprite = this.getSpriteByType(); + const sprite = this.getSpriteByType() if (sprite) { - sprite.anchor.set(0.5, 1); - this.addChild(sprite); + sprite.anchor.set(0.5, 1) + this.addChild(sprite) } } getSpriteByType() { if (this.type === "1") { if (this.variant === "GREEN") { - return Sprite.from("tree1Green"); + return Sprite.from("tree1Green") } if (this.variant === "BLUE") { - return Sprite.from("tree1Blue"); + return Sprite.from("tree1Blue") } if (this.variant === "STONE") { - return Sprite.from("tree1Stone"); + return Sprite.from("tree1Stone") } if (this.variant === "TEAL") { - return Sprite.from("tree1Teal"); + return Sprite.from("tree1Teal") } if (this.variant === "TOXIC") { - return Sprite.from("tree1Toxic"); + return Sprite.from("tree1Toxic") } if (this.variant === "VIOLET") { - return Sprite.from("tree1Violet"); + return Sprite.from("tree1Violet") } } if (this.type === "2") { - return Sprite.from("tree2"); + return Sprite.from("tree2") } if (this.type === "3") { - const random = getRandomInRange(1, 3); + const random = getRandomInRange(1, 3) if (random === 1) { - return Sprite.from("tree3"); + return Sprite.from("tree3") } if (random === 2) { - return Sprite.from("tree7"); + return Sprite.from("tree7") } if (random === 3) { - return Sprite.from("tree10"); + return Sprite.from("tree10") } } if (this.type === "4") { - return Sprite.from("tree4"); + return Sprite.from("tree4") } if (this.type === "5") { - return Sprite.from("tree5"); + return Sprite.from("tree5") } } animate() { - this.scale = this.size / 100; + this.scale = this.size / 100 if (this.state === "IDLE") { - this.shakeOnWind(); + this.shakeOnWind() } if (this.state === "DESTROYED") { - this.visible = false; + this.visible = false } if (this.state === "CHOPPING") { - this.shakeAnimation(); + this.shakeAnimation() } } shakeAnimation() { if (Math.abs(this.animationAngle) >= 2.5) { - this.animationHighSpeed *= -1; + this.animationHighSpeed *= -1 } - this.animationAngle += this.animationHighSpeed; - this.angle = this.animationAngle; + this.animationAngle += this.animationHighSpeed + this.angle = this.animationAngle } shakeOnWind() { if (Math.abs(this.animationAngle) >= 1.5) { - this.animationSlowSpeed *= -1; + this.animationSlowSpeed *= -1 } - this.animationAngle += this.animationSlowSpeed; - this.angle = this.animationAngle; + this.animationAngle += this.animationSlowSpeed + this.angle = this.animationAngle } update(object: IGameObjectTree) { - super.update(object); + super.update(object) - this.type = object.type; - this.variant = object.variant; - this.isReadyToChop = object.isReadyToChop; - this.resource = object.resource; - this.size = object.size; + this.type = object.type + this.variant = object.variant + this.isReadyToChop = object.isReadyToChop + this.resource = object.resource + this.size = object.size } } diff --git a/apps/client/src/game/objects/units/courier.ts b/apps/client/src/game/objects/units/courier.ts index d3256723..09681d4d 100644 --- a/apps/client/src/game/objects/units/courier.ts +++ b/apps/client/src/game/objects/units/courier.ts @@ -1,14 +1,14 @@ -import type { IGameObjectCourier } from "../../../../../../packages/api-sdk/src"; -import type { Game } from "../../game"; -import { Unit } from "./unit"; +import type { IGameObjectCourier } from "../../../../../../packages/api-sdk/src" +import type { Game } from "../../game" +import { Unit } from "./unit" interface ICourierOptions { - game: Game; - object: IGameObjectCourier; + game: Game + object: IGameObjectCourier } export class Courier extends Unit implements IGameObjectCourier { constructor({ game, object }: ICourierOptions) { - super({ game, object }); + super({ game, object }) } } diff --git a/apps/client/src/game/objects/units/farmer.ts b/apps/client/src/game/objects/units/farmer.ts index b1b9b02c..1f9b8e3d 100644 --- a/apps/client/src/game/objects/units/farmer.ts +++ b/apps/client/src/game/objects/units/farmer.ts @@ -1,14 +1,14 @@ -import type { IGameObjectFarmer } from "../../../../../../packages/api-sdk/src"; -import type { Game } from "../../game"; -import { Unit } from "./unit"; +import type { IGameObjectFarmer } from "../../../../../../packages/api-sdk/src" +import type { Game } from "../../game" +import { Unit } from "./unit" interface IFarmerOptions { - game: Game; - object: IGameObjectFarmer; + game: Game + object: IGameObjectFarmer } export class Farmer extends Unit implements IGameObjectFarmer { constructor({ game, object }: IFarmerOptions) { - super({ game, object }); + super({ game, object }) } } diff --git a/apps/client/src/game/objects/units/index.ts b/apps/client/src/game/objects/units/index.ts index 0b6cdd0b..e2481df9 100644 --- a/apps/client/src/game/objects/units/index.ts +++ b/apps/client/src/game/objects/units/index.ts @@ -3,4 +3,4 @@ export { Farmer } from "./farmer" export { Mechanic } from "./mechanic" export { Player } from "./player" export { Raider } from "./raider" -export { Unit } from "./unit" \ No newline at end of file +export { Unit } from "./unit" diff --git a/apps/client/src/game/objects/units/mechanic.ts b/apps/client/src/game/objects/units/mechanic.ts index 420c97de..dedf0128 100644 --- a/apps/client/src/game/objects/units/mechanic.ts +++ b/apps/client/src/game/objects/units/mechanic.ts @@ -1,23 +1,23 @@ import type { IGameObjectMechanic, IGameObjectUnit, -} from "../../../../../../packages/api-sdk/src"; -import type { Game } from "../../game"; -import { Unit } from "./unit"; +} from "../../../../../../packages/api-sdk/src" +import type { Game } from "../../game" +import { Unit } from "./unit" interface IMechanicOptions { - game: Game; - object: IGameObjectMechanic; + game: Game + object: IGameObjectMechanic } export class Mechanic extends Unit implements IGameObjectMechanic { constructor({ game, object }: IMechanicOptions) { - super({ game, object }); + super({ game, object }) } update(object: IGameObjectUnit) { - super.update(object); + super.update(object) - this.zIndex = Math.round(object.y + 100); + this.zIndex = Math.round(object.y + 100) } } diff --git a/apps/client/src/game/objects/units/player.ts b/apps/client/src/game/objects/units/player.ts index a9654458..4bca809b 100644 --- a/apps/client/src/game/objects/units/player.ts +++ b/apps/client/src/game/objects/units/player.ts @@ -1,97 +1,97 @@ import type { IGameObjectPlayer, IGameSkill, -} from "../../../../../../packages/api-sdk/src"; -import { PlayerInterface } from "../../components/playerInterface"; -import type { Game } from "../../game"; -import { Unit } from "./unit"; +} from "../../../../../../packages/api-sdk/src" +import { PlayerInterface } from "../../components/playerInterface" +import type { Game } from "../../game" +import { Unit } from "./unit" interface IPlayerOptions { - game: Game; - object: IGameObjectPlayer; + game: Game + object: IGameObjectPlayer } export class Player extends Unit implements IGameObjectPlayer { - reputation!: number; - villainPoints!: number; - refuellerPoints!: number; - userName!: string; - skills!: IGameSkill[]; + reputation!: number + villainPoints!: number + refuellerPoints!: number + userName!: string + skills!: IGameSkill[] constructor({ game, object }: IPlayerOptions) { - super({ game, object }); - this.update(object); + super({ game, object }) + this.update(object) - this.init(); + this.init() } init() { - super.init(); + super.init() - this.initInterface(); - super.addChild(this.interface); + this.initInterface() + super.addChild(this.interface) } initInterface() { - this.interface = new PlayerInterface(this); + this.interface = new PlayerInterface(this) } animate() { - super.animate(); + super.animate() - this.interface.animate(); - this.showToolInHand(); - this.handleSoundByState(); + this.interface.animate() + this.showToolInHand() + this.handleSoundByState() } showToolInHand() { - let interfaceContainer: PlayerInterface | undefined; + let interfaceContainer: PlayerInterface | undefined for (const container of this.children) { if (container instanceof PlayerInterface) { - interfaceContainer = container; + interfaceContainer = container } } if (!interfaceContainer) { - return; + return } if (this.state === "CHOPPING") { - interfaceContainer.showAxeInHand(); + interfaceContainer.showAxeInHand() } if (this.state === "MINING") { - interfaceContainer.showPickaxeInHand(); + interfaceContainer.showPickaxeInHand() } } handleSoundByState() { if (this.state === "CHOPPING") { if (this.inventory?.items.find((item) => item.type === "AXE")) { - this.game.audio.playChopWithAxeSound(); - return; + this.game.audio.playChopWithAxeSound() + return } - this.game.audio.playHandPunch(); + this.game.audio.playHandPunch() } if (this.state === "MINING") { if (this.inventory?.items.find((item) => item.type === "PICKAXE")) { - this.game.audio.playMineWithPickaxeSound(); - return; + this.game.audio.playMineWithPickaxeSound() + return } - this.game.audio.playHandPunch(); + this.game.audio.playHandPunch() } } update(object: IGameObjectPlayer) { - super.update(object); + super.update(object) - this.reputation = object.reputation; - this.villainPoints = object.villainPoints; - this.refuellerPoints = object.refuellerPoints; - this.userName = object.userName; - this.skills = object.skills; + this.reputation = object.reputation + this.villainPoints = object.villainPoints + this.refuellerPoints = object.refuellerPoints + this.userName = object.userName + this.skills = object.skills } } diff --git a/apps/client/src/game/objects/units/raider.ts b/apps/client/src/game/objects/units/raider.ts index 755ea251..e4a0dcee 100644 --- a/apps/client/src/game/objects/units/raider.ts +++ b/apps/client/src/game/objects/units/raider.ts @@ -1,17 +1,17 @@ -import type { IGameObjectRaider } from "../../../../../../packages/api-sdk/src"; -import type { Game } from "../../game"; -import { Unit } from "./unit"; +import type { IGameObjectRaider } from "../../../../../../packages/api-sdk/src" +import type { Game } from "../../game" +import { Unit } from "./unit" interface IRaiderOptions { - game: Game; - object: IGameObjectRaider; + game: Game + object: IGameObjectRaider } export class Raider extends Unit implements IGameObjectRaider { - userName!: string; - colorIndex!: number; + userName!: string + colorIndex!: number constructor({ game, object }: IRaiderOptions) { - super({ game, object }); + super({ game, object }) } } diff --git a/apps/client/src/game/objects/units/unit.ts b/apps/client/src/game/objects/units/unit.ts index 88a6d5b3..ce3afeaa 100644 --- a/apps/client/src/game/objects/units/unit.ts +++ b/apps/client/src/game/objects/units/unit.ts @@ -1,49 +1,49 @@ -import type { AnimatedSprite } from "pixi.js"; +import type { AnimatedSprite } from "pixi.js" import type { IGameInventory, IGameObjectUnit, -} from "../../../../../../packages/api-sdk/src"; -import type { GraphicsContainer } from "../../components/graphicsContainer"; -import { UnitHairContainer } from "../../components/unitHairContainer"; -import { UnitHeadContainer } from "../../components/unitHeadContainer"; -import { UnitInterface } from "../../components/unitInterface"; -import { UnitTopContainer } from "../../components/unitTopContainer"; -import type { Game } from "../../game"; -import { AssetsManager } from "../../utils"; -import { Flag } from "../flag"; -import { GameObjectContainer } from "../gameObjectContainer"; +} from "../../../../../../packages/api-sdk/src" +import type { GraphicsContainer } from "../../components/graphicsContainer" +import { UnitHairContainer } from "../../components/unitHairContainer" +import { UnitHeadContainer } from "../../components/unitHeadContainer" +import { UnitInterface } from "../../components/unitInterface" +import { UnitTopContainer } from "../../components/unitTopContainer" +import type { Game } from "../../game" +import { AssetsManager } from "../../utils" +import { Flag } from "../flag" +import { GameObjectContainer } from "../gameObjectContainer" interface IUnitOptions { - game: Game; - object: IGameObjectUnit; + game: Game + object: IGameObjectUnit } export class Unit extends GameObjectContainer implements IGameObjectUnit { - public inventory!: IGameInventory; - public visual!: IGameObjectUnit["visual"]; - public coins = 0; + public inventory!: IGameInventory + public visual!: IGameObjectUnit["visual"] + public coins = 0 - public interface!: UnitInterface; - public children: GraphicsContainer[] = []; - animationMovingLeft!: AnimatedSprite; - animationMovingRight!: AnimatedSprite; + public interface!: UnitInterface + public children: GraphicsContainer[] = [] + animationMovingLeft!: AnimatedSprite + animationMovingRight!: AnimatedSprite constructor({ game, object }: IUnitOptions) { - super({ game, ...object }); - this.update(object); + super({ game, ...object }) + this.update(object) - this.animationMovingLeft = AssetsManager.getAnimatedSpriteHeroLeft(); - this.animationMovingRight = AssetsManager.getAnimatedSpriteHeroRight(); + this.animationMovingLeft = AssetsManager.getAnimatedSpriteHeroLeft() + this.animationMovingRight = AssetsManager.getAnimatedSpriteHeroRight() - this.init(); + this.init() } init() { - const top = this.initTop(); - const head = this.initHead(); - const hair = this.initHair(); + const top = this.initTop() + const head = this.initHead() + const hair = this.initHair() - this.initInterface(); + this.initInterface() this.addChild( ...top, @@ -52,40 +52,40 @@ export class Unit extends GameObjectContainer implements IGameObjectUnit { this.animationMovingLeft, this.animationMovingRight, this.interface, - ); + ) } initTop() { - return UnitTopContainer.getAll(); + return UnitTopContainer.getAll() } initHead() { - return UnitHeadContainer.getAll(); + return UnitHeadContainer.getAll() } initHair() { - return UnitHairContainer.getAll(); + return UnitHairContainer.getAll() } initInterface() { - this.interface = new UnitInterface(this); + this.interface = new UnitInterface(this) } animate() { for (const container of this.children) { - container.visible = false; + container.visible = false if (this.state === "MOVING") { - this.animationMovingLeft.animationSpeed = 0.25; - this.animationMovingRight.animationSpeed = 0.25; + this.animationMovingLeft.animationSpeed = 0.25 + this.animationMovingRight.animationSpeed = 0.25 if (this.direction === "RIGHT") { - this.animationMovingRight.visible = true; - this.animationMovingRight.play(); + this.animationMovingRight.visible = true + this.animationMovingRight.play() } if (this.direction === "LEFT") { - this.animationMovingLeft.visible = true; - this.animationMovingLeft.play(); + this.animationMovingLeft.visible = true + this.animationMovingLeft.play() } } @@ -94,77 +94,77 @@ export class Unit extends GameObjectContainer implements IGameObjectUnit { this.state === "CHOPPING" || this.state === "MINING" ) { - this.animationMovingLeft.animationSpeed = 0; - this.animationMovingRight.animationSpeed = 0; - this.animationMovingLeft.currentFrame = 0; - this.animationMovingRight.currentFrame = 0; + this.animationMovingLeft.animationSpeed = 0 + this.animationMovingRight.animationSpeed = 0 + this.animationMovingLeft.currentFrame = 0 + this.animationMovingRight.currentFrame = 0 if (this.direction === "LEFT") { - this.animationMovingLeft.visible = true; + this.animationMovingLeft.visible = true } if (this.direction === "RIGHT") { - this.animationMovingRight.visible = true; + this.animationMovingRight.visible = true } } - this.drawTop(container); - this.drawHead(container); - this.drawHair(container); + this.drawTop(container) + this.drawHead(container) + this.drawHair(container) } - this.interface.animate(); + this.interface.animate() if (this.target && this.target instanceof Flag) { - this.target.visible = true; + this.target.visible = true } } drawTop(container: GraphicsContainer) { if (container instanceof UnitTopContainer) { if (container.visual !== this.visual.top) { - return; + return } if (container.direction !== this.direction) { - return; + return } - container.visible = true; + container.visible = true } } drawHead(container: GraphicsContainer) { if (container instanceof UnitHeadContainer) { if (container.visual !== this.visual.head) { - return; + return } if (container.direction !== this.direction) { - return; + return } - container.visible = true; + container.visible = true } } drawHair(container: GraphicsContainer) { if (container instanceof UnitHairContainer) { if (container.visual !== this.visual.hairstyle) { - return; + return } if (container.direction !== this.direction) { - return; + return } - container.visible = true; + container.visible = true } } update(object: IGameObjectUnit) { - super.update(object); + super.update(object) - this.zIndex = Math.round(object.y + 1); + this.zIndex = Math.round(object.y + 1) - this.inventory = object.inventory; - this.visual = object.visual; - this.coins = object.coins; + this.inventory = object.inventory + this.visual = object.visual + this.coins = object.coins } } diff --git a/apps/client/src/game/objects/wagon.ts b/apps/client/src/game/objects/wagon.ts index 7d07f864..37ec04d4 100644 --- a/apps/client/src/game/objects/wagon.ts +++ b/apps/client/src/game/objects/wagon.ts @@ -1,108 +1,106 @@ -import { Sprite } from "pixi.js"; -import type { IGameObjectWagon } from "../../../../../packages/api-sdk/src"; -import type { GraphicsContainer } from "../components/graphicsContainer"; -import { - WagonEngineCloudsContainer -} from "../components/wagonEngineCloudsContainer"; -import { WagonEngineContainer } from "../components/wagonEngineContainer"; -import { WagonWheelContainer } from "../components/wagonWheelContainer"; -import type { Game } from "../game"; -import { GameObjectContainer } from "./gameObjectContainer"; +import { Sprite } from "pixi.js" +import type { IGameObjectWagon } from "../../../../../packages/api-sdk/src" +import type { GraphicsContainer } from "../components/graphicsContainer" +import { WagonEngineCloudsContainer } from "../components/wagonEngineCloudsContainer" +import { WagonEngineContainer } from "../components/wagonEngineContainer" +import { WagonWheelContainer } from "../components/wagonWheelContainer" +import type { Game } from "../game" +import { GameObjectContainer } from "./gameObjectContainer" interface IWagonOptions { - game: Game; - object: IGameObjectWagon; + game: Game + object: IGameObjectWagon } export class Wagon extends GameObjectContainer implements IGameObjectWagon { - public speed!: number; - public fuel!: number; - public visibilityArea!: IGameObjectWagon["visibilityArea"]; + public speed!: number + public fuel!: number + public visibilityArea!: IGameObjectWagon["visibilityArea"] - public children: GraphicsContainer[] = []; + public children: GraphicsContainer[] = [] constructor({ game, object }: IWagonOptions) { - super({ game, ...object }); + super({ game, ...object }) - this.update(object); - this.init(); + this.update(object) + this.init() } init() { - const spriteSide = Sprite.from("wagonBase1"); - spriteSide.anchor.set(0.5, 1); - spriteSide.scale = 0.75; + const spriteSide = Sprite.from("wagonBase1") + spriteSide.anchor.set(0.5, 1) + spriteSide.scale = 0.75 - const spriteBase = Sprite.from("wagonBase2"); - spriteBase.anchor.set(0.5, 1); - spriteBase.scale = 0.75; + const spriteBase = Sprite.from("wagonBase2") + spriteBase.anchor.set(0.5, 1) + spriteBase.scale = 0.75 - const engine = WagonEngineContainer.create("wagonEngine1", "RIGHT"); - engine.scale = 0.75; + const engine = WagonEngineContainer.create("wagonEngine1", "RIGHT") + engine.scale = 0.75 - const wheel1 = WagonWheelContainer.create("wagonWheel1", "RIGHT", "LEFT"); - const wheel2 = WagonWheelContainer.create("wagonWheel1", "RIGHT", "RIGHT"); - wheel1.scale = 0.75; - wheel2.scale = 0.75; + const wheel1 = WagonWheelContainer.create("wagonWheel1", "RIGHT", "LEFT") + const wheel2 = WagonWheelContainer.create("wagonWheel1", "RIGHT", "RIGHT") + wheel1.scale = 0.75 + wheel2.scale = 0.75 - const clouds = new WagonEngineCloudsContainer(); + const clouds = new WagonEngineCloudsContainer() - this.addChild(spriteBase, engine, spriteSide, wheel1, wheel2, clouds); + this.addChild(spriteBase, engine, spriteSide, wheel1, wheel2, clouds) } animate() { for (const container of this.children) { - container.visible = true; + container.visible = true - this.drawWheels(container); - this.drawEngine(container); + this.drawWheels(container) + this.drawEngine(container) if (container instanceof WagonEngineCloudsContainer) { - container.animate(this.speed); + container.animate(this.speed) } } - this.handleSoundByState(); + this.handleSoundByState() } drawWheels(container: GraphicsContainer) { if (container instanceof WagonWheelContainer) { if (container.side === "LEFT") { - container.x = -123; - container.y = -16; + container.x = -123 + container.y = -16 } if (container.side === "RIGHT") { - container.x = 123; - container.y = -16; + container.x = 123 + container.y = -16 } - container.visible = true; + container.visible = true - const wheelRotation = this.direction === "LEFT" ? -1 : 1; + const wheelRotation = this.direction === "LEFT" ? -1 : 1 - container.angle += (wheelRotation * this.speed) / 2.5; + container.angle += (wheelRotation * this.speed) / 2.5 } } drawEngine(container: GraphicsContainer) { if (container instanceof WagonEngineContainer) { - container.x = -102; - container.y = -58; + container.x = -102 + container.y = -58 - container.visible = true; + container.visible = true } } handleSoundByState() { if (this.state === "MOVING") { - this.game.audio.playWagonMovingSound(); + this.game.audio.playWagonMovingSound() } } update(object: IGameObjectWagon) { - super.update(object); + super.update(object) - this.speed = object.speed; - this.fuel = object.fuel; + this.speed = object.speed + this.fuel = object.fuel } } diff --git a/apps/client/src/game/objects/wolf.ts b/apps/client/src/game/objects/wolf.ts index ff272205..390d5eb1 100644 --- a/apps/client/src/game/objects/wolf.ts +++ b/apps/client/src/game/objects/wolf.ts @@ -1,60 +1,60 @@ -import { Sprite } from "pixi.js"; -import type { IGameObjectWolf } from "../../../../../packages/api-sdk/src"; -import type { Game } from "../game"; -import { GameObjectContainer } from "./gameObjectContainer"; +import { Sprite } from "pixi.js" +import type { IGameObjectWolf } from "../../../../../packages/api-sdk/src" +import type { Game } from "../game" +import { GameObjectContainer } from "./gameObjectContainer" interface IWolfOptions { - game: Game; - object: IGameObjectWolf; + game: Game + object: IGameObjectWolf } export class Wolf extends GameObjectContainer implements IGameObjectWolf { - public animationAngle = 0; - public animationSlowSpeed = 0.1; + public animationAngle = 0 + public animationSlowSpeed = 0.1 constructor({ game, object }: IWolfOptions) { - super({ game, ...object }); + super({ game, ...object }) - this.update(object); - this.init(); + this.update(object) + this.init() } init() { - const spriteRight = Sprite.from("wolfRight"); - const spriteLeft = Sprite.from("wolfLeft"); + const spriteRight = Sprite.from("wolfRight") + const spriteLeft = Sprite.from("wolfLeft") - spriteRight.anchor.set(0.5, 1); - spriteLeft.anchor.set(0.5, 1); + spriteRight.anchor.set(0.5, 1) + spriteLeft.anchor.set(0.5, 1) - spriteRight.direction = "RIGHT"; - spriteLeft.direction = "LEFT"; + spriteRight.direction = "RIGHT" + spriteLeft.direction = "LEFT" - this.addChild(spriteRight, spriteLeft); + this.addChild(spriteRight, spriteLeft) } animate() { // Hide all for (const t of this.children) { - t.visible = false; + t.visible = false } // Visible only 1 - const sprite = this.children.find((t) => t.direction === this.direction); + const sprite = this.children.find((t) => t.direction === this.direction) if (sprite) { - sprite.visible = true; + sprite.visible = true } if (this.state === "MOVING") { - this.angle = this.animationAngle; - this.shakeAnimation(); + this.angle = this.animationAngle + this.shakeAnimation() } } shakeAnimation() { if (Math.abs(this.animationAngle) >= 2) { - this.animationSlowSpeed *= -1; + this.animationSlowSpeed *= -1 } - this.animationAngle += this.animationSlowSpeed; - this.angle = this.animationAngle; + this.animationAngle += this.animationSlowSpeed + this.angle = this.animationAngle } } diff --git a/apps/client/src/game/utils/assetsManager.ts b/apps/client/src/game/utils/assetsManager.ts index 0a61f732..fac2a008 100644 --- a/apps/client/src/game/utils/assetsManager.ts +++ b/apps/client/src/game/utils/assetsManager.ts @@ -1,98 +1,92 @@ import { AnimatedSprite, + type Application, Assets, + Graphics, Sprite, Texture, TilingSprite, - Application, - Graphics -} from "pixi.js"; -import { getRandomInRange } from "../../../../../packages/api-sdk/src"; -import campfireAnimation1 from "../assets/images/animation/campfire/1.png"; -import campfireAnimation2 from "../assets/images/animation/campfire/2.png"; -import campfireAnimation3 from "../assets/images/animation/campfire/3.png"; -import campfireAnimation4 from "../assets/images/animation/campfire/4.png"; -import campfireAnimation5 from "../assets/images/animation/campfire/5.png"; -import fireParticle1 from "../assets/images/animation/campfire/particle-1.png"; -import fireParticle2 from "../assets/images/animation/campfire/particle-2.png"; -import fireParticle3 from "../assets/images/animation/campfire/particle-3.png"; -import heroLeft1 from "../assets/images/animation/hero-moving-left/1.png"; -import heroLeft2 from "../assets/images/animation/hero-moving-left/2.png"; -import heroLeft3 from "../assets/images/animation/hero-moving-left/3.png"; -import heroLeft4 from "../assets/images/animation/hero-moving-left/4.png"; -import heroLeft5 from "../assets/images/animation/hero-moving-left/5.png"; -import heroLeft6 from "../assets/images/animation/hero-moving-left/6.png"; -import heroRight1 from "../assets/images/animation/hero-moving-right/1.png"; -import heroRight2 from "../assets/images/animation/hero-moving-right/2.png"; -import heroRight3 from "../assets/images/animation/hero-moving-right/3.png"; -import heroRight4 from "../assets/images/animation/hero-moving-right/4.png"; -import heroRight5 from "../assets/images/animation/hero-moving-right/5.png"; -import heroRight6 from "../assets/images/animation/hero-moving-right/6.png"; -import background1 from "../assets/images/background/1.png"; -import background2 from "../assets/images/background/2.png"; -import background3 from "../assets/images/background/3.png"; -import background4 from "../assets/images/background/4.png"; -import background5 from "../assets/images/background/5.png"; -import backgroundTeal1 from "../assets/images/background/teal/1.png"; -import backgroundTeal2 from "../assets/images/background/teal/2.png"; -import backgroundTeal3 from "../assets/images/background/teal/3.png"; -import backgroundTeal4 from "../assets/images/background/teal/4.png"; -import backgroundTeal5 from "../assets/images/background/teal/5.png"; +} from "pixi.js" +import { getRandomInRange } from "../../../../../packages/api-sdk/src" +import campfireAnimation1 from "../assets/images/animation/campfire/1.png" +import campfireAnimation2 from "../assets/images/animation/campfire/2.png" +import campfireAnimation3 from "../assets/images/animation/campfire/3.png" +import campfireAnimation4 from "../assets/images/animation/campfire/4.png" +import campfireAnimation5 from "../assets/images/animation/campfire/5.png" +import fireParticle1 from "../assets/images/animation/campfire/particle-1.png" +import fireParticle2 from "../assets/images/animation/campfire/particle-2.png" +import fireParticle3 from "../assets/images/animation/campfire/particle-3.png" +import heroLeft1 from "../assets/images/animation/hero-moving-left/1.png" +import heroLeft2 from "../assets/images/animation/hero-moving-left/2.png" +import heroLeft3 from "../assets/images/animation/hero-moving-left/3.png" +import heroLeft4 from "../assets/images/animation/hero-moving-left/4.png" +import heroLeft5 from "../assets/images/animation/hero-moving-left/5.png" +import heroLeft6 from "../assets/images/animation/hero-moving-left/6.png" +import heroRight1 from "../assets/images/animation/hero-moving-right/1.png" +import heroRight2 from "../assets/images/animation/hero-moving-right/2.png" +import heroRight3 from "../assets/images/animation/hero-moving-right/3.png" +import heroRight4 from "../assets/images/animation/hero-moving-right/4.png" +import heroRight5 from "../assets/images/animation/hero-moving-right/5.png" +import heroRight6 from "../assets/images/animation/hero-moving-right/6.png" +import background1 from "../assets/images/background/1.png" import backgroundMini from "../assets/images/background/2-16.png" -import wagonStop1 from "../assets/images/buildings/wagon-stop-1.png"; -import campfire1 from "../assets/images/buildings/camp-fire-1.png"; -import flag1 from "../assets/images/objects/flag-1.png"; -import flag2 from "../assets/images/objects/flag-2.png"; -import stone1 from "../assets/images/objects/stone-1.png"; -import tree1Green from "../assets/images/objects/tree/1/green.png"; -import tree1Blue from "../assets/images/objects/tree/1/blue.png"; -import tree1Stone from "../assets/images/objects/tree/1/stone.png"; -import tree1Teal from "../assets/images/objects/tree/1/teal.png"; -import tree1Toxic from "../assets/images/objects/tree/1/toxic.png"; -import tree1Violet from "../assets/images/objects/tree/1/violet.png"; -import tree2 from "../assets/images/objects/tree-2.png"; -import tree3 from "../assets/images/objects/tree-3.png"; -import tree4 from "../assets/images/objects/tree-4.png"; -import tree5 from "../assets/images/objects/tree-5.png"; -import tree6 from "../assets/images/objects/tree-6.png"; -import tree7 from "../assets/images/objects/tree-7.png"; -import tree10 from "../assets/images/objects/tree-10.png"; -import blackTopLeft from "../assets/images/unit/top/black-top-left.png"; -import blackTopRight from "../assets/images/unit/top/black-top-right.png"; -import blueTopLeft from "../assets/images/unit/top/blue-top-left.png"; -import blueTopRight from "../assets/images/unit/top/blue-top-right.png"; -import darkSilverTopLeft - from "../assets/images/unit/top/dark-silver-top-left.png"; -import darkSilverTopRight - from "../assets/images/unit/top/dark-silver-top-right.png"; -import greenTopLeft from "../assets/images/unit/top/green-top-left.png"; -import greenTopRight from "../assets/images/unit/top/green-top-right.png"; -import violetTopLeft from "../assets/images/unit/top/violet-top-left.png"; -import violetTopRight from "../assets/images/unit/top/violet-top-right.png"; -import unitHairClassicLeft - from "../assets/images/unit/hairstyle/hair-classic-left.png"; -import unitHairClassicRight - from "../assets/images/unit/hairstyle/hair-classic-right.png"; -import unitHairCoalLongLeft - from "../assets/images/unit/hairstyle/hair-coal-long-left.png"; -import unitHairCoalLongRight - from "../assets/images/unit/hairstyle/hair-coal-long-right.png"; -import unitHead1Left from "../assets/images/unit/head/head-1-left.png"; -import unitHead1Right from "../assets/images/unit/head/head-1-right.png"; -import wagonEngineCloud1 from "../assets/images/wagon/clouds/1.png"; -import wagonEngineCloud2 from "../assets/images/wagon/clouds/2.png"; -import wagonEngineCloud3 from "../assets/images/wagon/clouds/3.png"; -import wagonEngineCloud4 from "../assets/images/wagon/clouds/4.png"; -import wagonEngine1 from "../assets/images/wagon/engine-1.png"; -import wagonBase1 from "../assets/images/wagon/wagon-1.png"; -import wagonBase2 from "../assets/images/wagon/wagon-2.png"; -import wagonWheel1 from "../assets/images/wagon/wheel-1.png"; -import warehouse1 from "../assets/images/buildings/warehouse-1.png"; +import background2 from "../assets/images/background/2.png" +import background3 from "../assets/images/background/3.png" +import background4 from "../assets/images/background/4.png" +import background5 from "../assets/images/background/5.png" +import backgroundTeal1 from "../assets/images/background/teal/1.png" +import backgroundTeal2 from "../assets/images/background/teal/2.png" +import backgroundTeal3 from "../assets/images/background/teal/3.png" +import backgroundTeal4 from "../assets/images/background/teal/4.png" +import backgroundTeal5 from "../assets/images/background/teal/5.png" +import campfire1 from "../assets/images/buildings/camp-fire-1.png" +import wagonStop1 from "../assets/images/buildings/wagon-stop-1.png" +import warehouse1 from "../assets/images/buildings/warehouse-1.png" +import coin1 from "../assets/images/icons/coin-1.png" +import flag1 from "../assets/images/objects/flag-1.png" +import flag2 from "../assets/images/objects/flag-2.png" +import stone1 from "../assets/images/objects/stone-1.png" +import tree2 from "../assets/images/objects/tree-2.png" +import tree3 from "../assets/images/objects/tree-3.png" +import tree4 from "../assets/images/objects/tree-4.png" +import tree5 from "../assets/images/objects/tree-5.png" +import tree6 from "../assets/images/objects/tree-6.png" +import tree7 from "../assets/images/objects/tree-7.png" +import tree10 from "../assets/images/objects/tree-10.png" +import tree1Blue from "../assets/images/objects/tree/1/blue.png" +import tree1Green from "../assets/images/objects/tree/1/green.png" +import tree1Stone from "../assets/images/objects/tree/1/stone.png" +import tree1Teal from "../assets/images/objects/tree/1/teal.png" +import tree1Toxic from "../assets/images/objects/tree/1/toxic.png" +import tree1Violet from "../assets/images/objects/tree/1/violet.png" +import unitHairClassicLeft from "../assets/images/unit/hairstyle/hair-classic-left.png" +import unitHairClassicRight from "../assets/images/unit/hairstyle/hair-classic-right.png" +import unitHairCoalLongLeft from "../assets/images/unit/hairstyle/hair-coal-long-left.png" +import unitHairCoalLongRight from "../assets/images/unit/hairstyle/hair-coal-long-right.png" +import unitHead1Left from "../assets/images/unit/head/head-1-left.png" +import unitHead1Right from "../assets/images/unit/head/head-1-right.png" +import blackTopLeft from "../assets/images/unit/top/black-top-left.png" +import blackTopRight from "../assets/images/unit/top/black-top-right.png" +import blueTopLeft from "../assets/images/unit/top/blue-top-left.png" +import blueTopRight from "../assets/images/unit/top/blue-top-right.png" +import darkSilverTopLeft from "../assets/images/unit/top/dark-silver-top-left.png" +import darkSilverTopRight from "../assets/images/unit/top/dark-silver-top-right.png" +import greenTopLeft from "../assets/images/unit/top/green-top-left.png" +import greenTopRight from "../assets/images/unit/top/green-top-right.png" +import violetTopLeft from "../assets/images/unit/top/violet-top-left.png" +import violetTopRight from "../assets/images/unit/top/violet-top-right.png" +import wagonEngineCloud1 from "../assets/images/wagon/clouds/1.png" +import wagonEngineCloud2 from "../assets/images/wagon/clouds/2.png" +import wagonEngineCloud3 from "../assets/images/wagon/clouds/3.png" +import wagonEngineCloud4 from "../assets/images/wagon/clouds/4.png" +import wagonEngine1 from "../assets/images/wagon/engine-1.png" +import wagonBase1 from "../assets/images/wagon/wagon-1.png" +import wagonBase2 from "../assets/images/wagon/wagon-2.png" +import wagonWheel1 from "../assets/images/wagon/wheel-1.png" import water1 from "../assets/images/water/1.png" import water2 from "../assets/images/water/2.png" import water3 from "../assets/images/water/3.png" import water4 from "../assets/images/water/4.png" -import coin1 from "../assets/images/icons/coin-1.png" export abstract class AssetsManager { static assets = [ @@ -147,8 +141,8 @@ export abstract class AssetsManager { { alias: "wagonEngineCloud2", src: wagonEngineCloud2 }, { alias: "wagonEngineCloud3", src: wagonEngineCloud3 }, { alias: "wagonEngineCloud4", src: wagonEngineCloud4 }, - { alias: "coin1", src: coin1 } - ]; + { alias: "coin1", src: coin1 }, + ] static animationAssets = [ { alias: "heroRight1", src: heroRight1 }, @@ -163,19 +157,19 @@ export abstract class AssetsManager { { alias: "heroLeft4", src: heroLeft4 }, { alias: "heroLeft5", src: heroLeft5 }, { alias: "heroLeft6", src: heroLeft6 }, - ]; + ] static headAssets = [ { alias: "unitHead1Left", src: unitHead1Left }, { alias: "unitHead1Right", src: unitHead1Right }, - ]; + ] static hairAssets = [ { alias: "unitHairClassicLeft", src: unitHairClassicLeft }, { alias: "unitHairClassicRight", src: unitHairClassicRight }, { alias: "unitHairCoalLongLeft", src: unitHairCoalLongLeft }, { alias: "unitHairCoalLongRight", src: unitHairCoalLongRight }, - ]; + ] static topAssets = [ { alias: "violetTopLeft", src: violetTopLeft }, @@ -188,20 +182,24 @@ export abstract class AssetsManager { { alias: "blueTopRight", src: blueTopRight }, { alias: "darkSilverTopLeft", src: darkSilverTopLeft }, { alias: "darkSilverTopRight", src: darkSilverTopRight }, - ]; + ] static treeAssets = [ { alias: "tree1Green", src: tree1Green }, { alias: "tree1Blue", src: tree1Blue }, { alias: "tree1Stone", src: tree1Stone }, { - alias: "tree1Teal", src: tree1Teal + alias: "tree1Teal", + src: tree1Teal, }, { - alias: "tree1Toxic", src: tree1Toxic - }, { - alias: "tree1Violet", src: tree1Violet - } + alias: "tree1Toxic", + src: tree1Toxic, + }, + { + alias: "tree1Violet", + src: tree1Violet, + }, ] static backgroundAssets = [ @@ -210,17 +208,17 @@ export abstract class AssetsManager { { alias: "backgroundTeal3", src: backgroundTeal3 }, { alias: "backgroundTeal4", src: backgroundTeal4 }, { alias: "backgroundTeal5", src: backgroundTeal5 }, - { alias: "backgroundMini", src: backgroundMini } + { alias: "backgroundMini", src: backgroundMini }, ] public static async init() { - await Assets.load(AssetsManager.assets); - await Assets.load(AssetsManager.animationAssets); - await Assets.load(AssetsManager.headAssets); - await Assets.load(AssetsManager.hairAssets); - await Assets.load(AssetsManager.topAssets); - await Assets.load(AssetsManager.treeAssets); - await Assets.load(AssetsManager.backgroundAssets); + await Assets.load(AssetsManager.assets) + await Assets.load(AssetsManager.animationAssets) + await Assets.load(AssetsManager.headAssets) + await Assets.load(AssetsManager.hairAssets) + await Assets.load(AssetsManager.topAssets) + await Assets.load(AssetsManager.treeAssets) + await Assets.load(AssetsManager.backgroundAssets) } public static getAnimatedSpriteHeroRight() { @@ -231,18 +229,18 @@ export abstract class AssetsManager { "heroRight4", "heroRight5", "heroRight6", - ]; - const textureArray = []; + ] + const textureArray = [] for (const image of images) { - const texture = Texture.from(image); - textureArray.push(texture); + const texture = Texture.from(image) + textureArray.push(texture) } - const animation = new AnimatedSprite(textureArray); - animation.anchor.set(0.5, 1); + const animation = new AnimatedSprite(textureArray) + animation.anchor.set(0.5, 1) - return animation; + return animation } public static getAnimatedSpriteHeroLeft() { @@ -253,18 +251,18 @@ export abstract class AssetsManager { "heroLeft4", "heroLeft5", "heroLeft6", - ]; - const textureArray = []; + ] + const textureArray = [] for (const image of images) { - const texture = Texture.from(image); - textureArray.push(texture); + const texture = Texture.from(image) + textureArray.push(texture) } - const animation = new AnimatedSprite(textureArray); - animation.anchor.set(0.5, 1); + const animation = new AnimatedSprite(textureArray) + animation.anchor.set(0.5, 1) - return animation; + return animation } public static getAnimatedSpriteCampfire() { @@ -274,138 +272,141 @@ export abstract class AssetsManager { "campfireAnimation3", "campfireAnimation4", "campfireAnimation5", - ]; - const textureArray = []; + ] + const textureArray = [] for (const image of images) { - const texture = Texture.from(image); - textureArray.push(texture); + const texture = Texture.from(image) + textureArray.push(texture) } - const animation = new AnimatedSprite(textureArray); - animation.anchor.set(0.5, 1); + const animation = new AnimatedSprite(textureArray) + animation.anchor.set(0.5, 1) - return animation; + return animation } public static getRandomSpriteForBackground(app: Application) { - const graphics1 = new Graphics(); - graphics1.rect(0, 0, 64, 64).fill(0x0b8a8f); - const texture1 = app.renderer.generateTexture(graphics1); + const graphics1 = new Graphics() + graphics1.rect(0, 0, 64, 64).fill(0x0b8a8f) + const texture1 = app.renderer.generateTexture(graphics1) - const sprite1 = Sprite.from(texture1); - const sprite2 = Sprite.from("backgroundTeal2"); - const sprite3 = Sprite.from("backgroundTeal3"); - const sprite4 = Sprite.from("backgroundTeal4"); - const sprite5 = Sprite.from("backgroundTeal5"); + const sprite1 = Sprite.from(texture1) + const sprite2 = Sprite.from("backgroundTeal2") + const sprite3 = Sprite.from("backgroundTeal3") + const sprite4 = Sprite.from("backgroundTeal4") + const sprite5 = Sprite.from("backgroundTeal5") - const random = getRandomInRange(1, 100); + const random = getRandomInRange(1, 100) if (random <= 55) { - return sprite1; + return sprite1 } if (random <= 93) { - return sprite2; + return sprite2 } if (random <= 96) { - return sprite5; + return sprite5 } if (random <= 98) { - return sprite3; + return sprite3 } - return sprite4; + return sprite4 } public static getRandomSpriteForWater() { - const sprite1 = Sprite.from("water1"); - const sprite2 = Sprite.from("water2"); - const sprite3 = Sprite.from("water3"); - const sprite4 = Sprite.from("water4"); + const sprite1 = Sprite.from("water1") + const sprite2 = Sprite.from("water2") + const sprite3 = Sprite.from("water3") + const sprite4 = Sprite.from("water4") - const random = getRandomInRange(1, 100); + const random = getRandomInRange(1, 100) if (random <= 70) { - return sprite2; + return sprite2 } if (random <= 80) { - return sprite4; + return sprite4 } if (random <= 98) { - return sprite1; + return sprite1 } - return sprite3; + return sprite3 } public static generateRandomGridBackground({ - app, - width, - height, - }: { - app: Application, - width: number; - height: number; + app, + width, + height, + }: { + app: Application + width: number + height: number }) { - const gridX = Math.ceil(width / 64); - const gridY = Math.floor(height / 64); + const gridX = Math.ceil(width / 64) + const gridY = Math.floor(height / 64) - const bg: Sprite[] = []; + const bg: Sprite[] = [] for (let i = 0; i < gridX; i++) { for (let j = 0; j < gridY; j++) { - const background = AssetsManager.getRandomSpriteForBackground(app); + const background = AssetsManager.getRandomSpriteForBackground(app) - background.x = i * 64; - background.y = j * 64; + background.x = i * 64 + background.y = j * 64 - bg.push(background); + bg.push(background) } } - return bg; + return bg } public static async generateAndSaveBackground(app: Application) { const bg = AssetsManager.generateRandomGridBackground({ width: 2560, height: 1440, - app - }); - app.stage.addChild(...bg); + app, + }) + app.stage.addChild(...bg) - return AssetsManager.saveCanvasAsWebp(app); + return AssetsManager.saveCanvasAsWebp(app) } public static async getGeneratedBackgroundTilingSprite(app: Application) { const bg = AssetsManager.generateRandomGridBackground({ width: 2560, height: 1440, - app - }); - app.stage.addChild(...bg); + app, + }) + app.stage.addChild(...bg) const blob = await app.renderer.extract.image({ target: app.stage, format: "webp", - quality: 1 - }); + quality: 1, + }) - app.stage.removeChild(...bg); + app.stage.removeChild(...bg) return new TilingSprite({ texture: Texture.from(blob), - }); + }) } - public static async saveCanvasAsWebp(app: Application, imageName = "untitled") { + public static async saveCanvasAsWebp( + app: Application, + imageName = "untitled", + ) { const blob = await app.renderer.extract.image({ target: app.stage, format: "webp", - quality: 1 - }); - - const link = document.createElement("a"); - link.href = blob.src; - link.download = `${imageName}.webp`; - link.click(); - link.remove(); - app.renderer.destroy(); + quality: 1, + }) + + const link = document.createElement("a") + link.href = blob.src + link.download = `${imageName}.webp` + link.click() + link.remove() + app.renderer.destroy() } } diff --git a/apps/client/src/game/utils/audioManager.ts b/apps/client/src/game/utils/audioManager.ts index 6fb62ef0..02768180 100644 --- a/apps/client/src/game/utils/audioManager.ts +++ b/apps/client/src/game/utils/audioManager.ts @@ -1,11 +1,11 @@ -import { Howl } from "howler"; -import chop1Audio from "../assets/audio/chop-1.wav"; -import fireBurn1Audio from "../assets/audio/fire-1.wav"; -import forest1Audio from "../assets/audio/forest-1.mp3"; -import handPunch1Audio from "../assets/audio/hand-punch-1.wav"; -import marchWithHorns1Audio from "../assets/audio/marching-with-horns-1.wav"; -import mine1Audio from "../assets/audio/mine-1.wav"; -import wagon1Audio from "../assets/audio/wagon-1.wav"; +import { Howl } from "howler" +import chop1Audio from "../assets/audio/chop-1.wav" +import fireBurn1Audio from "../assets/audio/fire-1.wav" +import forest1Audio from "../assets/audio/forest-1.mp3" +import handPunch1Audio from "../assets/audio/hand-punch-1.wav" +import marchWithHorns1Audio from "../assets/audio/marching-with-horns-1.wav" +import mine1Audio from "../assets/audio/mine-1.wav" +import wagon1Audio from "../assets/audio/wagon-1.wav" type SoundName = | "chop-hit" @@ -14,111 +14,111 @@ type SoundName = | "marching-with-horns" | "forest-background" | "wagon-moving" - | "fire-burn"; + | "fire-burn" export class AudioManager { public chop1 = new Howl({ src: chop1Audio, - }); + }) public mine1 = new Howl({ src: mine1Audio, rate: 0.7, - }); + }) public handPunch1 = new Howl({ src: handPunch1Audio, rate: 0.5, - }); + }) public marchWithHorns1 = new Howl({ src: marchWithHorns1Audio, - }); + }) public forest1 = new Howl({ src: forest1Audio, loop: true, - }); + }) public wagon1 = new Howl({ src: wagon1Audio, rate: 0.7, - }); + }) public fireBurn1 = new Howl({ src: fireBurn1Audio, - }); + }) getSounds(name: SoundName): Howl[] { switch (name) { case "chop-hit": - return [this.chop1]; + return [this.chop1] case "mine-hit": - return [this.mine1]; + return [this.mine1] case "hand-hit": - return [this.handPunch1]; + return [this.handPunch1] case "marching-with-horns": - return [this.marchWithHorns1]; + return [this.marchWithHorns1] case "forest-background": - return [this.forest1]; + return [this.forest1] case "wagon-moving": - return [this.wagon1]; + return [this.wagon1] case "fire-burn": - return [this.fireBurn1]; + return [this.fireBurn1] default: - return []; + return [] } } play({ name, volume }: { name: SoundName; volume: number }) { - const sounds = this.getSounds(name); + const sounds = this.getSounds(name) if (sounds.length > 0) { - const sound = sounds[Math.floor(Math.random() * sounds.length)]; - sound.volume(volume); - sound.play(); + const sound = sounds[Math.floor(Math.random() * sounds.length)] + sound.volume(volume) + sound.play() } } playBackgroundSound() { - return this.play({ name: "forest-background", volume: 0.5 }); + return this.play({ name: "forest-background", volume: 0.5 }) } playCampfireSound() { if (this.fireBurn1.playing()) { - return; + return } - return this.play({ name: "fire-burn", volume: 0.7 }); + return this.play({ name: "fire-burn", volume: 0.7 }) } playWagonMovingSound() { if (this.wagon1.playing()) { - return; + return } - return this.play({ name: "wagon-moving", volume: 0.08 }); + return this.play({ name: "wagon-moving", volume: 0.08 }) } playRaidSound() { - return this.play({ name: "marching-with-horns", volume: 0.7 }); + return this.play({ name: "marching-with-horns", volume: 0.7 }) } playChopWithAxeSound() { if (this.chop1.playing()) { - return; + return } - return this.play({ name: "chop-hit", volume: 0.3 }); + return this.play({ name: "chop-hit", volume: 0.3 }) } playMineWithPickaxeSound() { if (this.mine1.playing()) { - return; + return } - return this.play({ name: "mine-hit", volume: 0.4 }); + return this.play({ name: "mine-hit", volume: 0.4 }) } playHandPunch() { if (this.handPunch1.playing()) { - return; + return } - return this.play({ name: "hand-hit", volume: 0.2 }); + return this.play({ name: "hand-hit", volume: 0.2 }) } } diff --git a/apps/client/src/game/utils/generators/background.ts b/apps/client/src/game/utils/generators/background.ts index af94aba9..5ce2ac43 100644 --- a/apps/client/src/game/utils/generators/background.ts +++ b/apps/client/src/game/utils/generators/background.ts @@ -1,1293 +1,231 @@ +import { Application, Container, Graphics, Sprite, TilingSprite } from "pixi.js" +import { getRandomInRange } from "../../../../../../packages/api-sdk/src" import { - Graphics, - Application, - Sprite, - TilingSprite, - Container -} from "pixi.js"; -import { getRandomInRange } from "../../../../../../packages/api-sdk/src"; + BACKGROUND_TILE_1, + BACKGROUND_TILE_2, + BACKGROUND_TILE_3, + BACKGROUND_TILE_4, + BACKGROUND_TILE_5, +} from "./backgroundImages" + +interface Palette { + 93: string + 97: string + 103: string + 111: string + 115: string + 123: string + 136: string + 147: string + 149: string + 151: string + 153: string + 156: string + 168: string + 173: string + 203: string + 206: string + 209: string + 211: string + 213: string + 218: string +} export class BackgroundGenerator { - app: Application; - palette: any; - color1: string; - color2: string; - color3: string; - color4: string; - color5: string; + app: Application + palette: Palette + mainColor1: string + mainColor2: string + accentColor1: string + accentColor2: string + accentColor3: string constructor(app: Application) { - this.app = app; + this.app = app - this.color1 = "0x239063"; - this.color2 = "0x1ebc73"; - this.color3 = "0x91db69"; - this.color4 = "0xcddf6c"; - this.color5 = "0x8fd3ff"; + this.mainColor1 = "0x239063" + this.mainColor2 = "0x1ebc73" + this.accentColor1 = "0x91db69" + this.accentColor2 = "0xcddf6c" + this.accentColor3 = "0x8fd3ff" this.palette = { - 93: this.color1, - 97: this.color1, - 103: this.color1, - 111: this.color2, - 115: this.color2, + 93: this.mainColor1, + 97: this.mainColor1, + 103: this.mainColor1, + 111: this.mainColor2, + 115: this.mainColor2, 123: "0xcd683d", // brown 136: "0xcd683d", // brown - 147: this.color3, + 147: this.accentColor1, 149: "0x92a984", // light neutral 151: "0xe6904e", // orange - 153: this.color3, - 156: this.color3, + 153: this.accentColor1, + 156: this.accentColor1, 168: "0xf68181", // bright pink 173: "0xfbb954", // light orange 203: "0x8fd3ff", // light blue - 206: this.color4, + 206: this.accentColor2, 209: "0xc7dcd0", // almost white - 211: this.color5, - 213: this.color5, - 218: "0xfbff86" // light yellow + 211: this.accentColor3, + 213: this.accentColor3, + 218: "0xfbff86", // light yellow } } - generate1() { - const graphics = new Graphics(); - graphics.rect(0, 0, 16, 16).fill(this.color1); + generate(imageArray: number[]) { + const imageWidth = Math.sqrt(imageArray.length) - return this.app.renderer.generateTexture({ - target: graphics, - resolution: 4 - }); - } - - generate2() { - const imageArray = [ - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93 - ] - - const imageWidth = Math.sqrt(imageArray.length); - - const graphics = new Graphics(); - - let index = 0; - for (let y = 0; y < imageWidth; y++) { - for (let x = 0; x < imageWidth; x++) { - const color = this.palette[imageArray[index]]; - graphics.rect(x, y, 1, 1).fill(color); - index++; - } - } - - return this.app.renderer.generateTexture({ - target: graphics, - resolution: 4 - }); - } - - generate3() { - const imageArray = [ - 97, - 97, - 97, - 149, - 149, - 97, - 97, - 97, - 149, - 149, - 97, - 97, - 97, - 115, - 97, - 97, - 97, - 206, - 97, - 149, - 115, - 115, - 97, - 115, - 115, - 97, - 97, - 97, - 103, - 115, - 103, - 97, - 97, - 206, - 206, - 97, - 115, - 115, - 97, - 115, - 97, - 97, - 153, - 153, - 97, - 97, - 103, - 97, - 103, - 115, - 115, - 97, - 103, - 115, - 97, - 97, - 103, - 97, - 153, - 115, - 115, - 97, - 149, - 149, - 97, - 103, - 115, - 97, - 103, - 115, - 103, - 97, - 97, - 97, - 103, - 115, - 115, - 103, - 115, - 115, - 97, - 97, - 97, - 97, - 97, - 97, - 97, - 97, - 206, - 206, - 103, - 97, - 97, - 103, - 97, - 115, - 97, - 206, - 206, - 206, - 97, - 97, - 97, - 115, - 115, - 206, - 97, - 97, - 97, - 97, - 103, - 97, - 97, - 97, - 206, - 115, - 115, - 97, - 103, - 115, - 115, - 103, - 97, - 149, - 103, - 206, - 206, - 97, - 97, - 97, - 103, - 115, - 115, - 97, - 103, - 115, - 103, - 97, - 149, - 115, - 103, - 115, - 115, - 97, - 153, - 153, - 97, - 103, - 115, - 97, - 103, - 97, - 103, - 97, - 115, - 103, - 97, - 103, - 115, - 97, - 153, - 115, - 115, - 97, - 97, - 103, - 153, - 153, - 97, - 97, - 97, - 97, - 97, - 103, - 97, - 97, - 103, - 115, - 115, - 103, - 97, - 103, - 153, - 115, - 115, - 97, - 97, - 206, - 206, - 206, - 97, - 97, - 97, - 103, - 97, - 103, - 97, - 97, - 103, - 115, - 115, - 97, - 115, - 115, - 206, - 97, - 97, - 97, - 149, - 97, - 97, - 97, - 206, - 206, - 97, - 97, - 97, - 103, - 115, - 115, - 103, - 97, - 206, - 97, - 115, - 149, - 97, - 97, - 103, - 115, - 115, - 103, - 97, - 103, - 115, - 103, - 97, - 115, - 206, - 97, - 97, - 115, - 103, - 97, - 97, - 103, - 115, - 103, - 97, - 103, - 97, - 97, - 97, - 115, - 115, - 103 - ] - - const imageWidth = Math.sqrt(imageArray.length); - - const graphics = new Graphics(); - - let index = 0; - for (let y = 0; y < imageWidth; y++) { - for (let x = 0; x < imageWidth; x++) { - const color = this.palette[imageArray[index]]; - graphics.rect(x, y, 1, 1).fill(color); - index++; - } - } - - return this.app.renderer.generateTexture({ - target: graphics, - resolution: 4 - }); - } - - generate4() { - const imageArray = [ - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 111, - 173, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 173, - 168, - 173, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 103, - 173, - 93, - 111, - 93, - 93, - 93, - 211, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 211, - 168, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 103, - 93, - 103, - 93, - 93, - 93, - 209, - 209, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 209, - 173, - 173, - 173, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 103, - 209, - 173, - 136, - 173, - 209, - 93, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 103, - 103, - 173, - 173, - 173, - 209, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 103, - 209, - 209, - 103, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 218, - 93, - 93, - 93, - 111, - 93, - 173, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 111, - 147, - 218, - 93, - 93, - 111, - 173, - 136, - 173, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 103, - 93, - 93, - 111, - 93, - 103, - 103, - 173, - 93, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 103, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93 - ] + const graphics = new Graphics() - const imageWidth = Math.sqrt(imageArray.length); - - const graphics = new Graphics(); - - let index = 0; + let index = 0 for (let y = 0; y < imageWidth; y++) { for (let x = 0; x < imageWidth; x++) { - const color = this.palette[imageArray[index]]; - graphics.rect(x, y, 1, 1).fill(color); - index++; - } - } - - return this.app.renderer.generateTexture({ - target: graphics, - resolution: 4 - }); - } + const grayscaleKey = imageArray[index] - generate5() { - const imageArray = [ - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 211, - 211, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 211, - 173, - 173, - 173, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 103, - 211, - 173, - 123, - 173, - 211, - 93, - 93, - 93, - 93, - 213, - 93, - 93, - 93, - 93, - 93, - 103, - 103, - 173, - 173, - 173, - 211, - 111, - 93, - 93, - 93, - 151, - 213, - 93, - 93, - 93, - 111, - 93, - 103, - 211, - 211, - 156, - 93, - 111, - 93, - 93, - 103, - 156, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 111, - 203, - 93, - 93, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 203, - 136, - 203, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 209, - 93, - 93, - 93, - 93, - 103, - 156, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 211, - 209, - 151, - 93, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 111, - 93, - 93, - 103, - 209, - 151, - 209, - 209, - 93, - 111, - 93, - 93, - 93, - 93, - 218, - 93, - 111, - 93, - 103, - 103, - 211, - 209, - 211, - 93, - 93, - 111, - 93, - 111, - 93, - 218, - 168, - 93, - 93, - 93, - 111, - 103, - 103, - 156, - 103, - 111, - 93, - 93, - 93, - 111, - 93, - 103, - 156, - 111, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 111, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93, - 93 - ] + if (!(grayscaleKey in this.palette)) { + // Not found! + console.log("Not found key in Palette:", grayscaleKey) + continue + } - const imageWidth = Math.sqrt(imageArray.length); + const color = this.palette[grayscaleKey as keyof Palette] - const graphics = new Graphics(); - - let index = 0; - for (let y = 0; y < imageWidth; y++) { - for (let x = 0; x < imageWidth; x++) { - const color = this.palette[imageArray[index]]; - graphics.rect(x, y, 1, 1).fill(color); - index++; + graphics.rect(x, y, 1, 1).fill(color) + index++ } } return this.app.renderer.generateTexture({ target: graphics, - resolution: 4 - }); + resolution: 4, + }) } async getPixelsData() { - let canvas = document.createElement("CANVAS") as HTMLCanvasElement; - let ctx = canvas.getContext('2d'); + const canvas = document.createElement("CANVAS") as HTMLCanvasElement + const ctx = canvas.getContext("2d") if (!ctx) { - return; + return } - const app = new Application(); - await app.init(); + const app = new Application() + await app.init() - let img = Sprite.from("backgroundMini"); - app.stage.addChild(img); + const img = Sprite.from("backgroundMini") + app.stage.addChild(img) const blob = await app.renderer.extract.image({ target: app.stage, format: "webp", - quality: 1 - }); + quality: 1, + }) - ctx.canvas.width = blob.width; - ctx.canvas.height = blob.height; - ctx.drawImage(blob, 0, 0); + ctx.canvas.width = blob.width + ctx.canvas.height = blob.height + ctx.drawImage(blob, 0, 0) - const imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height); + const imageData = ctx.getImageData( + 0, + 0, + ctx.canvas.width, + ctx.canvas.height, + ) - const pixels: number[] = []; + const pixels: number[] = [] for (let y = 0; y < blob.width; y++) { for (let x = 0; x < blob.width; x++) { - const [redIndex, greenIndex, blueIndex, _] = this.getColorIndicesForCoord(x, y, ctx.canvas.width); + const [redIndex, greenIndex, blueIndex, _] = + this.getColorIndicesForCoord(x, y, ctx.canvas.width) - const average = Math.round((imageData?.data[redIndex] + imageData?.data[greenIndex] + imageData?.data[blueIndex]) / 3); + const average = Math.round( + (imageData?.data[redIndex] + + imageData?.data[greenIndex] + + imageData?.data[blueIndex]) / + 3, + ) pixels.push(average) } } - console.log(pixels); + console.log(pixels) - return imageData; + return imageData } getColorIndicesForCoord(x: number, y: number, width: number) { - const red = y * (width * 4) + x * 4; - return [red, red + 1, red + 2, red + 3]; - }; + const red = y * (width * 4) + x * 4 + return [red, red + 1, red + 2, red + 3] + } public async getGeneratedBackgroundTilingSprite() { const bg = this.generateRandomGridBackground({ width: 2560, height: 1440, - }); - const container = new Container(); - container.addChild(...bg); + }) + const container = new Container() + container.addChild(...bg) - const texture = this.app.renderer.generateTexture(container); - container.destroy(); + const texture = this.app.renderer.generateTexture(container) + container.destroy() return new TilingSprite({ texture, - }); + }) } generateRandomGridBackground({ - width, - height, - }: { - width: number; - height: number; + width, + height, + }: { + width: number + height: number }) { - const gridX = Math.ceil(width / 64); - const gridY = Math.floor(height / 64); + const gridX = Math.ceil(width / 64) + const gridY = Math.floor(height / 64) - const bg: Sprite[] = []; + const bg: Sprite[] = [] for (let i = 0; i < gridX; i++) { for (let j = 0; j < gridY; j++) { - const background = this.getRandomSpriteForBackground(); + const background = this.getRandomSpriteForBackground() - background.x = i * 64; - background.y = j * 64; + background.x = i * 64 + background.y = j * 64 - bg.push(background); + bg.push(background) } } - return bg; + return bg } getRandomSpriteForBackground() { - const random = getRandomInRange(1, 100); + const tileArray = this.getTileByRandomChance() + const sprite = Sprite.from(this.generate(tileArray)) + sprite.scale = 4 + + return sprite + } + + getTileByRandomChance(): number[] { + const randomMax = 100 + const random = getRandomInRange(1, randomMax) + if (random <= 55) { - const sprite = Sprite.from(this.generate1()); - sprite.scale = 4; - return sprite; + return BACKGROUND_TILE_1 } if (random <= 93) { - const sprite = Sprite.from(this.generate2()); - sprite.scale = 4; - return sprite; + return BACKGROUND_TILE_2 } if (random <= 96) { - const sprite = Sprite.from(this.generate3()) - sprite.scale = 4; - return sprite; + return BACKGROUND_TILE_3 } if (random <= 98) { - const sprite = Sprite.from(this.generate4()); - sprite.scale = 4; - return sprite; + return BACKGROUND_TILE_4 } - const sprite = Sprite.from(this.generate5()) - sprite.scale = 4; - return sprite; + return BACKGROUND_TILE_5 } -} \ No newline at end of file +} diff --git a/apps/client/src/game/utils/generators/backgroundImages.ts b/apps/client/src/game/utils/generators/backgroundImages.ts new file mode 100644 index 00000000..0b01ff37 --- /dev/null +++ b/apps/client/src/game/utils/generators/backgroundImages.ts @@ -0,0 +1,88 @@ +export const BACKGROUND_TILE_1 = [ + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, +] + +export const BACKGROUND_TILE_2 = [ + 93, 93, 93, 93, 111, 93, 93, 93, 93, 111, 93, 93, 93, 93, 93, 93, 93, 111, 93, + 93, 111, 93, 93, 93, 93, 111, 93, 93, 111, 93, 93, 93, 93, 111, 93, 93, 93, + 93, 93, 111, 93, 93, 93, 93, 111, 93, 93, 111, 93, 93, 93, 93, 93, 93, 93, + 111, 93, 93, 93, 93, 93, 93, 93, 111, 93, 93, 93, 93, 111, 93, 93, 93, 93, + 111, 93, 93, 93, 111, 93, 93, 93, 93, 111, 93, 111, 93, 93, 93, 93, 111, 93, + 93, 93, 111, 93, 93, 93, 93, 111, 93, 93, 93, 93, 93, 93, 93, 93, 111, 93, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 111, 93, 93, 111, 93, 93, 111, 93, 93, + 111, 93, 93, 93, 111, 93, 93, 111, 93, 93, 93, 93, 93, 111, 93, 93, 111, 93, + 93, 93, 111, 93, 93, 93, 93, 93, 93, 111, 93, 93, 93, 93, 93, 93, 111, 93, 93, + 93, 93, 93, 93, 93, 93, 111, 93, 93, 93, 93, 93, 93, 111, 93, 93, 93, 111, 93, + 93, 93, 93, 93, 93, 93, 93, 111, 93, 93, 93, 93, 93, 93, 111, 93, 93, 93, 111, + 93, 93, 93, 93, 111, 93, 111, 93, 93, 93, 93, 93, 93, 111, 93, 111, 93, 93, + 111, 93, 93, 93, 111, 93, 93, 93, 111, 93, 93, 111, 93, 93, 93, 93, 111, 93, + 93, 93, 93, 93, 93, 93, 111, 93, 93, 93, 93, 93, 93, 93, 93, 93, +] + +export const BACKGROUND_TILE_3 = [ + 97, 97, 97, 149, 149, 97, 97, 97, 149, 149, 97, 97, 97, 115, 97, 97, 97, 206, + 97, 149, 115, 115, 97, 115, 115, 97, 97, 97, 103, 115, 103, 97, 97, 206, 206, + 97, 115, 115, 97, 115, 97, 97, 153, 153, 97, 97, 103, 97, 103, 115, 115, 97, + 103, 115, 97, 97, 103, 97, 153, 115, 115, 97, 149, 149, 97, 103, 115, 97, 103, + 115, 103, 97, 97, 97, 103, 115, 115, 103, 115, 115, 97, 97, 97, 97, 97, 97, + 97, 97, 206, 206, 103, 97, 97, 103, 97, 115, 97, 206, 206, 206, 97, 97, 97, + 115, 115, 206, 97, 97, 97, 97, 103, 97, 97, 97, 206, 115, 115, 97, 103, 115, + 115, 103, 97, 149, 103, 206, 206, 97, 97, 97, 103, 115, 115, 97, 103, 115, + 103, 97, 149, 115, 103, 115, 115, 97, 153, 153, 97, 103, 115, 97, 103, 97, + 103, 97, 115, 103, 97, 103, 115, 97, 153, 115, 115, 97, 97, 103, 153, 153, 97, + 97, 97, 97, 97, 103, 97, 97, 103, 115, 115, 103, 97, 103, 153, 115, 115, 97, + 97, 206, 206, 206, 97, 97, 97, 103, 97, 103, 97, 97, 103, 115, 115, 97, 115, + 115, 206, 97, 97, 97, 149, 97, 97, 97, 206, 206, 97, 97, 97, 103, 115, 115, + 103, 97, 206, 97, 115, 149, 97, 97, 103, 115, 115, 103, 97, 103, 115, 103, 97, + 115, 206, 97, 97, 115, 103, 97, 97, 103, 115, 103, 97, 103, 97, 97, 97, 115, + 115, 103, +] + +export const BACKGROUND_TILE_4 = [ + 93, 93, 93, 93, 111, 93, 93, 93, 93, 111, 93, 93, 93, 93, 93, 93, 93, 111, 93, + 93, 111, 93, 93, 93, 93, 111, 93, 93, 111, 173, 93, 93, 93, 111, 93, 93, 93, + 93, 93, 111, 93, 93, 93, 93, 173, 168, 173, 111, 93, 93, 93, 93, 93, 93, 93, + 111, 93, 93, 93, 93, 103, 173, 93, 111, 93, 93, 93, 211, 111, 93, 93, 93, 93, + 111, 93, 93, 93, 111, 93, 93, 93, 93, 211, 168, 111, 93, 93, 93, 93, 111, 93, + 93, 93, 111, 93, 93, 93, 93, 103, 93, 103, 93, 93, 93, 209, 209, 93, 111, 93, + 93, 93, 93, 93, 93, 93, 93, 93, 93, 209, 173, 173, 173, 93, 111, 93, 93, 111, + 93, 93, 111, 93, 93, 93, 103, 209, 173, 136, 173, 209, 93, 93, 93, 111, 93, + 93, 111, 93, 93, 93, 103, 103, 173, 173, 173, 209, 93, 111, 93, 93, 93, 93, + 93, 93, 111, 93, 93, 103, 209, 209, 103, 93, 93, 111, 93, 93, 93, 93, 93, 93, + 111, 93, 93, 93, 111, 93, 93, 93, 93, 218, 93, 93, 93, 111, 93, 173, 93, 93, + 93, 93, 111, 93, 93, 93, 111, 147, 218, 93, 93, 111, 173, 136, 173, 93, 93, + 93, 93, 93, 111, 93, 103, 93, 93, 111, 93, 103, 103, 173, 93, 93, 93, 111, 93, + 93, 111, 93, 93, 93, 93, 111, 93, 103, 93, 93, 93, 93, 93, 111, 93, 93, 93, + 93, 93, 93, 93, 93, 93, +] + +export const BACKGROUND_TILE_5 = [ + 93, 93, 93, 93, 111, 93, 93, 93, 93, 111, 93, 93, 93, 93, 93, 93, 93, 111, 93, + 93, 111, 93, 211, 211, 93, 111, 93, 93, 111, 93, 93, 93, 93, 111, 93, 93, 211, + 173, 173, 173, 93, 93, 93, 93, 111, 93, 93, 93, 93, 93, 93, 103, 211, 173, + 123, 173, 211, 93, 93, 93, 93, 213, 93, 93, 93, 93, 93, 103, 103, 173, 173, + 173, 211, 111, 93, 93, 93, 151, 213, 93, 93, 93, 111, 93, 103, 211, 211, 156, + 93, 111, 93, 93, 103, 156, 93, 93, 93, 93, 111, 93, 93, 93, 93, 93, 93, 93, + 93, 111, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 111, 93, 93, 111, 93, + 93, 111, 93, 93, 111, 203, 93, 93, 111, 93, 93, 111, 93, 93, 93, 93, 93, 111, + 93, 93, 203, 136, 203, 93, 111, 93, 93, 93, 93, 93, 93, 209, 93, 93, 93, 93, + 103, 156, 111, 93, 93, 93, 93, 93, 93, 93, 211, 209, 151, 93, 93, 93, 93, 93, + 111, 93, 93, 93, 111, 93, 93, 103, 209, 151, 209, 209, 93, 111, 93, 93, 93, + 93, 218, 93, 111, 93, 103, 103, 211, 209, 211, 93, 93, 111, 93, 111, 93, 218, + 168, 93, 93, 93, 111, 103, 103, 156, 103, 111, 93, 93, 93, 111, 93, 103, 156, + 111, 93, 93, 111, 93, 93, 93, 93, 111, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, + 93, 93, 93, 93, 93, 93, 93, +] diff --git a/apps/client/src/game/utils/index.ts b/apps/client/src/game/utils/index.ts index 83985302..91fb73ab 100644 --- a/apps/client/src/game/utils/index.ts +++ b/apps/client/src/game/utils/index.ts @@ -1,4 +1,4 @@ -export { AssetsManager } from "./assetsManager"; -export { AudioManager } from "./audioManager"; -export { SceneManager } from "./sceneManager"; -export { WebSocketManager } from "./webSocketManager"; +export { AssetsManager } from "./assetsManager" +export { AudioManager } from "./audioManager" +export { SceneManager } from "./sceneManager" +export { WebSocketManager } from "./webSocketManager" diff --git a/apps/client/src/game/utils/sceneManager.ts b/apps/client/src/game/utils/sceneManager.ts index 0253a94e..6932c406 100644 --- a/apps/client/src/game/utils/sceneManager.ts +++ b/apps/client/src/game/utils/sceneManager.ts @@ -1,11 +1,11 @@ -import { Application } from "pixi.js"; +import { Application } from "pixi.js" export class SceneManager { - public app: Application; + public app: Application constructor() { - this.app = new Application(); - void this.init(); + this.app = new Application() + void this.init() } public async init() { @@ -14,8 +14,8 @@ export class SceneManager { resizeTo: window, antialias: true, roundPixels: false, - resolution: 1 - }); - document.getElementById("game-canvas")?.appendChild(this.app.canvas); + resolution: 1, + }) + document.getElementById("game-canvas")?.appendChild(this.app.canvas) } } diff --git a/apps/client/src/game/utils/webSocketManager.ts b/apps/client/src/game/utils/webSocketManager.ts index f651b706..051f9dae 100644 --- a/apps/client/src/game/utils/webSocketManager.ts +++ b/apps/client/src/game/utils/webSocketManager.ts @@ -1,37 +1,37 @@ -import { MessageController } from "../../../../../packages/api-sdk/src"; -import type { Game } from "../game"; +import { MessageController } from "../../../../../packages/api-sdk/src" +import type { Game } from "../game" export abstract class WebSocketManager { - public static socket: WebSocket; - public static messagesPerSecond = 0; - public static kbitPerSecond = 0; + public static socket: WebSocket + public static messagesPerSecond = 0 + public static kbitPerSecond = 0 public static init(game: Game) { - WebSocketManager.socket = new WebSocket("ws://localhost:4002"); + WebSocketManager.socket = new WebSocket("ws://localhost:4002") - WebSocketManager.setMessagesPerSecondHandler(); + WebSocketManager.setMessagesPerSecondHandler() WebSocketManager.socket.addEventListener("message", (event) => { - const message = MessageController.parse(event.data.toString()); + const message = MessageController.parse(event.data.toString()) if (!message) { - return; + return } - WebSocketManager.messagesPerSecond += 1; - const bytes = JSON.stringify(message).length; - WebSocketManager.kbitPerSecond += Math.round((bytes * 8) / 1024); + WebSocketManager.messagesPerSecond += 1 + const bytes = JSON.stringify(message).length + WebSocketManager.kbitPerSecond += Math.round((bytes * 8) / 1024) - game.handleMessage(message); - }); + game.handleMessage(message) + }) } public static setMessagesPerSecondHandler() { return setInterval(() => { console.log( `${WebSocketManager.messagesPerSecond} msg/s, ${WebSocketManager.kbitPerSecond} kbit/s`, - ); - WebSocketManager.messagesPerSecond = 0; - WebSocketManager.kbitPerSecond = 0; - }, 1000); + ) + WebSocketManager.messagesPerSecond = 0 + WebSocketManager.kbitPerSecond = 0 + }, 1000) } } diff --git a/apps/client/src/hooks/useCountdown.ts b/apps/client/src/hooks/useCountdown.ts index a1168423..ca165b7f 100644 --- a/apps/client/src/hooks/useCountdown.ts +++ b/apps/client/src/hooks/useCountdown.ts @@ -1,31 +1,31 @@ -import { useEffect, useState } from "react"; +import { useEffect, useState } from "react" export const useCountdown = (targetDate: Date) => { - const countDownDate = new Date(targetDate).getTime(); + const countDownDate = new Date(targetDate).getTime() const [countDown, setCountDown] = useState( countDownDate - new Date().getTime(), - ); + ) useEffect(() => { const interval = setInterval(() => { - setCountDown(countDownDate - new Date().getTime()); - }, 1000); + setCountDown(countDownDate - new Date().getTime()) + }, 1000) - return () => clearInterval(interval); - }, [countDownDate]); + return () => clearInterval(interval) + }, [countDownDate]) - return getReturnValues(countDown); -}; + return getReturnValues(countDown) +} const getReturnValues = (countDown: number) => { // calculate time left - const days = Math.floor(countDown / (1000 * 60 * 60 * 24)); + const days = Math.floor(countDown / (1000 * 60 * 60 * 24)) const hours = Math.floor( (countDown % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60), - ); - const minutes = Math.floor((countDown % (1000 * 60 * 60)) / (1000 * 60)); - const seconds = Math.floor((countDown % (1000 * 60)) / 1000); + ) + const minutes = Math.floor((countDown % (1000 * 60 * 60)) / (1000 * 60)) + const seconds = Math.floor((countDown % (1000 * 60)) / 1000) - return [days, hours, minutes, seconds]; -}; + return [days, hours, minutes, seconds] +} diff --git a/apps/client/src/hooks/useScene.ts b/apps/client/src/hooks/useScene.ts index a74bee33..d533a7b8 100644 --- a/apps/client/src/hooks/useScene.ts +++ b/apps/client/src/hooks/useScene.ts @@ -1,29 +1,29 @@ -import { useEffect, useState } from "react"; +import { useEffect, useState } from "react" import { type GetSceneResponse, getSceneInfo, -} from "../../../../packages/api-sdk/src"; +} from "../../../../packages/api-sdk/src" export const useScene = () => { - const [sceneInfo, setSceneInfo] = useState(); + const [sceneInfo, setSceneInfo] = useState() useEffect(() => { getSceneInfo().then((res) => { - if (!res) return; + if (!res) return - setSceneInfo(res); - }); + setSceneInfo(res) + }) const reload = setInterval(() => { getSceneInfo().then((res) => { - if (!res) return; + if (!res) return - setSceneInfo(res); - }); - }, 500); + setSceneInfo(res) + }) + }, 500) - return () => clearInterval(reload); - }, []); + return () => clearInterval(reload) + }, []) - return sceneInfo; -}; + return sceneInfo +} diff --git a/apps/client/src/hooks/useTopPlayers.ts b/apps/client/src/hooks/useTopPlayers.ts index 4409bdb5..54289633 100644 --- a/apps/client/src/hooks/useTopPlayers.ts +++ b/apps/client/src/hooks/useTopPlayers.ts @@ -1,29 +1,29 @@ -import { useEffect, useState } from "react"; +import { useEffect, useState } from "react" import { type TopPlayersResponse, getTopPlayers, -} from "../../../../packages/api-sdk/src"; +} from "../../../../packages/api-sdk/src" export const useTopPlayers = () => { - const [players, setPlayers] = useState(); + const [players, setPlayers] = useState() useEffect(() => { getTopPlayers().then((res) => { - if (!res) return; + if (!res) return - setPlayers(res); - }); + setPlayers(res) + }) const reload = setInterval(() => { getTopPlayers().then((res) => { - if (!res) return; + if (!res) return - setPlayers(res); - }); - }, 10000); + setPlayers(res) + }) + }, 10000) - return () => clearInterval(reload); - }, []); + return () => clearInterval(reload) + }, []) - return players; -}; + return players +} diff --git a/apps/client/src/main.tsx b/apps/client/src/main.tsx index bdee274c..60aa50f7 100644 --- a/apps/client/src/main.tsx +++ b/apps/client/src/main.tsx @@ -1,10 +1,10 @@ -import React from "react"; -import ReactDOM from "react-dom/client"; -import "./index.css"; -import { InterfaceLayer } from "./components/interface"; +import React from "react" +import ReactDOM from "react-dom/client" +import "./index.css" +import { InterfaceLayer } from "./components/interface" ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( , -); +) diff --git a/apps/client/vite.config.ts b/apps/client/vite.config.ts index 2c630efd..d6c14fe4 100644 --- a/apps/client/vite.config.ts +++ b/apps/client/vite.config.ts @@ -1,6 +1,6 @@ -import tailwindcss from "@tailwindcss/vite"; -import react from "@vitejs/plugin-react"; -import { defineConfig } from "vite"; +import tailwindcss from "@tailwindcss/vite" +import react from "@vitejs/plugin-react" +import { defineConfig } from "vite" // https://vitejs.dev/config/ export default defineConfig({ @@ -8,4 +8,4 @@ export default defineConfig({ build: { target: "ESNext", }, -}); +}) diff --git a/biome.json b/biome.json index 2cbd60bc..feb188d8 100644 --- a/biome.json +++ b/biome.json @@ -1,5 +1,5 @@ { - "$schema": "https://biomejs.dev/schemas/1.6.1/schema.json", + "$schema": "https://biomejs.dev/schemas/1.7.3/schema.json", "organizeImports": { "enabled": true }, @@ -11,10 +11,18 @@ "noStaticOnlyClass": "off" } }, - "ignore": ["node_modules", "tmp"] + "ignore": [ + "node_modules", + "tmp" + ] }, "formatter": { "indentWidth": 2, "indentStyle": "space" + }, + "javascript": { + "formatter": { + "semicolons": "asNeeded" + } } } diff --git a/packages/api-sdk/src/index.ts b/packages/api-sdk/src/index.ts index 7ae5605d..e81acdf5 100644 --- a/packages/api-sdk/src/index.ts +++ b/packages/api-sdk/src/index.ts @@ -1,5 +1,5 @@ -export * from "./lib/types"; -export * from "./lib/client"; -export * from "./lib/messageController"; -export * from "./lib/random"; -export * from "./lib/date"; +export * from "./lib/types" +export * from "./lib/client" +export * from "./lib/messageController" +export * from "./lib/random" +export * from "./lib/date" diff --git a/packages/api-sdk/src/lib/client.ts b/packages/api-sdk/src/lib/client.ts index e43bf7e8..a4c8e1df 100644 --- a/packages/api-sdk/src/lib/client.ts +++ b/packages/api-sdk/src/lib/client.ts @@ -1,34 +1,34 @@ -import type { GetSceneResponse, IGameObjectPlayer } from "./types"; +import type { GetSceneResponse, IGameObjectPlayer } from "./types" interface PlayerWithPoints { - player: IGameObjectPlayer; - points: number; + player: IGameObjectPlayer + points: number } export interface TopPlayersResponse { - famous: PlayerWithPoints | null; - rich: PlayerWithPoints | null; - viewer: PlayerWithPoints | null; - woodsman: PlayerWithPoints | null; - miner: PlayerWithPoints | null; - villain: PlayerWithPoints | null; - refueller: PlayerWithPoints | null; + famous: PlayerWithPoints | null + rich: PlayerWithPoints | null + viewer: PlayerWithPoints | null + woodsman: PlayerWithPoints | null + miner: PlayerWithPoints | null + villain: PlayerWithPoints | null + refueller: PlayerWithPoints | null } export async function getTopPlayers() { try { - const res = await fetch("http://localhost:4001/players/top"); - return (await res.json()) as TopPlayersResponse; + const res = await fetch("http://localhost:4001/players/top") + return (await res.json()) as TopPlayersResponse } catch (err) { - return null; + return null } } export async function getSceneInfo() { try { - const res = await fetch("http://localhost:4001/scene"); - return (await res.json()) as GetSceneResponse; + const res = await fetch("http://localhost:4001/scene") + return (await res.json()) as GetSceneResponse } catch (err) { - return null; + return null } } diff --git a/packages/api-sdk/src/lib/date.ts b/packages/api-sdk/src/lib/date.ts index ba263ea5..28406556 100644 --- a/packages/api-sdk/src/lib/date.ts +++ b/packages/api-sdk/src/lib/date.ts @@ -1,9 +1,9 @@ export function getDatePlusMinutes(minutes: number) { - const milliseconds = minutes * 60 * 1000; - return new Date(new Date().getTime() + milliseconds); + const milliseconds = minutes * 60 * 1000 + return new Date(new Date().getTime() + milliseconds) } export function getDatePlusSeconds(seconds: number) { - const milliseconds = seconds * 1000; - return new Date(new Date().getTime() + milliseconds); + const milliseconds = seconds * 1000 + return new Date(new Date().getTime() + milliseconds) } diff --git a/packages/api-sdk/src/lib/messageController.ts b/packages/api-sdk/src/lib/messageController.ts index 7cceb13d..2d15aaf5 100644 --- a/packages/api-sdk/src/lib/messageController.ts +++ b/packages/api-sdk/src/lib/messageController.ts @@ -1,12 +1,12 @@ -import type { WebSocketMessage } from "./types"; +import type { WebSocketMessage } from "./types" export class MessageController { public static parse(message: string): WebSocketMessage | undefined { - const parsed = JSON.parse(message); + const parsed = JSON.parse(message) if (parsed) { - return parsed as WebSocketMessage; + return parsed as WebSocketMessage } - return undefined; + return undefined } } diff --git a/packages/api-sdk/src/lib/random.ts b/packages/api-sdk/src/lib/random.ts index 601b338a..535c25cd 100644 --- a/packages/api-sdk/src/lib/random.ts +++ b/packages/api-sdk/src/lib/random.ts @@ -1,4 +1,4 @@ export function getRandomInRange(min: number, max: number) { - const ceilMin = Math.ceil(min); - return Math.floor(Math.random() * (max - ceilMin + 1)) + ceilMin; + const ceilMin = Math.ceil(min) + return Math.floor(Math.random() * (max - ceilMin + 1)) + ceilMin } diff --git a/packages/api-sdk/src/lib/types.ts b/packages/api-sdk/src/lib/types.ts index 1cf178de..86c088be 100644 --- a/packages/api-sdk/src/lib/types.ts +++ b/packages/api-sdk/src/lib/types.ts @@ -13,80 +13,77 @@ export type IGameSceneAction = | "START_CHANGING_SCENE" | "START_RAID" | "CREATE_NEW_PLAYER" - | "START_CREATING_NEW_ADVENTURE"; + | "START_CREATING_NEW_ADVENTURE" -export type ItemType = "WOOD" | "STONE" | "AXE" | "PICKAXE"; +export type ItemType = "WOOD" | "STONE" | "AXE" | "PICKAXE" export interface IGameInventory { - id: string; - objectId: string; - items: InventoryItem[]; + id: string + objectId: string + items: InventoryItem[] } export interface InventoryItem { - id: string; - createdAt: Date; - updatedAt: Date; - inventoryId: string; - type: ItemType; - amount: number; - durability: number; + id: string + createdAt: Date + updatedAt: Date + inventoryId: string + type: ItemType + amount: number + durability: number } export interface IGameSkill { - id: string; - type: "WOODSMAN" | "MINER"; - objectId: string | null; - lvl: number; - xp: number; - xpNextLvl: number; + id: string + type: "WOODSMAN" | "MINER" + objectId: string | null + lvl: number + xp: number + xpNextLvl: number } export interface IGameChunk { - id: string; - title: string; - type: "VILLAGE" | "FOREST" | "LAKE"; - theme: IGameChunkTheme; + id: string + title: string + type: "VILLAGE" | "FOREST" | "LAKE" + theme: IGameChunkTheme center: { - x: number; - y: number; - }; + x: number + y: number + } area: { - startX: number; - endX: number; - startY: number; - endY: number; - }; - isVisibleOnClient: boolean; + startX: number + endX: number + startY: number + endY: number + } + isVisibleOnClient: boolean } export type IGameChunkTheme = - "GREEN" + | "GREEN" | "TOXIC" | "STONE" | "TEAL" | "BLUE" - | "VIOLET"; + | "VIOLET" -export interface IGameVillageChunk extends IGameChunk { -} +export interface IGameVillageChunk extends IGameChunk {} -export interface IGameForestChunk extends IGameChunk { -} +export interface IGameForestChunk extends IGameChunk {} -export interface IGameLakeChunk extends IGameChunk { -} +export interface IGameLakeChunk extends IGameChunk {} export interface IGameObject { - id: string; - x: number; - y: number; - state: IGameObjectState; - direction: IGameObjectDirection; - entity: IGameObjectEntity; - target: IGameObject | undefined; - health: number; - isVisibleOnClient: boolean; + id: string + x: number + y: number + state: IGameObjectState + direction: IGameObjectDirection + entity: IGameObjectEntity + target: IGameObject | undefined + health: number + isVisibleOnClient: boolean } export type IGameObjectState = @@ -95,7 +92,7 @@ export type IGameObjectState = | "WAITING" | "CHOPPING" | "MINING" - | "DESTROYED"; + | "DESTROYED" export type IGameObjectEntity = | "RABBIT" | "WOLF" @@ -110,11 +107,11 @@ export type IGameObjectEntity = | "FARMER" | "MECHANIC" | "WAGON" - | IGameObjectBuildingType; -export type IGameObjectDirection = "LEFT" | "RIGHT"; + | IGameObjectBuildingType +export type IGameObjectDirection = "LEFT" | "RIGHT" export interface WebSocketMessage { - id: string; + id: string event: | "OBJECT_UPDATED" | "RAID_STARTED" @@ -122,35 +119,32 @@ export interface WebSocketMessage { | "SCENE_CHANGING_STARTED" | "COUNTDOWN_NEXT_WAVE_STARTED" | "SCENE_CHANGED" - | "CREATING_NEW_ADVENTURE_STARTED"; - object?: Partial; + | "CREATING_NEW_ADVENTURE_STARTED" + object?: Partial } export interface IGameObjectWagon extends IGameObject { - speed: number; - fuel: number; + speed: number + fuel: number visibilityArea: { - startX: number; - endX: number; - startY: number; - endY: number; - }; + startX: number + endX: number + startY: number + endY: number + } } -export type IGameObjectBuildingType = "CAMPFIRE" | "WAREHOUSE" | "WAGON_STOP"; +export type IGameObjectBuildingType = "CAMPFIRE" | "WAREHOUSE" | "WAGON_STOP" export interface IGameObjectBuilding extends IGameObject { - inventory: IGameInventory; + inventory: IGameInventory } -export interface IGameBuildingCampfire extends IGameObjectBuilding { -} +export interface IGameBuildingCampfire extends IGameObjectBuilding {} -export interface IGameBuildingWarehouse extends IGameObjectBuilding { -} +export interface IGameBuildingWarehouse extends IGameObjectBuilding {} -export interface IGameBuildingWagonStop extends IGameObjectBuilding { -} +export interface IGameBuildingWagonStop extends IGameObjectBuilding {} export interface IGameObjectFlag extends IGameObject { type: @@ -159,108 +153,109 @@ export interface IGameObjectFlag extends IGameObject { | "WAGON_NEAR_MOVEMENT" | "RESOURCE" | "SPAWN_LEFT" - | "SPAWN_RIGHT"; + | "SPAWN_RIGHT" } -export interface IGameObjectWater extends IGameObject { -} +export interface IGameObjectWater extends IGameObject {} export interface IGameObjectLake extends IGameObject { - water: IGameObjectWater[]; + water: IGameObjectWater[] } export interface IGameObjectTree extends IGameObject { - type: "1" | "2" | "3" | "4" | "5"; - variant: IGameChunkTheme; - resource: number; - size: number; - isReadyToChop: boolean; + type: "1" | "2" | "3" | "4" | "5" + variant: IGameChunkTheme + resource: number + size: number + isReadyToChop: boolean } export interface IGameObjectStone extends IGameObject { - type: "1"; - resource: number; - size: number; + type: "1" + resource: number + size: number } export interface IGameObjectUnit extends IGameObject { - coins: number; - inventory: IGameInventory; + coins: number + inventory: IGameInventory visual: { - head: "1"; - hairstyle: "BOLD" | "CLASSIC" | "COAL_LONG"; + head: "1" + hairstyle: "BOLD" | "CLASSIC" | "COAL_LONG" top: | "VIOLET_SHIRT" | "BLACK_SHIRT" | "GREEN_SHIRT" | "BLUE_SHIRT" - | "DARK_SILVER_SHIRT"; - }; + | "DARK_SILVER_SHIRT" + } } -export interface IGameObjectCourier extends IGameObjectUnit { -} +export interface IGameObjectCourier extends IGameObjectUnit {} -export interface IGameObjectFarmer extends IGameObjectUnit { -} +export interface IGameObjectFarmer extends IGameObjectUnit {} -export interface IGameObjectMechanic extends IGameObjectUnit { -} +export interface IGameObjectMechanic extends IGameObjectUnit {} export interface IGameObjectPlayer extends IGameObjectUnit { - reputation: number; - villainPoints: number; - refuellerPoints: number; - userName: string; - skills: IGameSkill[]; + reputation: number + villainPoints: number + refuellerPoints: number + userName: string + skills: IGameSkill[] } export interface IGameObjectRaider extends IGameObjectUnit { - userName: string; - colorIndex: number; + userName: string + colorIndex: number } -export interface IGameObjectRabbit extends IGameObject { -} +export interface IGameObjectRabbit extends IGameObject {} -export interface IGameObjectWolf extends IGameObject { -} +export interface IGameObjectWolf extends IGameObject {} export interface IGameEvent { - id: string; - title: string; - type: WebSocketMessage["event"]; - status: "STARTED" | "STOPPED"; - endsAt: Date; + id: string + title: string + type: WebSocketMessage["event"] + status: "STARTED" | "STOPPED" + endsAt: Date } -export type GameSceneType = "VILLAGE" | "DEFENCE" | "MOVING"; +export type GameSceneType = "VILLAGE" | "DEFENCE" | "MOVING" export interface GetSceneResponse { - id: string; - commands: string[]; - chunk: IGameChunk | null; - events: IGameEvent[]; - group: IGameGroup | undefined; - wagon: IGameObjectWagon | undefined; - route: IGameRoute | null; + id: string + commands: string[] + chunk: IGameChunk | null + events: IGameEvent[] + group: IGameGroup | undefined + wagon: IGameObjectWagon | undefined + route: IGameRoute | null } export interface IGameGroup { - id: string; - target: GameSceneType; - players: IGameObjectPlayer[]; + id: string + target: GameSceneType + players: IGameObjectPlayer[] } export interface IGameRoute { - startPoint: { x: number; y: number }; - endPoint: { x: number; y: number }; - chunks: IGameChunk[]; + startPoint: { x: number; y: number } + endPoint: { x: number; y: number } + chunks: IGameChunk[] } export interface PlayerTitle { - title: string; - type: "RICH" | "FAMOUS" | "VIEWER" | "VILLAIN" | "REFUELLER" | "WOODSMAN" | "MINER"; + title: string + type: + | "RICH" + | "FAMOUS" + | "VIEWER" + | "VILLAIN" + | "REFUELLER" + | "WOODSMAN" + | "MINER" } export type GraphicsContainerType = @@ -277,4 +272,4 @@ export type GraphicsContainerType = | "WAGON_WHEEL" | "WAGON_ENGINE" | "WAGON_ENGINE_CLOUD" - | "FIRE_PARTICLE"; + | "FIRE_PARTICLE"