奥赛罗游戏:黑白棋博弈策略
奥赛罗游戏:黑白棋博弈策略
题目描述
奥赛罗,又称黑白棋,是一款经典的策略棋盘游戏。游戏在一个 8x8 的棋盘上进行,玩家轮流放置棋子,目标是将对方棋子全部翻转为己方棋子。
游戏规则:
- 棋盘上每个格子用 (x, y) 表示,其中 1 ≤ x, y ≤ 8,且 x, y 为整数。
- 双方各执一色棋子,从黑棋开始,轮流放置一枚棋子。每放下一枚棋子叫做'一手'。
- 如果当前放置的棋子与在同一直线上的某个己方棋子之间'全部'是对方的棋子(即不能有空格),则这两个棋子之间的所有棋子的颜色均改变为本方颜色。
- 放置后,至少有一个棋子会变成本方颜色的空格可以放置。即不能将棋子放在没有'收获'的地方。
- 最初的棋盘为在 (4, 4) 和 (5, 5) 处有两枚黑棋,在 (4, 5) 和 (5, 4) 处有两枚白棋,其它位置为空。
输入格式
从标准输入读入数据。 第一行一个正整数 n(n ≤ 200),表示操作的步骤数。 接下来 n 行,每行两个数,依次为双方放置棋子的坐标,从黑棋开始。你需要判断该位置能否放置棋子。如果该位置不能放置,则不放置棋子,也不引起变化,下一行仍为该方放置的位置,直到放置成功为止。
输出格式
输出到标准输出。 输出 8 行,每行 8 个字符,表示结束时候的棋盘。 第 i 行第 j 个字符为坐标 (i, j) 位置的情况。如果该位置为黑棋,则该字符为 'B';如果为白棋,则该字符为 'W';如果为空格,则该字符为 '.'。
样例 #1
样例输入 #1
4
5 3
6 5
5 6
4 3
样例输出 #1
........
........
........
..WWW...
..BWBB..
....W...
........
........
提示
子任务
有 50% 的数据保证每次均可以放置。
写出一个正确的C++代码内容:```cpp
#include
char board[8][8];
void init() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { board[i][j] = '.'; } } board[3][3] = board[4][4] = 'B'; board[3][4] = board[4][3] = 'W'; }
bool isValid(int x, int y, char color) { if (board[x][y] != '.') { return false; } int dx[] = {0, 0, 1, -1, 1, -1, 1, -1}; int dy[] = {1, -1, 0, 0, 1, -1, -1, 1}; for (int i = 0; i < 8; i++) { int nx = x + dx[i]; int ny = y + dy[i]; while (nx >= 0 && nx < 8 && ny >= 0 && ny < 8 && board[nx][ny] != '.' && board[nx][ny] != color) { nx += dx[i]; ny += dy[i]; } if (nx >= 0 && nx < 8 && ny >= 0 && ny < 8 && board[nx][ny] == color && (nx != x + dx[i] || ny != y + dy[i])) { return true; } } return false; }
void placePiece(int x, int y, char color) { board[x][y] = color; int dx[] = {0, 0, 1, -1, 1, -1, 1, -1}; int dy[] = {1, -1, 0, 0, 1, -1, -1, 1}; for (int i = 0; i < 8; i++) { int nx = x + dx[i]; int ny = y + dy[i]; while (nx >= 0 && nx < 8 && ny >= 0 && ny < 8 && board[nx][ny] != '.' && board[nx][ny] != color) { nx += dx[i]; ny += dy[i]; } if (nx >= 0 && nx < 8 && ny >= 0 && ny < 8 && board[nx][ny] == color && (nx != x + dx[i] || ny != y + dy[i])) { while (nx != x || ny != y) { board[nx][ny] = color; nx -= dx[i]; ny -= dy[i]; } } } }
int main() { init(); int n; cin >> n; char color; int x, y; for (int i = 0; i < n; i++) { cin >> x >> y; if (i % 2 == 0) { color = 'B'; } else { color = 'W'; } if (isValid(x-1, y-1, color)) { placePiece(x-1, y-1, color); } else { i--; } } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { cout << board[i][j]; } cout << endl; } return 0; }
原文地址: https://www.cveoy.top/t/topic/qvUL 著作权归作者所有。请勿转载和采集!