Skip to content

Commit

Permalink
Added farming key to player resources query
Browse files Browse the repository at this point in the history
  • Loading branch information
k-karuna committed Jul 1, 2024
1 parent ecfb35d commit 5a954cf
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
26 changes: 25 additions & 1 deletion cardinal/query/player_resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,41 @@ type PlayerResourcesRequest struct {
type PlayerResourcesResponse struct {
Resources []comp.Resource `json:"resources"`
Effects []comp.Effect `json:"effects"`
Farming []comp.Farming `json:"farming"`
}

func PlayerResources(world cardinal.WorldContext, req *PlayerResourcesRequest) (*PlayerResourcesResponse, error) {
_, playerResources, err := system.QueryComponent[comp.PlayerResources](
_, playerResources, _ := system.QueryComponent[comp.PlayerResources](
world,
req.Nickname,
filter.Component[comp.Player](),
filter.Component[comp.PlayerResources](),
)

_, farmingComponents, err := system.QueryAllComponents[comp.Farming](
world,
req.Nickname,
filter.Component[comp.Building](),
filter.Component[comp.Farming](),
)

aggregatedFarmingMap := make(map[comp.ResourceType]float32)
for _, farming := range farmingComponents {
aggregatedFarmingMap[farming.Type] += farming.Speed
}

aggregatedfarmingSlice := make([]comp.Farming, 0, len(aggregatedFarmingMap))

for resourceType, speed := range aggregatedFarmingMap {
aggregatedfarmingSlice = append(aggregatedfarmingSlice, comp.Farming{
Type: resourceType,
Speed: speed,
})
}

return &PlayerResourcesResponse{
Resources: playerResources.Resources,
Effects: playerResources.Effects,
Farming: aggregatedfarmingSlice,
}, err
}
35 changes: 35 additions & 0 deletions cardinal/system/query_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,38 @@ func QueryComponent[T types.Component](

return entityID, targetComponent, err
}

func QueryAllComponents[T types.Component](
world cardinal.WorldContext,
targetNickname string,
components ...filter.ComponentWrapper,
) (types.EntityID, []*T, error) {
var entityID types.EntityID
var targetComponents []*T
var err error

searchErr := cardinal.NewSearch().Entity(
filter.Contains(components...)).Each(world,
func(id types.EntityID) bool {
var player *comp.Player
player, err = cardinal.GetComponent[comp.Player](world, id)
if err != nil {
return false
}

if player.Nickname == targetNickname {
entityID = id
targetComponent, _ := cardinal.GetComponent[T](world, id)
targetComponents = append(targetComponents, targetComponent)
}

return true
})
if searchErr != nil {
return 0, nil, err
}
if err != nil {
return 0, nil, err
}
return entityID, targetComponents, err
}

0 comments on commit 5a954cf

Please sign in to comment.