Connect Four Game Gaming Project in C++
|
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 |
#include <iostream> #include <vector> using namespace std; class ConnectFour { public: ConnectFour(); void playGame(); private: vector<vector<char>> board; int rows, cols; char currentPlayer; void printBoard(); bool makeMove(int col); bool checkWin(int row, int col); bool checkDirection(int startX, int startY, int dirX, int dirY); bool isFull(); }; ConnectFour::ConnectFour() : rows(6), cols(7), currentPlayer('X') { board.resize(rows, vector<char>(cols, '.')); } void ConnectFour::printBoard() { for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << board[i][j] << " "; } cout << endl; } cout << endl; } bool ConnectFour::makeMove(int col) { if (col < 0 || col >= cols || board[0][col] != '.') { cout << "Invalid move. Try again." << endl; return false; } for (int i = rows - 1; i >= 0; --i) { if (board[i][col] == '.') { board[i][col] = currentPlayer; if (checkWin(i, col)) { printBoard(); cout << "Player " << currentPlayer << " wins!" << endl; return true; } currentPlayer = (currentPlayer == 'X') ? 'O' : 'X'; return false; } } return false; } bool ConnectFour::checkWin(int row, int col) { return checkDirection(row, col, 1, 0) || // Horizontal checkDirection(row, col, 0, 1) || // Vertical checkDirection(row, col, 1, 1) || // Diagonal / checkDirection(row, col, 1, -1); // Diagonal \ } bool ConnectFour::checkDirection(int startX, int startY, int dirX, int dirY) { int count = 0; for (int i = -3; i <= 3; ++i) { int x = startX + i * dirX; int y = startY + i * dirY; if (x >= 0 && x < rows && y >= 0 && y < cols && board[x][y] == currentPlayer) { count++; if (count == 4) return true; } else { count = 0; } } return false; } bool ConnectFour::isFull() { for (int i = 0; i < cols; ++i) { if (board[0][i] == '.') return false; } return true; } void ConnectFour::playGame() { int col; bool gameWon = false; cout << "Welcome to Connect Four!" << endl; while (!gameWon && !isFull()) { printBoard(); cout << "Player " << currentPlayer << ", enter the column (0-" << cols-1 << ") to drop your piece: "; cin >> col; gameWon = makeMove(col); } if (!gameWon) { printBoard(); cout << "The game is a draw!" << endl; } } int main() { ConnectFour game; game.playGame(); return 0; } |
Explanation: Class Definition (ConnectFour): The ConnectFour class manages the game, including the game board, player moves, and win condition checks. Board Initialization: The board is initialized as a 6×7 grid filled with dots (‘.’), representing empty slots. The currentPlayer is set to ‘X’, meaning player X starts the game. Board Printing (printBoard): The printBoard …
