#include <iostream>
#include <cstdlib>
#define N 10 // 棋盘尺寸 N*N
using namespace std
//棋子类型
typedef enum{
CT_NONE, CT_WHITE, CT_BLACK
}CHESS_TYPE;
CHESS_TYPE board[N][N];
CHESS_TYPE downType;
//初始化棋盘
void lnit()
{
downType = CT_BLACK;
for(int i = 0; i < N; ++ i){
for(int j = 0; j < N; ++ j){
board[i][j] = CT_NONE;
}
}
}
//判断棋子是否落在棋盘内
bool IsInBoard(int x, int y)
{
return x >= 0 && x < N && y >= 0 && y < N;
}
//定义一组方向向量
const int dx[8] = {0, 0, 1, -1, 1, -1, -1, 1};
const int dy[8] = {1, -1, 0, 0, 1, -1, 1, -1};
//判断某一方是否胜利
bool IsWin(int x0, int y0)
{
int count[8] = {0};
int x = x0, y = y0;
for(int i = 0; i < 8; ++ i){
int x = x0, y = y0;
while(true){
x += dx[i];
y += dy[i];
if(IsInBoard(x, y) && board[x][y] == board[x0][y0]){
++ count[i];
}
else{
break;
}
}
}
for(int i = 0; i < 8; i += 2){
if(count[i] + count[i + 1] >= 4){
return true;
}
}
return false;
}
//打印棋盘
void Print()
{
cout << " ";
for(int i = 0; i < N; ++ i){
cout << " " << (char)('A' + i ) ;
}
cout << endl;
for(int i = 0; i < N; ++ i){
if(i >= 9){
cout << i + 1;
}
else {
cout << i + 1 << " ";
}
for(int j = 0; j < N; ++ j){
if(board[i][j] == CT_NONE){
cout << "□";
}
if(board[i][j] == CT_WHITE){
cout << "●";
}
if(board[i][j] == CT_BLACK){
cout << "○";
}
}
cout << endl;
}
}
//游戏过程
void Process()
{
Print();
char a, b;
int k = 0;
for(int i = 0; i < N*N; ++ i){
cout << "请根据图示坐标类型,依次输入棋子的横纵坐标" << endl;
cin >> a >> b;
a -= '1';
b -= 'A';
if(!IsInBoard(a, b) || board[a][b] != CT_NONE){
cout << "ERROR" << endl;
continue;
}
board[a][b] = downType;
system("cls");
Print();
if(IsWin(a, b)){
cout << (downType == CT_WHITE ? "白棋赢" : "黑棋赢") << endl;
k ++;
break;
}
downType = (downType == CT_BLACK )? CT_WHITE : CT_BLACK;
}
if(!k){
cout << "平局" << endl;
}
}
int main()
{
lnit();
Process();
return 0;
}
下面是这个程序的运行结果:
首先,再输入棋子之前,程序会弹出一个空白的棋盘,注意,一定要根据棋盘周围所标注的横纵坐标来确定落子的位置。