生成五子棋的C++代码。
时间: 2024-02-15 13:03:53 浏览: 26
以下是一个简单的五子棋C++代码,供参考:
```c++
#include <iostream>
using namespace std;
const int ROWS = 15; // 棋盘行数
const int COLS = 15; // 棋盘列数
enum ChessType { NONE, BLACK, WHITE }; // 棋子类型
class ChessBoard {
public:
ChessBoard() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
board[i][j] = NONE;
}
}
}
void printBoard() {
cout << " ";
for (int i = 0; i < COLS; i++) {
cout << i << " ";
}
cout << endl;
for (int i = 0; i < ROWS; i++) {
cout << i << " ";
for (int j = 0; j < COLS; j++) {
if (board[i][j] == NONE) {
cout << "+ ";
} else if (board[i][j] == BLACK) {
cout << "X ";
} else if (board[i][j] == WHITE) {
cout << "O ";
}
}
cout << endl;
}
}
bool placeChess(int row, int col, ChessType type) {
if (row < 0 || row >= ROWS || col < 0 || col >= COLS) {
return false;
}
if (board[row][col] != NONE) {
return false;
}
board[row][col] = type;
return true;
}
ChessType getChess(int row, int col) {
if (row < 0 || row >= ROWS || col < 0 || col >= COLS) {
return NONE;
}
return board[row][col];
}
private:
ChessType board[ROWS][COLS]; // 棋盘
};
class ChessGame {
public:
ChessGame() {
curPlayer = BLACK;
board = new ChessBoard();
}
~ChessGame() {
delete board;
}
void play() {
int row, col;
while (true) {
board->printBoard();
cout << "Player " << curPlayer << " (row, col): ";
cin >> row >> col;
if (board->placeChess(row, col, curPlayer)) {
if (checkWin(row, col)) {
board->printBoard();
cout << "Player " << curPlayer << " wins!" << endl;
break;
}
curPlayer = (curPlayer == BLACK) ? WHITE : BLACK;
} else {
cout << "Invalid move. Please try again." << endl;
}
}
}
private:
bool checkWin(int row, int col) {
ChessType type = board->getChess(row, col);
int count = 0;
for (int i = row - 4; i <= row + 4; i++) {
if (i < 0 || i >= ROWS) {
continue;
}
if (board->getChess(i, col) == type) {
count++;
if (count >= 5) {
return true;
}
} else {
count = 0;
}
}
count = 0;
for (int j = col - 4; j <= col + 4; j++) {
if (j < 0 || j >= COLS) {
continue;
}
if (board->getChess(row, j) == type) {
count++;
if (count >= 5) {
return true;
}
} else {
count = 0;
}
}
count = 0;
for (int k = -4; k <= 4; k++) {
int i = row + k, j = col + k;
if (i < 0 || i >= ROWS || j < 0 || j >= COLS) {
continue;
}
if (board->getChess(i, j) == type) {
count++;
if (count >= 5) {
return true;
}
} else {
count = 0;
}
}
count = 0;
for (int k = -4; k <= 4; k++) {
int i = row + k, j = col - k;
if (i < 0 || i >= ROWS || j < 0 || j >= COLS) {
continue;
}
if (board->getChess(i, j) == type) {
count++;
if (count >= 5) {
return true;
}
} else {
count = 0;
}
}
return false;
}
ChessType curPlayer; // 当前玩家
ChessBoard* board; // 棋盘
};
int main() {
ChessGame game;
game.play();
return 0;
}
```
这个代码实现了一个简单的五子棋游戏,包括棋盘、棋子、玩家、胜负判断等功能。在主函数中创建了一个`ChessGame`对象,并调用其中的`play`方法开始游戏。在游戏进行中,玩家可以输入要下棋子的位置,程序会判断是否合法并放置棋子,同时判断是否有玩家获胜。