Skip to content

Commit

Permalink
feat: inventory data load from server
Browse files Browse the repository at this point in the history
  • Loading branch information
hmbanan666 committed Jun 26, 2024
1 parent fe613b9 commit 0e3ed9e
Show file tree
Hide file tree
Showing 12 changed files with 71 additions and 45 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"prepare": "husky"
},
"dependencies": {
"@hmbanan666/chat-game-api": "^0.1.6",
"@hmbanan666/chat-game-api": "^0.1.8",
"@paralleldrive/cuid2": "^2.2.2",
"@radix-ui/colors": "^3.0.0",
"@twurple/api": "^7.1.0",
Expand Down
41 changes: 22 additions & 19 deletions src/lib/game/common/inventory.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,33 @@
import { createId } from '@paralleldrive/cuid2'
import type {
GameObject,
IGameInventory,
IGameInventoryItem,
ItemType,
} from '$lib/game/types'

interface InventoryOptions {
objectId: string
saveInDb: boolean
object: GameObject
saveInDb?: boolean
}

export class Inventory implements IGameInventory {
public id: string
public objectId: string
public items: IGameInventoryItem[] = []
public saveInDb: boolean
id: string
object: GameObject
items: IGameInventoryItem[] = []
saveInDb: boolean

constructor({ objectId, saveInDb }: InventoryOptions) {
constructor({ object, saveInDb }: InventoryOptions) {
this.id = createId()
this.objectId = objectId
this.saveInDb = saveInDb
this.object = object
this.saveInDb = saveInDb ?? false
}

public async init(inventoryId?: string) {
if (inventoryId) {
this.id = inventoryId
await this.#readFromDB()
}
await this.updateFromDB()
}

public async destroyItem(id: string) {
Expand Down Expand Up @@ -84,19 +85,19 @@ export class Inventory implements IGameInventory {
const item = { id: '123' }
if (!item) {
await this.createItemInDB(this.id, type, amount)
await this.updateFromDB()
await this.#readFromDB()
return
}

await this.incrementAmountOfItemInDB(item.id, amount)
await this.updateFromDB()
await this.#readFromDB()
}

async destroyItemInDB(_id: string) {
// await db.inventoryItem.delete({
// where: { id },
// })
await this.updateFromDB()
await this.#readFromDB()
}

public tryGetItemInDB(type: ItemType) {
Expand All @@ -106,7 +107,7 @@ export class Inventory implements IGameInventory {
async checkAndBreakItem(item: IGameInventoryItem, decrement: number) {
if (item.durability <= decrement) {
await this.destroyItemInDB(item.id)
await this.updateFromDB()
await this.#readFromDB()
return
}

Expand Down Expand Up @@ -175,10 +176,12 @@ export class Inventory implements IGameInventory {
this.items.push(item)
}

async updateFromDB() {
// const items = await db.inventoryItem.findMany({
// where: { inventoryId: this.id },
// })
// this.items = items as IGameInventoryItem[]
async #readFromDB() {
const inventory = await this.object.game.serverService.getInventory(this.id)
if (!inventory) {
return
}

this.items = inventory.items
}
}
5 changes: 1 addition & 4 deletions src/lib/game/objects/buildings/baseBuilding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,6 @@ export class BaseBuilding extends BaseObject implements IGameObjectBuilding {
}

#initInventory() {
this.inventory = new Inventory({
objectId: this.id,
saveInDb: false,
})
this.inventory = new Inventory({ object: this })
}
}
6 changes: 3 additions & 3 deletions src/lib/game/objects/units/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ export class Player extends UnitObject implements GameObjectPlayer {

async init() {
await this.#readFromDB()
await this.#initInventoryFromDB()
// await this.#initSkillsFromDB()
// await this.#initInventoryFromDB()

super.initVisual({
head: '1',
Expand Down Expand Up @@ -122,7 +122,7 @@ export class Player extends UnitObject implements GameObjectPlayer {
}

async #readFromDB() {
const player = await this.game.serverService.getPlayerData(this.id)
const player = await this.game.serverService.getPlayer(this.id)
if (!player) {
return
}
Expand Down Expand Up @@ -152,7 +152,7 @@ export class Player extends UnitObject implements GameObjectPlayer {
}

const inventory = new Inventory({
objectId: this.id,
object: this,
saveInDb: true,
})
await inventory.init(this.inventoryId)
Expand Down
5 changes: 1 addition & 4 deletions src/lib/game/objects/units/unitObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,7 @@ export class UnitObject extends BaseObject implements IGameObjectUnit {
this.#animationMovingRight = AssetsManager.getAnimatedSpriteHero('RIGHT')
this.#animationMovingLeft = AssetsManager.getAnimatedSpriteHero('LEFT')

this.inventory = new Inventory({
objectId: this.id,
saveInDb: false,
})
this.inventory = new Inventory({ object: this })

this.#initDialogue()

Expand Down
5 changes: 3 additions & 2 deletions src/lib/game/services/server/interface.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Player } from '@hmbanan666/chat-game-api'
import type { Inventory, Player } from '@hmbanan666/chat-game-api'
import type { GameService } from '../interface'

export interface GameServerService extends GameService {
getPlayerData: (id: string) => Promise<Player | null>
getPlayer: (id: string) => Promise<Player | null>
getInventory: (id: string) => Promise<Inventory | null>
}
18 changes: 16 additions & 2 deletions src/lib/game/services/server/serverService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Player } from '@hmbanan666/chat-game-api'
import type { Inventory, Player } from '@hmbanan666/chat-game-api'
import type { GameServerService } from './interface'
import type { Game } from '$lib/game/types'

Expand All @@ -11,7 +11,7 @@ export class ServerService implements GameServerService {

update() {}

async getPlayerData(id: string): Promise<Player | null> {
async getPlayer(id: string): Promise<Player | null> {
try {
const res = await fetch(`/auth/game/player/${id}`)
const player = await res.json() as Player
Expand All @@ -24,4 +24,18 @@ export class ServerService implements GameServerService {
return null
}
}

async getInventory(id: string): Promise<Inventory | null> {
try {
const res = await fetch(`/auth/game/inventory/${id}`)
const inventory = await res.json() as Inventory
if (!inventory) {
return null
}

return inventory
} catch (err) {
return null
}
}
}
5 changes: 1 addition & 4 deletions src/lib/game/services/wagon/wagonService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,7 @@ export class WagonService implements GameWagonService {
}

setCargo() {
this.cargo = new Inventory({
saveInDb: false,
objectId: this.wagon.id,
})
this.cargo = new Inventory({ object: this.wagon })
void this.cargo.addOrCreateItem('WOOD', 100)
this.wagon.cargoType = 'CHEST'
}
Expand Down
2 changes: 1 addition & 1 deletion src/lib/game/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ export type ItemType = 'WOOD' | 'STONE' | 'AXE' | 'PICKAXE' | 'COIN'

export interface IGameInventory {
id: string
objectId: string
object: GameObject
items: IGameInventoryItem[]
reduceOrDestroyItem: (type: ItemType, amount: number) => Promise<boolean>
addOrCreateItem: (type: ItemType, amount: number) => Promise<void>
Expand Down
17 changes: 17 additions & 0 deletions src/routes/auth/game/inventory/[id]/+server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { type RequestHandler, error, json } from '@sveltejs/kit'
import { api } from '$lib/server/api'

export const GET: RequestHandler = async ({ locals, params }) => {
if (!locals.profile) {
return error(401)
}

const inventoryId = params.id ?? ''

const inventory = await api.inventory.getById(inventoryId)
if (!inventory || inventory instanceof Error) {
return error(404)
}

return json(inventory)
}
2 changes: 1 addition & 1 deletion src/routes/auth/game/player/[id]/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const GET: RequestHandler = async ({ locals, params }) => {

const player = await api.player.getById(playerId)
if (!player || player instanceof Error) {
return error(401)
return error(404)
}

return json(player)
Expand Down
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -528,10 +528,10 @@
resolved "https://registry.yarnpkg.com/@eslint/object-schema/-/object-schema-2.1.4.tgz#9e69f8bb4031e11df79e03db09f9dbbae1740843"
integrity sha512-BsWiH1yFGjXXS2yvrf5LyuoSIIbPrGUWob917o+BTKuZ7qJdxX8aJLRxs1fS9n6r7vESrq1OUqb68dANcFXuQQ==

"@hmbanan666/chat-game-api@^0.1.6":
version "0.1.6"
resolved "https://registry.yarnpkg.com/@hmbanan666/chat-game-api/-/chat-game-api-0.1.6.tgz#f2650b6cb9428417bb0dd025d402b66c15a1e67f"
integrity sha512-AZiL5+SaDyo8wisGrzSBpbP0nrHQw/A3uIhiIrQ6yDvSdVIlm37yaqrgPIQys+L48/MvUk7Z3QhyUUH2me0B5A==
"@hmbanan666/chat-game-api@^0.1.8":
version "0.1.8"
resolved "https://registry.yarnpkg.com/@hmbanan666/chat-game-api/-/chat-game-api-0.1.8.tgz#1fb93d73722b65ff42cc42c8c58b3413c5b31a3a"
integrity sha512-n0+6/hJ22P0XWPjjfB8HlN0Txct1MtkUsFTllC1yXLEP4NwE7GWoX/v1FT2yG4vTZE2EB7ApPuo5WESEWHh5NQ==

"@humanwhocodes/module-importer@^1.0.1":
version "1.0.1"
Expand Down

0 comments on commit 0e3ed9e

Please sign in to comment.