Skip to content

Commit

Permalink
feat: game communicates with server via svelte server (#182)
Browse files Browse the repository at this point in the history
* fix: logout link

* feat: server service with local api communication

* feat: inventory data load from server

* chore: actionService handlers refactored

* fix: game unit dialogs

* fix: game import
  • Loading branch information
hmbanan666 authored Jun 26, 2024
1 parent 47cd328 commit 195f3fc
Show file tree
Hide file tree
Showing 22 changed files with 205 additions and 116 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.5",
"@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
6 changes: 3 additions & 3 deletions src/lib/components/Header.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@

<nav>
<ul>
<li aria-current={$page.url.pathname === '/' ? 'page' : undefined}>
<li aria-current={$page.url.pathname === `/${locale}` ? 'page' : undefined}>
<a href='/{locale}'>{t.header.menu.home}</a>
</li>
<li aria-current={$page.url.pathname === '/about' ? 'page' : undefined}>
<li aria-current={$page.url.pathname === `/${locale}/about` ? 'page' : undefined}>
<a href='/{locale}/about'>{t.header.menu.about}</a>
</li>
<li aria-current={$page.url.pathname === '/character' ? 'page' : undefined}>
<li aria-current={$page.url.pathname === `/${locale}/character` ? 'page' : undefined}>
<a href='/{locale}/character'>{t.header.menu.characters}</a>
</li>
</ul>
Expand Down
2 changes: 1 addition & 1 deletion src/lib/components/Profile.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
const isSignedIn = !!$page.data.profile
const handleSignOut = () => {
void fetch('/en/auth/profile', {
void fetch('/auth/profile', {
method: 'DELETE',
headers: {
'content-type': 'application/json',
Expand Down
4 changes: 2 additions & 2 deletions src/lib/game/actions/plantTreeAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { Game, GameObjectPlayer } from '$lib/game/types'
import { VillageChunk } from '$lib/game/services/chunk/villageChunk'
import type { GameAction } from '$lib/game/actions/interface'

interface IPlantTreeActionOptions {
interface PlantTreeActionOptions {
game: Game
}

Expand All @@ -13,7 +13,7 @@ export class PlantTreeAction implements GameAction {
commandDescription = '!plant'
game: Game

constructor({ game }: IPlantTreeActionOptions) {
constructor({ game }: PlantTreeActionOptions) {
this.game = game
}

Expand Down
3 changes: 3 additions & 0 deletions src/lib/game/baseGame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Application, Container } from 'pixi.js'
import { createId } from '@paralleldrive/cuid2'
import { WebSocketService } from './services/socket/webSocketService'
import { gameOptions } from './store.svelte'
import { ServerService } from './services/server/serverService'
import type {
Game,
GameObject,
Expand Down Expand Up @@ -63,6 +64,7 @@ export class BaseGame extends Container implements Game {
playerService: PlayerService
questService: QuestService
websocketService: WebSocketService
serverService: ServerService

#cameraX = 0
#cameraY = 0
Expand Down Expand Up @@ -93,6 +95,7 @@ export class BaseGame extends Container implements Game {
this.playerService = new PlayerService(this)
this.questService = new QuestService(this)
this.websocketService = new WebSocketService(this)
this.serverService = new ServerService(this)
}

async init() {
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
}
}
20 changes: 10 additions & 10 deletions src/lib/game/components/dialogueInterface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ import type { IGameObjectUnit } from '$lib/game/types'
export class DialogueInterface extends GraphicsContainer {
public unit: IGameObjectUnit
public messages: { id: string, text: string, isShowed: boolean }[]
public showingSpeed: number
#showingSpeed: number

constructor(unit: IGameObjectUnit) {
super({ type: 'INTERFACE' })

this.unit = unit
this.messages = []

this.showingSpeed = 0.0005
this.#showingSpeed = 0.05

this.x = 0
this.y = 0
Expand All @@ -28,10 +28,10 @@ export class DialogueInterface extends GraphicsContainer {
fontFamily: 'Noto Serif',
fontSize: 16,
fontWeight: '500',
fill: 0x694F62,
fill: 0x451A03,
align: 'left',
wordWrap: true,
wordWrapWidth: 300,
wordWrapWidth: 350,
},
})

Expand All @@ -41,8 +41,8 @@ export class DialogueInterface extends GraphicsContainer {
const rectHeight = basicText.height + rectOffsetY * 2

const graphics = new Graphics()
graphics.roundRect(-rectOffsetX, -rectOffsetY, rectWidth, rectHeight, 8)
graphics.fill(0xFFFFFF)
graphics.rect(-rectOffsetX, -rectOffsetY, rectWidth, rectHeight)
graphics.fill(0xFEF3C7)

container.addChild(graphics, basicText)

Expand Down Expand Up @@ -76,23 +76,23 @@ export class DialogueInterface extends GraphicsContainer {
this.create(needToShowMessages[0])

needToShowMessages[0].isShowed = true
this.showingSpeed = this.getShowingSpeed(
this.#showingSpeed = this.#getShowingSpeed(
needToShowMessages[0].text.length,
)
}

for (const container of this.children) {
container.visible = true
container.zIndex = 0
container.alpha -= this.showingSpeed
container.alpha -= this.#showingSpeed

if (container.alpha <= 0.8) {
this.remove(container)
}
}
}

getShowingSpeed(messageLength: number) {
return 0.0006 - (messageLength * 4) / 1000000
#getShowingSpeed(messageLength: number) {
return (0.05 - ((messageLength * 4) / 10000)) / this.unit.game.tick
}
}
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 })
}
}
27 changes: 13 additions & 14 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,19 +122,18 @@ export class Player extends UnitObject implements GameObjectPlayer {
}

async #readFromDB() {
// const res = await fetch(`/mock/game/player/${this.id}`)
// const player = await res.json()
// if (!player) {
// return
// }
const player = await this.game.serverService.getPlayer(this.id)
if (!player) {
return
}

// this.name = player.name
// this.coins = player.coins
// this.reputation = player.reputation
// this.villainPoints = player.villainPoints
// this.refuellerPoints = player.refuellerPoints
// this.raiderPoints = player.raiderPoints
// this.inventoryId = player.inventoryId
this.name = player.name
this.coins = player.coins
this.reputation = player.reputation
this.villainPoints = player.villainPoints
this.refuellerPoints = player.refuellerPoints
this.raiderPoints = player.raiderPoints
this.inventoryId = player.inventoryId
}

updateLastActionAt(): void {
Expand All @@ -153,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
Loading

0 comments on commit 195f3fc

Please sign in to comment.