用c++写一个五子棋游戏代码
时间: 2024-01-02 09:01:57 浏览: 115
好的,以下是一个简单的 C++ 五子棋游戏代码:
```c++
#include <iostream>
using namespace std;
const int BOARD_SIZE = 15; // 定义棋盘大小
enum Piece { EMPTY = 0, BLACK = 1, WHITE = 2 }; // 定义棋子类型
class Board {
public:
Board() { // 初始化棋盘
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = EMPTY;
}
}
}
void print() { // 打印棋盘
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 canMove(int row, int col) { // 判断该位置是否可以落子
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) {
return false;
}
if (board[row][col] != EMPTY) {
return false;
}
return true;
}
bool move(int row, int col, Piece piece) { // 落子
if (!canMove(row, col)) {
return false;
}
board[row][col] = piece;
return true;
}
bool isWin(int row, int col, Piece piece) { // 判断是否胜利
// 水平方向
int count = 1;
for (int i = col - 1; i >= 0; i--) { // 左边
if (board[row][i] == piece) {
count++;
} else {
break;
}
}
for (int i = col + 1; i < BOARD_SIZE; i++) { // 右边
if (board[row][i] == piece) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 垂直方向
count = 1;
for (int i = row - 1; i >= 0; i--) { // 上面
if (board[i][col] == piece) {
count++;
} else {
break;
}
}
for (int i = row + 1; i < BOARD_SIZE; i++) { // 下面
if (board[i][col] == piece) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 左上到右下方向
count = 1;
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { // 左上
if (board[i][j] == piece) {
count++;
} else {
break;
}
}
for (int i = row + 1, j = col + 1; i < BOARD_SIZE && j < BOARD_SIZE; i++, j++) { // 右下
if (board[i][j] == piece) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 右上到左下方向
count = 1;
for (int i = row - 1, j = col + 1; i >= 0 && j < BOARD_SIZE; i--, j++) { // 右上
if (board[i][j] == piece) {
count++;
} else {
break;
}
}
for (int i = row + 1, j = col - 1; i < BOARD_SIZE && j >= 0; i++, j--) { // 左下
if (board[i][j] == piece) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
return false;
}
private:
Piece board[BOARD_SIZE][BOARD_SIZE];
};
int main() {
Board board;
Piece turn = BLACK;
while (true) {
board.print();
int row, col;
cout << "Player " << (turn == BLACK ? "X" : "O") << " move (row col): ";
cin >> row >> col;
if (!board.move(row, col, turn)) {
cout << "Invalid move!" << endl;
continue;
}
if (board.isWin(row, col, turn)) {
cout << "Player " << (turn == BLACK ? "X" : "O") << " wins!" << endl;
break;
}
turn = (turn == BLACK ? WHITE : BLACK);
}
return 0;
}
```
这个五子棋游戏代码实现了基本的落子、胜负判断和打印棋盘功能,但是还有很多可以改进的地方,比如增加悔棋功能、实现人机对战等等。
阅读全文