109 lines
2.4 KiB
C++
109 lines
2.4 KiB
C++
|
|
||
|
|
||
|
#include "State.h"
|
||
|
#include <algorithm>
|
||
|
#include <ctime>
|
||
|
|
||
|
/**
|
||
|
* Current state of the game.
|
||
|
*/
|
||
|
|
||
|
/**
|
||
|
* Display the description of the room the player is in. */
|
||
|
|
||
|
void State::announceLoc() const {
|
||
|
Room::getRoomById(currentRoomId)->describe();
|
||
|
}
|
||
|
|
||
|
int State::seed = time(nullptr);
|
||
|
|
||
|
/**
|
||
|
* Constructor.
|
||
|
* @param startRoom Pointer to the room to start in.
|
||
|
*/
|
||
|
State::State(int room_id) : currentRoomId(room_id),inventory_sorted(true),inventory(),HP(100) {};
|
||
|
|
||
|
/**
|
||
|
* Move to a specified room and print its description.
|
||
|
* @param target Pointer to the room to move to.
|
||
|
*/
|
||
|
void State::goTo(Room *target) {
|
||
|
if (target != nullptr) {
|
||
|
this->currentRoomId = target->getRoomId();
|
||
|
this->announceLoc();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Return a pointer to the current room.
|
||
|
* @return Pointer to the current room.
|
||
|
*/
|
||
|
Room *State::getCurrentRoom() const {
|
||
|
return Room::room_map.find(currentRoomId)->second;
|
||
|
}
|
||
|
|
||
|
int State::getHP() const {
|
||
|
return HP;
|
||
|
}
|
||
|
|
||
|
void State::setHP(int HP) {
|
||
|
HP = std::min(HP, 100);
|
||
|
HP = std::max(HP, 0);
|
||
|
this->HP = HP;
|
||
|
}
|
||
|
|
||
|
string State::ToString() const {
|
||
|
Packer packer;
|
||
|
for (auto it = inventory.begin(); it != inventory.end(); it++) {
|
||
|
packer.pack(*it);
|
||
|
}
|
||
|
packer.pack(inventory.size())
|
||
|
.pack(HP)
|
||
|
.pack(currentRoomId);
|
||
|
return packer.ToHexStr();
|
||
|
}
|
||
|
|
||
|
void State::FromString(const string &str) {
|
||
|
inventory.clear();
|
||
|
Packer packer;
|
||
|
packer.FromHexStr(str);
|
||
|
size_t inventory_size;
|
||
|
|
||
|
packer.unpack(currentRoomId)
|
||
|
.unpack(HP)
|
||
|
.unpack(inventory_size);
|
||
|
for (int i = 0; i < inventory_size; i++) {
|
||
|
int id;
|
||
|
packer.unpack(id);
|
||
|
inventory.push_back(id);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
std::list<int> State::getInventory() {
|
||
|
inventory_sorted = true;
|
||
|
inventory.sort();
|
||
|
return inventory;
|
||
|
}
|
||
|
|
||
|
bool State::IsInInventory(int object_id) const {
|
||
|
return std::find(inventory.begin(), inventory.end(), object_id) != inventory.end();
|
||
|
}
|
||
|
|
||
|
void State::addToInventory(int object_id) {
|
||
|
inventory.push_back(object_id);
|
||
|
inventory_sorted = false;
|
||
|
}
|
||
|
|
||
|
void State::removeFromInventory(int object_id) {
|
||
|
inventory.remove(object_id);
|
||
|
inventory_sorted = false;
|
||
|
}
|
||
|
|
||
|
int State::NextRandom() {
|
||
|
const int a = 1103515245;
|
||
|
const int c = 12345;
|
||
|
const int m = 1 << 31;
|
||
|
seed = (a * seed + c) % m;
|
||
|
return (int)((unsigned int)seed >> 1);
|
||
|
}
|