Skip to content

Commit a9f286e

Browse files
committed
feat: more optional refs
1 parent 954add4 commit a9f286e

File tree

3 files changed

+14
-10
lines changed

3 files changed

+14
-10
lines changed

include/entity_manager.hpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ class EntityManager {
2828
void clear_except_player();
2929
std::optional<std::reference_wrapper<Entity>> get_blocking_entity_at(
3030
Vector2D position);
31-
Entity* get_non_blocking_entity_at(Vector2D position);
31+
std::optional<std::reference_wrapper<Entity>> get_non_blocking_entity_at(
32+
Vector2D position);
3233
Entity* get_closest_living_monster(Vector2D position, float range) const;
3334
std::vector<Entity*> get_entities_at(Vector2D position);
3435
void place_entities(

src/entity_manager.cpp

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,14 +124,15 @@ EntityManager::get_blocking_entity_at(Vector2D position) {
124124
return std::nullopt;
125125
}
126126

127-
Entity* EntityManager::get_non_blocking_entity_at(Vector2D position) {
127+
std::optional<std::reference_wrapper<Entity>>
128+
EntityManager::get_non_blocking_entity_at(Vector2D position) {
128129
for (const auto& entity : entities_) {
129130
if (!entity->is_blocking() &&
130131
entity->get_transform_component().get_position() == position) {
131-
return entity;
132+
return std::reference_wrapper<Entity>(*entity);
132133
}
133134
}
134-
return nullptr;
135+
return std::nullopt;
135136
}
136137

137138
void EntityManager::remove(Entity* entity) {

src/events/command.cpp

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,15 @@
1212
namespace cpprl {
1313

1414
StateResult PickupCommand::execute() {
15-
Entity* item = world_.get_entities().get_non_blocking_entity_at(
16-
entity_->get_transform_component().get_position());
17-
if (item) {
15+
std::optional<std::reference_wrapper<Entity>> optional_item_ref =
16+
world_.get_entities().get_non_blocking_entity_at(
17+
entity_->get_transform_component().get_position());
18+
if (optional_item_ref.has_value()) {
19+
Entity& item = optional_item_ref.value().get();
1820
world_.get_message_log().add_message(
19-
"You pick up the " + item->get_name() + ".", WHITE);
20-
entity_->get_container().add(item);
21-
world_.get_entities().remove(item);
21+
"You pick up the " + item.get_name() + ".", WHITE);
22+
entity_->get_container().add(&item);
23+
world_.get_entities().remove(&item);
2224
} else {
2325
return NoOp{"There is nothing here to pick up."};
2426
}

0 commit comments

Comments
 (0)