c++五子棋
时间: 2023-06-29 13:16:49 浏览: 97
好的,这是一个简单的C++五子棋代码示例,您可以参考:
```cpp
#include <iostream>
using namespace std;
// 定义棋盘大小
const int BOARD_SIZE = 15;
// 定义棋盘中的棋子类型
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;
}
}
}
// 下棋函数
bool PlaceChess(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 >= 5) {
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 >= 5) {
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 >= 5) {
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 >= 5) {
return true;
}
return false;
}
// 打印棋盘函数
void DrawBoard() {
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++) {
if (board[i][j] == EMPTY) {
cout << "+ ";
} else if (board[i][j] == BLACK) {
cout << "X ";
} else {
cout << "O ";
}
}
cout << endl;
}
}
private:
ChessType board[BOARD_SIZE][BOARD_SIZE];
};
int main() {
ChessBoard board;
int x, y;
ChessType type = BLACK;
while (true) {
board.DrawBoard();
cout << (type == BLACK ? "Black" : "White") << "'s turn. Input x,y to place chess: ";
cin >> x >> y;
if (board.PlaceChess(x, y, type)) {
if (board.CheckWin(x, y, type)) {
board.DrawBoard();
cout << (type == BLACK ? "Black" : "White") << " wins!" << endl;
break;
}
type = (type == BLACK ? WHITE : BLACK);
} else {
cout << "Invalid position, please input again." << endl;
}
}
return 0;
}
```
这个代码实现了五子棋游戏的基本功能,包括下棋、判断胜负和打印棋盘等。
阅读全文