帮我写一个五子棋的c++代码
时间: 2023-08-20 14:56:27 浏览: 99
当然,下面是一个简单的五子棋游戏的C++代码示例:
```cpp
#include <iostream>
#include <vector>
const int BOARD_SIZE = 15;
const char EMPTY = '-';
const char PLAYER_ONE = 'X';
const char PLAYER_TWO = 'O';
std::vector<std::vector<char>> board(BOARD_SIZE, std::vector<char>(BOARD_SIZE, EMPTY));
void printBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
std::cout << board[i][j] << " ";
}
std::cout << std::endl;
}
}
bool isFull() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == EMPTY) {
return false;
}
}
}
return true;
}
bool checkWin(char player) {
// 检查行
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j <= BOARD_SIZE - 5; j++) {
bool win = true;
for (int k = 0; k < 5; k++) {
if (board[i][j + k] != player) {
win = false;
break;
}
}
if (win) {
return true;
}
}
}
// 检查列
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j <= BOARD_SIZE - 5; j++) {
bool win = true;
for (int k = 0; k < 5; k++) {
if (board[j + k][i] != player) {
win = false;
break;
}
}
if (win) {
return true;
}
}
}
// 检查主对角线
for (int i = 0; i <= BOARD_SIZE - 5; i++) {
for (int j = 0; j <= BOARD_SIZE - 5; j++) {
bool win = true;
for (int k = 0; k < 5; k++) {
if (board[i + k][j + k] != player) {
win = false;
break;
}
}
if (win) {
return true;
}
}
}
// 检查副对角线
for (int i = 4; i < BOARD_SIZE; i++) {
for (int j = 0; j <= BOARD_SIZE - 5; j++) {
bool win = true;
for (int k = 0; k < 5; k++) {
if (board[i - k][j + k] != player) {
win = false;
break;
}
}
if (win) {
return true;
}
}
}
return false;
}
bool makeMove(int row, int col, char player) {
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE || board[row][col] != EMPTY) {
return false;
}
board[row][col] = player;
return true;
}
int main() {
char currentPlayer = PLAYER_ONE;
while (true) {
std::cout << "当前棋盘:" << std::endl;
printBoard();
int row, col;
std::cout << "玩家 " << currentPlayer << ",请输入要落子的坐标(行 列):";
std::cin >> row >> col;
if (makeMove(row, col, currentPlayer)) {
if (checkWin(currentPlayer)) {
std::cout << "玩家 " << currentPlayer << " 获胜!" << std::endl;
break;
} else if (isFull()) {
std::cout << "游戏结束,平局!" << std::endl;
break;
}
currentPlayer = (currentPlayer == PLAYER_ONE) ? PLAYER_TWO : PLAYER_ONE;
} else {
std::cout << "无效的落子位置,请重新输入!" << std::endl;
}
}
return 0;
}
```
这段代码实现了一个简单的五子棋游戏。玩家可以交替输入要落子的坐标(行和列),程序会根据玩家输入的位置进行落子判断,并打印出当前棋盘状态。当有一方玩家获胜或者棋盘已满时,游戏结束。注意,此代码只实现了基本的功能,还可以根据需要进行扩展和优化。
阅读全文