Skip to content

Commit

Permalink
Added resources subtracting while building
Browse files Browse the repository at this point in the history
  • Loading branch information
k-karuna committed Jul 3, 2024
1 parent c211e61 commit 77b92e1
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions cardinal/system/create_building.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package system

import (
"errors"
"fmt"

"pkg.world.dev/world-engine/cardinal"
Expand Down Expand Up @@ -29,6 +30,10 @@ func CreateBuildingSystem(world cardinal.WorldContext) error {
return msg.CreateBuildingResult{Success: false}, fmt.Errorf("index of tiles out of range")
}

if err := SubtractResourcesToBuild(world, building, request.Tx.PersonaTag); err != nil {
return msg.CreateBuildingResult{Success: false}, err
}

tile := &(*playerMap.Tiles)[request.Msg.TileIndex]
if tile.Building == nil {
tile.Building = &building
Expand Down Expand Up @@ -76,3 +81,50 @@ func CreateBuildingSystem(world cardinal.WorldContext) error {
return msg.CreateBuildingResult{Success: true}, nil
})
}

func SubtractResourcesToBuild(world cardinal.WorldContext, building comp.Building, personaTag string) error {
playerResourcesEntityID, playerResources, _ := QueryComponent[comp.PlayerResources](
world,
personaTag,
filter.Component[comp.Player](),
filter.Component[comp.PlayerResources](),
)

resourcesToBuild := comp.BuildingConfigs[building.Type].Resources
for _, resource := range resourcesToBuild {
var playerResource *comp.Resource
var err error
if playerResource, err = GetResourceByType(playerResources, resource.Type); err != nil {
return fmt.Errorf("can't get player resource %s: %w", resource.Type, err)
}
if playerResource.Amount < resource.Amount {
return fmt.Errorf("not enough resource %s", resource.Type)
}

playerResource.Amount -= resource.Amount
SetResourceByType(playerResources, *playerResource)

if err := cardinal.SetComponent(world, playerResourcesEntityID, playerResources); err != nil {
return fmt.Errorf("failed to update player resource: %w", err)
}
}

return nil
}

func GetResourceByType(playerResources *comp.PlayerResources, resourceType comp.ResourceType) (*comp.Resource, error) {
for i := range playerResources.Resources {
if playerResources.Resources[i].Type == resourceType {
return &playerResources.Resources[i], nil
}
}
return nil, errors.New("resource not found")
}

func SetResourceByType(playerResources *comp.PlayerResources, newResource comp.Resource) {
for i := range playerResources.Resources {
if playerResources.Resources[i].Type == newResource.Type {
playerResources.Resources[i] = newResource
}
}
}

0 comments on commit 77b92e1

Please sign in to comment.