DEEPSEEK版五子棋(人机)
2026-10-10 20:47:00
发布于:四川
#include<bits/stdc++.h>
using namespace std;
int a[31][31]; // 棋盘:0空,1玩家,2电脑
int c, k; // c行数,k列数
// 检查在 (x, y) 落子 player 后是否形成五子连珠
bool checkWin(int x, int y, int player) {
int dirs[4][2] = {{0,1}, {1,0}, {1,1}, {1,-1}};
for (int d = 0; d < 4; d++) {
int dx = dirs[d][0], dy = dirs[d][1];
int count = 1;
// 正方向
for (int i = 1; i < 5; i++) {
int nx = x + i * dx, ny = y + i * dy;
if (nx < 1 || nx > c || ny < 1 || ny > k || a[nx][ny] != player) break;
count++;
}
// 反方向
for (int i = 1; i < 5; i++) {
int nx = x - i * dx, ny = y - i * dy;
if (nx < 1 || nx > c || ny < 1 || ny > k || a[nx][ny] != player) break;
count++;
}
if (count >= 5) return true;
}
return false;
}
// 电脑下棋:先赢,再阻挡,最后随机
void computerMove() {
int i, j;
// 1. 尝试自己获胜
for (i = 1; i <= c; i++) {
for (j = 1; j <= k; j++) {
if (a[i][j] == 0) {
a[i][j] = 2;
if (checkWin(i, j, 2)) return;
a[i][j] = 0;
}
}
}
// 2. 阻挡玩家获胜
for (i = 1; i <= c; i++) {
for (j = 1; j <= k; j++) {
if (a[i][j] == 0) {
a[i][j] = 1;
if (checkWin(i, j, 1)) {
a[i][j] = 2;
return;
}
a[i][j] = 0;
}
}
}
// 3. 随机选择空位
int empties[900][2];
int cnt = 0;
for (i = 1; i <= c; i++)
for (j = 1; j <= k; j++)
if (a[i][j] == 0) {
empties[cnt][0] = i;
empties[cnt][1] = j;
cnt++;
}
if (cnt > 0) {
int idx = rand() % cnt;
a[empties[idx][0]][empties[idx][1]] = 2;
}
}
// 打印棋盘
void printBoard() {
int i, j;
for (i = 1; i <= c; i++) {
for (j = 1; j <= k; j++) {
if (a[i][j] == 0) cout << "- ";
else if (a[i][j] == 1) cout << "O ";
else cout << "X ";
}
cout << endl;
}
}
int main() {
srand((unsigned)time(0));
cout << "黄绿色爆炸生物五子棋程序!" << endl;
cout << "请输入棋盘的长和宽(长和宽在5以上30以内):" << endl;
while (true) {
cin >> c >> k;
if (c <= 30 && k <= 30 && c >= 5 && k >= 5) break;
cout << "输入错误,请重新输入:" << endl;
}
int total = c * k;
for (int turn = 1; turn <= total; turn++) {
printBoard();
if (turn % 2 == 1) { // 玩家
cout << "现在轮到玩家下,请问下在哪里?(输入行和列)" << endl;
int x, y;
while (true) {
cin >> x >> y;
if (x < 1 || x > c || y < 1 || y > k) {
cout << "出界了,请重新输入:" << endl;
} else if (a[x][y] != 0) {
cout << "重叠了,请重新输入:" << endl;
} else break;
}
a[x][y] = 1;
if (checkWin(x, y, 1)) {
printBoard();
cout << "恭喜玩家胜利!" << endl;
return 0;
}
} else { // 电脑
cout << "现在轮到电脑下..." << endl;
computerMove();
bool win = false;
for (int x = 1; x <= c && !win; x++) {
for (int y = 1; y <= k && !win; y++) {
if (a[x][y] == 2 && checkWin(x, y, 2)) {
win = true;
}
}
}
if (win) {
printBoard();
cout << "恭喜电脑胜利!" << endl;
return 0;
}
}
}
printBoard();
cout << "平局!" << endl;
return 0;
}
这里空空如也






















有帮助,赞一个