用C++写一个五子棋游戏
作者:野牛程序员:2023-06-01 19:29:08 C++阅读 2407
以下是一个用C++编写的简单五子棋游戏的示例:
#include <iostream> #include <vector> const int BOARD_SIZE = 15; const char EMPTY = '.'; const char BLACK = 'X'; const char WHITE = 'O'; std::vector<std::vector<char> > board(BOARD_SIZE, std::vector<char>(BOARD_SIZE, EMPTY)); bool isValidMove(int row, int col) { return (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE && board[row][col] == EMPTY); } bool checkWin(int row, int col, char player) { int directions[4][2] = {{1, 0}, {0, 1}, {1, 1}, {1, -1}}; for (int i = 0; i < 4; i++) { int count = 1; int dx = directions[i][0]; int dy = directions[i][1]; int r = row + dx; int c = col + dy; while (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE && board[r][c] == player) { count++; r += dx; c += dy; } dx = -dx; dy = -dy; r = row + dx; c = col + dy; while (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE && board[r][c] == player) { count++; r += dx; c += dy; } if (count >= 5) { return true; } } return false; } void printBoard() { for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { std::cout << board[i][j] << ' '; } std::cout << std::endl; } } void playGame() { char currentPlayer = BLACK; while (true) { printBoard(); int row, col; std::cout << "Player " << currentPlayer << ", enter your move (row column): "; std::cin >> row >> col; if (isValidMove(row, col)) { board[row][col] = currentPlayer; if (checkWin(row, col, currentPlayer)) { std::cout << "Player " << currentPlayer << " wins!" << std::endl; break; } currentPlayer = (currentPlayer == BLACK) ? WHITE : BLACK; } else { std::cout << "Invalid move. Try again." << std::endl; } } } int main() { playGame(); return 0; }
这个示例实现了一个简单的五子棋游戏。游戏使用15x15的棋盘,玩家可以轮流下棋。玩家通过输入行和列来选择落子位置。程序会检查是否有玩家获胜,如果有,游戏结束并宣布胜利者。否则,游戏将继续进行,直到有玩家获胜或棋盘被下满。
请注意,此示例只是一个基本的五子棋游戏框架,并未添加任何高级功能,如禁手规则、悔棋、人机对战等。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
- 上一篇:应用如何实现redis的双写
- 下一篇:数论之素数