这个题的思路也比较清晰,依然花了1个小时才把代码写出来,好在bug不多
//Othello
#include<iostream>
#include<cstring>
using namespace std;
char b[10][10];
int check(char type,int x,int y);
char* move(int dir, int num,int x,int y);
void M(char type, int x, int y);
int count(char type);
char* move(int dir, int num,int x,int y)
{
if (dir == 1)return &b[x + num][y];
else if (dir == 2)return &b[x + num][y + num];
else if (dir == 3)return &b[x][y + num];
else if (dir == 4)return &b[x - num][y + num];
else if (dir == 5)return &b[x - num][y];
else if (dir == 6)return &b[x - num][y - num];
else if (dir == 7)return &b[x][y - num];
else if (dir == 8)return &b[x + num][y - num];
}
int check(char type,int x,int y)
{
int c_b = 0;
for (int i = 1; i < 9; i++)
{
if (*move(i, 1, x, y) != type && *move(i, 1, x, y) != '-')
{
for (int j = 2; x + j < 9 && x - j>0 && y + j < 9 && y - j>0; j++)
{
if (*move(i, j, x, y) == '-')break;
if (*move(i, j, x, y) == type)c_b = 1;
}
}
}
return c_b;
}
void M(char type, int x, int y)
{
b[x][y] = type;
for (int i = 1; i < 9; i++)
{
int che = 0;
if (*move(i, 1, x, y) != type && *move(i, 1, x, y) != '-')
{
for (int j = 2; x + j < 9 && x - j>0 && y + j < 9 && y - j>0; j++)
{
if (*move(i, j, x, y) == '-')break;
if (*move(i, j, x, y) == type)che = 1;
}
}
if (che)
{
for (int j = 1; *move(i, j, x, y) != type; j++)
*move(i, j, x, y) = type;
}
}
}
int count(char type)
{
int n = 0;
for (int i = 1; i < 9; i++)
{
for (int j = 1; j < 9; j++)
if (b[i][j] == type)n++;
}
return n;
}
int main()
{
int round;
cin >> round;
while (round--)
{
memset(b, 0, sizeof(b));
for (int i = 1; i < 9; i++)
{
for (int j = 1; j < 9; j++)
cin >> b[i][j];
}
char type;
cin >> type;
char cmd;
while (cin >> cmd&&cmd != 'Q')
{
if (cmd == 'L')
{
int l = 0;
for (int i = 1; i < 9; i++)
{
for (int j = 1; j < 9; j++)
{
l += check(type, i, j);
if (check(type, i, j))
cout << "(" << i << "," << j << ") ";
}
}
if (!l)
{
cout << "No legal move." << endl;
type = type == 'B' ? 'M' : 'B';
}
}
else if (cmd == 'M')
{
int x, y;
cin >> x >> y;
M(type, x, y);
cout << "Black - " << count('B') << " White - " << count('W') << endl;
type = type == 'B' ? 'M' : 'B';
}
}
if (cmd == 'Q')
{
for (int i = 1; i < 9; i++)
{
for (int j = 1; j < 9; j++)
cout << b[i][j];
cout << endl;
}
}
}
}
简化代码的一个重要方法是定义了一个move()函数,这个函数把8个方向用1到8表示,返回棋盘指针,用于check()函数的检测和M()函数的修改。
细节方面就是注意棋盘边界和当前棋子颜色的改变(当M操作一次或L报告No legal move时改变)