Lab 8

Store all of your files for this lab in a folder named "lab8".

The provided code is a partially complete implementation of a 8 puzzle game. The game is played by swapping the blank tile with any non-diagonal adjacent tile until all the tiles are in the following order: 1 2 3 4 5 6 7 8

Everything should go into ep.cpp and the compiled program should be named ep. To complete the program, you must implement the move and completed member functions of the EightPuzzle class. You need not modify anything else. Descriptions of these member functions are provided in the comments:

#include <iostream> #include <iomanip> #include <vector> #include <algorithm> #include <random> using namespace std; class Board { private: vector< vector<char> > data; public: Board(int n) { this->resize(n); } void resize(int n) { this->data.resize(n); for (auto& row : this->data) { row.resize(n, '.'); } } void clear() { for (auto& row : this->data) { for (auto& col : row) { col = '.'; } } } char& operator()(int r, int c) { return this->data[r][c]; } const char& operator()(int r, int c) const { return this->data[r][c]; } int size() const { return this->data.size(); } }; std::ostream& operator<<(std::ostream& os, const Board& board) { int s = board.size(); for (int r = 0; r < s; ++r) { for (int c = 0; c < s; ++c) { os << board(r, c) << ' '; } os << std::endl; } return os; } class EightPuzzle : public Board { public: EightPuzzle() : Board(3) { this->reset(); } void reset() { char t = '1'; for (int r = 0; r < 3; ++r) { for (int c = 0; c < 3; ++c) { (*this)(r, c) = t++; } } (*this)(2, 2) = ' '; } void shuffle() { std::default_random_engine prng(std::random_device{}()); std::array<char, 9> a; char t = '1'; std::generate_n(a.begin(), 8, [&](){ return t++; }); a[8] = ' '; std::shuffle(a.begin(), a.end(), prng); auto it = a.begin(); for (int r = 0; r < 3; ++r) { for (int c = 0; c < 3; ++c) { (*this)(r, c) = *it++; } } } bool move(char dir) { /* Swaps the blank tile with an adjacent * tile specified by dir. dir can be 'w', * 'a', 's', or 'd' to indicate the top, * left, bottom, or right-adjacent tile * respectively. * * Returns true if the swap was successful * or false if the blank tile cannot be * moved in the specified direction. */ } bool completed() const { /* Returns true if the 8 puzzle * is completed. The 8 puzzle is * completed when it looks like * this: * * +---+---+---+ * | 1 | 2 | 3 | * +---+---+---+ * | 4 | 5 | 6 | * +---+---+---+ * | 7 | 8 | | * +---+---+---+ */ } }; int main() { EightPuzzle ep; char dir; ep.shuffle(); do { cout << ep << endl; if (not (cin >> dir)) break; if (not ep.move(dir)) { cout << "Invalid move." << endl; } } while (not ep.completed()); return 0; }