1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
|
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cctype>
using std::cout, std::cin, std::string, std::vector;
enum { North, East, South, West, Down, Up, NumDirs };
struct Room
{
string name;
string descrip;
int dirs[NumDirs];
Room(const string& nm, const string& desc, const int* d)
: name(nm), descrip(desc)
{
for (int i = 0; i < NumDirs; ++i) dirs[i] = d[i];
}
};
auto readRooms(const string& filename)
{
vector<Room> rooms;
string line;
std::ifstream in(filename);
if (!in)
{
std::cerr << "Error: Cannot open input file " << filename << '\n';
std::exit(EXIT_FAILURE);
}
using std::getline;
for (int n = 1, num; in >> num; ++n)
{
if (n != num)
{
std::cerr << "Error: rooms are out of order: "
<< num << " should be " << n << ".\n";
exit(EXIT_FAILURE);
}
string name, descrip;
getline(in >> std::ws, name);
int d[NumDirs];
for (int i = 0; i < NumDirs; ++i) in >> d[i];
getline(in >> std::ws, descrip);
while (getline(in, line) && !line.empty())
descrip += "\n" + line;
rooms.emplace_back(name, descrip, d);
}
return rooms;
}
int charDirToNumDir(char cd)
{
switch (cd)
{
case 'n': return 0;
case 'e': return 1;
case 's': return 2;
case 'w': return 3;
case 'd': return 4;
case 'u': return 5;
}
return -1;
}
std::string numDirToString(int d)
{
static const char* sdirs[NumDirs]
{"North", "East", "South", "West", "Down", "Up"};
return sdirs[d];
}
void describeRoom(const Room& r)
{
cout << r.name << '\n'
<< r.descrip << '\n'
<< "Exits are: ";
for (int i = 0; i < NumDirs; ++i)
if (r.dirs[i] != 0)
cout << numDirToString(i) << ' ';
cout << '\n';
}
void dumpRooms(const vector<Room>& rooms)
{
for (const auto& r: rooms)
{
describeRoom(r);
cout << '\n';
}
}
void explore(const vector<Room>& rooms)
{
int r = 0;
while (true)
{
describeRoom(rooms[r]);
int d = -1;
while (true)
{
cout << "Direction: ";
char cd;
cin >> cd;
cd = std::tolower(cd);
if (cd == 'q') return;
d = charDirToNumDir(cd);
if (d != -1 && rooms[r].dirs[d] != 0) break;
cout << "Bad direction\n";
}
r = rooms[r].dirs[d] - 1;
cout << '\n';
}
}
int main()
{
auto rooms = readRooms("rooms.txt");
//dumpRooms(rooms);
explore(rooms);
}
| |