programming c++

profileRahanmet
example3x3.cpp

#define DEBUG #include <iostream> #include <vector> #include <iomanip> #include <algorithm> using namespace std; class Cell { bool m_occu; // unoccupied, shown '.' bool m_mark; // true -> circle 'o', false -> cross 'x' public: Cell() : m_occu(false), m_mark(false) {} void setMark(const bool h_or_c) {m_mark = h_or_c; m_occu = true;} bool isMarked() const { return m_occu;} bool isCircle() const { return m_occu && m_mark; } bool isCross() const { return m_occu && !m_mark; } friend ostream& operator<<(ostream& o, const Cell& c) { if(!c.m_occu) return o << setw(2) << '.'; return o << setw(2) << (c.m_mark? 'o' : 'x'); } }; class Board { vector<vector<Cell> > m_map; public: Board(){ vector<Cell> a_row(3); for (int i = 0; i < 3; ++i) m_map.push_back(a_row); } bool setMark(const bool h_or_c, const int r, const int c) { if(m_map[r][c].isMarked()) return false; m_map[r][c].setMark(h_or_c); return true; } bool isMarked(const int r, const int c) const { return m_map[r][c].isMarked();} bool isWon(const bool h_or_c) const { int circle = 0, cross = 0; for (int row = 0; row < 3; ++row){ circle = cross = 0; for(int col = 0; col < 3; ++col) { if(m_map[row][col].isCircle()) { if(++circle > 2 && h_or_c) return true; } if(m_map[row][col].isCross()) { if(++cross > 2 && !h_or_c) return true; } } } for (int col = 0; col < 3; ++col){ circle = cross = 0; for(int row = 0; row < 3; ++row) { if(m_map[row][col].isCircle()) { if(++circle > 2 && h_or_c) return true; } if(m_map[row][col].isCross()) { if(++cross > 2 && !h_or_c) return true; } } } circle = cross = 0; for(int row = 2, col = 0; row >= 3 && col < 3; --row, ++col) { if(m_map[row][col].isCircle()) { if(++circle > 2 && h_or_c) return true; } if(m_map[row][col].isCross()) { if(++cross > 2 && !h_or_c) return true; } } return false; } friend ostream& operator<<(ostream& o, const Board& b) { cout << " "; for(int col = 0; col < 3; ++col) o << setw(2) << char('1'+col); o << endl; for(int row = 0; row < 3; ++row) { o << setw(3) << char('A' + row); for(int col = 0; col < 3; ++col) o << b.m_map[row][col]; o << endl; } return o; } }; struct Turn { int m_row; int m_col; Turn (const int r = 0, const int c = 0) : m_row(r), m_col(c) {} }; int main() { Board b; while(true){ cout << b; cout << "\nEnter row/col: "; char r, c ; cin >> r >> c; b.setMark(true, r - 'A', c - '1'); //omit consistency check. if(b.isWon(true)) { cout << "You won!" << endl; break; } vector<Turn> vt; for(int row = 0; row <3; ++row) for(int col =0; col <3; ++col) if(!b.isMarked(row, col)) vt.push_back(Turn(row,col)); if(vt.size() <= 0) { cout << "Tied..." << endl; break; } random_shuffle(vt.begin(), vt.end()); b.setMark(false, vt[0].m_row, vt[0].m_col); if(b.isWon(false)){ cout << "You lost!" << endl; break; } } cout << b; return 0; }