c++面向对象的五子棋代码
时间: 2023-09-12 08:09:54 浏览: 62
下面是一个简单的 C++ 面向对象的五子棋代码,仅供参考:
```
#include <iostream>
using namespace std;
class Chessboard {
public:
Chessboard(); // 构造函数
void print(); // 打印棋盘
bool checkWin(int row, int col); // 检查胜利条件
bool setChess(int row, int col, char chess); // 下棋
private:
char board[15][15]; // 存储棋盘
};
Chessboard::Chessboard() {
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
board[i][j] = '+';
}
}
}
void Chessboard::print() {
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
bool Chessboard::checkWin(int row, int col) {
char chess = board[row][col];
int count = 0;
// 检查行
for (int i = 0; i < 15; i++) {
if (board[row][i] == chess) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
count = 0;
// 检查列
for (int i = 0; i < 15; i++) {
if (board[i][col] == chess) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
count = 0;
// 检查左上到右下斜线
for (int i = row, j = col; i < 15 && j < 15; i++, j++) {
if (board[i][j] == chess) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
count = 0;
// 检查右上到左下斜线
for (int i = row, j = col; i >= 0 && j < 15; i--, j++) {
if (board[i][j] == chess) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
return false;
}
bool Chessboard::setChess(int row, int col, char chess) {
if (board[row][col] == '+') {
board[row][col] = chess;
return true;
}
return false;
}
int main() {
Chessboard board;
char player1 = 'O';
char player2 = 'X';
bool isPlayer1 = true;
int row, col;
while (true) {
board.print();
char chess = isPlayer1 ? player1 : player2;
cout << "Player " << (isPlayer1 ? "1" : "2") << " (" << chess << "), please enter the row and column (e.g. 3 4) to set your chess: ";
cin >> row >> col;
if (board.setChess(row - 1, col - 1, chess)) {
if (board.checkWin(row - 1, col - 1)) {
board.print();
cout << "Player " << (isPlayer1 ? "1" : "2") << " (" << chess << ") wins!" << endl;
break;
}
isPlayer1 = !isPlayer1;
} else {
cout << "Invalid input or the position is already occupied. Please try again." << endl;
}
}
return 0;
}
```
这个程序使用了一个 `Chessboard` 类来表示棋盘,包含了打印棋盘、检查胜利条件以及下棋的方法。在 `main` 函数中,通过交替使用两个玩家的棋子来进行游戏,并检查是否有玩家胜利。