这道题按照题目描述的三种指令来模拟即可。
Q–退出并打印当前棋盘,L–先明确当前是黑棋还是白旗的回合,然后搜索棋盘的每个位置看是否可以放,M–先检查当前回合是否有合法位置,如果没有切换双方回合然后放置,放置后修改棋盘和棋子数目。
注意输出格式,特别是’Black - xx White - yy’,是%2d格式。
代码如下:
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
char a[10][10];
bool turn; //0--white turn 1--black turn
typedef struct{
int x;
int y;
}Node;
vector list;
int bnum,wnum;//black piece num and white piece num
int dirx[] = { -1, 1, 0, 0, -1, -1, 1, 1 }, diry[] = {0,0,-1,1,-1,1,-1,1};
bool inxy(int x, int y){
if (x<1 || x>8 || y<1 || y>8)
return false;
return true;
}
void print(){
for (int i = 1; i < 9; i++){
for (int j = 1; j < 9; j++){
cout << a[i][j];
}
cout << endl;
}
}
bool check(int x,int y){
if (a[x][y] != '-')
return false;
char c,t;//c represents the current play, t represents the other
if (turn){
c = 'B';
t = 'W';
}
else{
c = 'W';
t = 'B';
}
for (int i = 0; i < 8; i++){//8 direct
int dx = x + dirx[i];
int dy = y + diry[i];
if (!inxy(dx, dy)||a[dx][dy]!=t)
continue;
while (inxy(dx,dy)&&a[dx][dy] == t){
dx += dirx[i];
dy += diry[i];
}
if (inxy(dx, dy) && a[dx][dy] == c)
return true;
}
return false;
}
void place(int x, int y){//place a piece
char c, t;//c represents the current play, t represents the other
if (turn){
c = 'B';
t = 'W';
}
else{
c = 'W';
t = 'B';
}
a[x][y] = c;
if (turn)
bnum++;
else
wnum++;
for (int i = 0; i < 8; i++){//8 direct
int dx = x + dirx[i];
int dy = y + diry[i];
if (!inxy(dx, dy) || a[dx][dy] != t)
continue;
while (a[dx][dy] == t){
dx += dirx[i];
dy += diry[i];
}
if (a[dx][dy] == c){
dx -= dirx[i];
dy -= diry[i];
while (inxy(dx, dy) && a[dx][dy] == t){
a[dx][dy] = c;
if (turn){
bnum++;
wnum--;
}
else{
wnum++;
bnum--;
}
dx -= dirx[i];
dy -= diry[i];
}
}
}
printf("Black - %2d White - %2d\n", bnum, wnum);
}
int main()
{
int T;
cin >> T;
int i = 0;
while (iif (i>1)
cout << endl;
//every game
bnum = 0;
wnum = 0;
for (int i = 1; i < 9; i++){
for (int j = 1; j < 9; j++){
cin >> a[i][j];
if (a[i][j] == 'B')
bnum++;
else if (a[i][j] == 'W')
wnum++;
}
}
char c;
cin >> c;
if (c == 'W')
turn = false;
else
turn = true;
while (true){
char ord[10];
cin >> ord;
if (ord[0] == 'Q'){//quit
print();
break;
}
else if (ord[0] == 'L'){
list.clear();
for (int i = 1; i < 9; i++){
for (int j = 1; j < 9; j++){
if (check(i, j)){
Node x = { i, j };
list.push_back(x);
}
}
}
if (list.size()==0)
cout << "No legal move.";
else{
cout << "(" << list[0].x << "," << list[0].y << ")";
for (int j = 1; j < list.size(); j++){
cout << " (" << list[j].x << "," << list[j].y << ")";
}
}
cout << endl;
}
else if (ord[0] == 'M'){
int x = ord[1] - '0';
int y = ord[2] - '0';
bool find = false;
for (int i = 1; i < 9; i++){
for (int j = 1; j < 9; j++){
if (check(i, j)){
find = true;
break;
}
}
}
if (!find)
turn = !turn;
place(x, y);
turn = !turn;
}
}
}
return 0;
}