前言
本游戏基于Windows系统VS2022使用C++实现;
#include <iostream>
#include <iomanip> //setw函数所需头文件
#include <cstring>
using namespace std;
const int N = 16;
char g[N][N]; // 棋盘
char player[2] = { 'X', 'O' }; // 玩家
int dx[4] = { 0, 1, 1, 1 }; // 方向数组
int dy[4] = { 1, 1, 0, -1 };
bool checkWin(int x, int y, char c) // 判断是否胜利
{
for (int i = 0; i < 4; i++) // 四个方向
{
int cnt = 1; // 连续的棋子数
int nx = x + dx[i], ny = y + dy[i]; // 下一个位置
while (nx >= 0 && nx < N && ny >= 0 && ny < N && g[nx][ny] == c) // 判断是否越界和是否连续
{
cnt++;
nx += dx[i];
ny += dy[i];
}
nx = x - dx[i], ny = y - dy[i]; // 上一个位置
while (nx >= 0 && nx < N && ny >= 0 && ny < N && g[nx][ny] == c) // 判断是否越界和是否连续
{
cnt++;
nx -= dx[i];
ny -= dy[i];
}
if (cnt >= 5) return true; // 连续的棋子数大于等于5,胜利
}
return false; // 没有胜利
}
void printBoard() // 打印棋盘
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (i == 0)
{
cout << setw(3) << j; //setw用于设置输入输出格式标准库
}
else if (j == 0)
{
cout << setw(3) << i; //设置打印字符总宽度为3
}
else
{
cout << setw(3) << g[i][j];
}
}
cout << endl;
}
}
int main()
{
memset(g, '.', sizeof(g)); // 初始化棋盘
int cur = 0; // 当前玩家
while (true)
{
printBoard(); // 打印棋盘
cout << "Player " << player[cur] << " 's turn: ";
int x, y;
cin >> x >> y;
if (g[x][y] != '.') // 判断该位置是否已经下棋
{
cout << "This position has been occupied, please choose another one." << endl;
continue;
}
g[x][y] = player[cur]; // 下棋
if (checkWin(x, y, player[cur])) // 判断胜利
{
printBoard(); // 打印棋盘
cout << "Player " << player[cur] << " wins!" << endl;
break;
}
cur = (cur + 1) % 2; // 切换玩家
}
return 0;
}