写一个五子棋的c++代码
时间: 2024-03-10 22:47:20 浏览: 68
以下是基本的五子棋 C++ 代码,包括棋盘的绘制、用户输入、落子和判断胜负等功能:
```c++
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 15;
char board[MAXN][MAXN]; // 棋盘
int n = 10; // 棋盘大小
// 绘制棋盘
void draw_board() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
// 判断胜负
bool check_win(char c) {
// 判断行
for (int i = 0; i < n; i++) {
int cnt = 0;
for (int j = 0; j < n; j++) {
if (board[i][j] == c) cnt++;
else cnt = 0;
if (cnt >= 5) return true;
}
}
// 判断列
for (int j = 0; j < n; j++) {
int cnt = 0;
for (int i = 0; i < n; i++) {
if (board[i][j] == c) cnt++;
else cnt = 0;
if (cnt >= 5) return true;
}
}
// 判断对角线
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int cnt = 0;
for (int k = 0; k < 5 && i+k<n && j+k<n; k++) {
if (board[i+k][j+k] == c) cnt++;
else break;
if (cnt >= 5) return true;
}
cnt = 0;
for (int k = 0; k < 5 && i+k<n && j-k>=0; k++) {
if (board[i+k][j-k] == c) cnt++;
else break;
if (cnt >= 5) return true;
}
}
}
return false;
}
int main() {
memset(board, '.', sizeof(board)); // 初始化棋盘
draw_board(); // 绘制棋盘
char player = 'X'; // 先手为 X
while (true) {
cout << "Player " << player << " turn:" << endl;
int x, y;
cin >> x >> y;
if (x < 0 || x >= n || y < 0 || y >= n || board[x][y] != '.') {
cout << "Invalid move!" << endl;
continue;
}
board[x][y] = player; // 落子
draw_board(); // 绘制棋盘
if (check_win(player)) {
cout << "Player " << player << " wins!" << endl;
break;
}
// 交换玩家
player = (player == 'X' ? 'O' : 'X');
}
return 0;
}
```
这只是一个基本的五子棋代码,你可以根据需求进行修改和扩展。
阅读全文