Source

zorkish / Inventory.hpp

/*
 * Inventory.hpp
 *
 *  Created on: 24/08/2012
 *      Author: rhys
 */

#ifndef INVENTORY_HPP_
#define INVENTORY_HPP_

#include <list>
#include <memory>
#include "Item.hpp"

class Inventory {
private:
    static const std::unique_ptr<Item> EMPTY_PTR;
    std::list<std::unique_ptr<Item>> items;

    auto find_it(const std::string& name)
            -> std::list<std::unique_ptr<Item>>::iterator {
        return std::find_if(begin(this->items), end(this->items),
            [&](const std::unique_ptr<Item>& item) {
                return item->identifies_as(name);
            });
    }

public:
    typedef std::list<std::unique_ptr<Item>>::const_iterator const_iterator;

    bool empty() const {
        return this->items.empty();
    }

    void add(std::unique_ptr<Item> item) {
        this->items.push_back(std::move(item));
    }

    const std::unique_ptr<Item>& get(const std::string& name) {
        auto it = this->find_it(name);
        if (it != end(this->items)) {
            return *it;
        } else {
            return Inventory::EMPTY_PTR;
        }
    }

    std::unique_ptr<Item> take(const std::string& name) {
        auto it = this->find_it(name);
        if (it != end(this->items)) {
            std::unique_ptr<Item> item = std::move(*it);
            this->items.erase(it);
            return item;
        } else {
            return std::unique_ptr<Item>();
        }
    }

    Inventory::const_iterator cbegin() const {
        return this->items.cbegin();
    }

    Inventory::const_iterator cend() const {
        return this->items.cend();
    }

    void for_each(std::function<void(const std::unique_ptr<Item>&)> f) const {
        std::for_each(this->cbegin(), this->cend(), f);
    }
};


#endif /* INVENTORY_HPP_ */