From 77b92e1c41ee8eb1f5ef3afa15e5861b1007f571 Mon Sep 17 00:00:00 2001 From: Konst Date: Wed, 3 Jul 2024 13:56:22 +0300 Subject: [PATCH] Added resources subtracting while building --- cardinal/system/create_building.go | 52 ++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/cardinal/system/create_building.go b/cardinal/system/create_building.go index 98ea1cc..7017042 100644 --- a/cardinal/system/create_building.go +++ b/cardinal/system/create_building.go @@ -1,6 +1,7 @@ package system import ( + "errors" "fmt" "pkg.world.dev/world-engine/cardinal" @@ -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 @@ -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 + } + } +}