用c++写一个五子棋游戏
时间: 2024-06-13 11:06:52 浏览: 107
以下是用C++编写五子棋游戏的示例代码:
```c++
#include <iostream>
using namespace std;
const int BOARD_SIZE = 15; // 棋盘大小
const int WIN_COUNT = 5; // 获胜所需棋子数
enum ChessType { EMPTY, BLACK, WHITE }; // 棋子类型
class ChessBoard {
public:
ChessBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = EMPTY;
}
}
}
void printBoard() {
cout << " ";
for (int i = 0; i < BOARD_SIZE; i++) {
cout << i << " ";
}
cout << endl;
for (int i = 0; i < BOARD_SIZE; i++) {
cout << i << " ";
for (int j = 0; j < BOARD_SIZE; j++) {
switch (board[i][j]) {
case EMPTY:
cout << "+ ";
break;
case BLACK:
cout << "X ";
break;
case WHITE:
cout << "O ";
break;
}
}
cout << endl;
}
}
bool putChess(int x, int y, ChessType type) {
if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE || board[x][y] != EMPTY) {
return false;
}
board[x][y] = type;
return true;
}
bool checkWin(int x, int y, ChessType type) {
int count = 1;
for (int i = x - 1; i >= 0 && board[i][y] == type; i--) {
count++;
}
for (int i = x + 1; i < BOARD_SIZE && board[i][y] == type; i++) {
count++;
}
if (count >= WIN_COUNT) {
return true;
}
count = 1;
for (int j = y - 1; j >= 0 && board[x][j] == type; j--) {
count++;
}
for (int j = y + 1; j < BOARD_SIZE && board[x][j] == type; j++) {
count++;
}
if (count >= WIN_COUNT) {
return true;
}
count = 1;
for (int i = x - 1, j = y - 1; i >= 0 && j >= 0 && board[i][j] == type; i--, j--) {
count++;
}
for (int i = x + 1, j = y + 1; i < BOARD_SIZE && j < BOARD_SIZE && board[i][j] == type; i++, j++) {
count++;
}
if (count >= WIN_COUNT) {
return true;
}
count = 1;
for (int i = x - 1, j = y + 1; i >= 0 && j < BOARD_SIZE && board[i][j] == type; i--, j++) {
count++;
}
for (int i = x + 1, j = y - 1; i < BOARD_SIZE && j >= 0 && board[i][j] == type; i++, j--) {
count++;
}
if (count >= WIN_COUNT) {
return true;
}
return false;
}
private:
ChessType board[BOARD_SIZE][BOARD_SIZE];
};
int main() {
ChessBoard board;
int x, y;
ChessType type = BLACK;
while (true) {
board.printBoard();
cout << (type == BLACK ? "Black" : "White") << " player's turn, please input the coordinate (x y): ";
cin >> x >> y;
if (board.putChess(x, y, type)) {
if (board.checkWin(x, y, type)) {
board.printBoard();
cout << (type == BLACK ? "Black" : "White") << " player wins!" << endl;
break;
}
type = type == BLACK ? WHITE : BLACK;
}
else {
cout << "Invalid input, please try again." << endl;
}
}
return 0;
}
```
阅读全文