本文共 3216 字,大约阅读时间需要 10 分钟。
为了解决这个问题,我们需要模拟国际象棋棋盘上的移动和转向操作,更新棋盘的状态并输出最终结果。我们将按照以下步骤进行:
#include#include #include using namespace std;int dirs[5][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {0, 0}}; // 方向向量,索引0到4int kay(char c) { if (c == '^') return 1; if (c == '<') return 2; if (c == '>') return 4; if (c == 'v') return 3; return 0;}char key(int idx) { if (idx == 1) return '^'; if (idx == 2) return '<'; if (idx == 3) return 'v'; if (idx == 4) return '>'; return ' ';}void move(int steps, int &dir) { int dx = dirs[dir][0], dy = dirs[dir][1]; for (int i = 0; i < steps; ++i) { if (i > 0 && !check(x + dx, y + dy)) break; // 提前终止 if (!check(x, y)) break; // 超出棋盘 if (a[x][y] != '.') { int cnt = 0; while (true) { int nx = x + dx, ny = y + dy; if (!check(nx, ny)) break; if (a[nx][ny] != '.') { // 推动棋子 char t = a[nx][ny]; a[nx][ny] = a[x][y]; a[x][y] = t; x = nx; y = ny; cnt++; } else { break; } } steps -= cnt; if (steps <= 0) break; } else { x += dx; y += dy; if (!check(x, y)) break; } }}bool check(int x, int y) { return (x >= 1 && x <= 8 && y >= 1 && y <= 8);}int main() { a[1][1] = '\0'; // 初始化为非打印字符 for (int i = 1; i <= 8; ++i) { string line; do { line = string(8, ' '); getline(cin, line); } while (line.find('.') == string::npos); // 确保读入完整行 for (int j = 1; j <= 8; ++j) { a[i][j] = line[j-1]; } } int x, y, dir; bool found = false; for (int i = 1; i <= 8; ++i) { for (int j = 1; j <= 8; ++j) { if (a[i][j] == '^' || a[i][j] == '<' || a[i][j] == '>' || a[i][j] == 'v') { x = i; y = j; dir = kay(a[i][j]); found = true; break; } } if (found) break; } string s; while (true) { cin >> s; if (s == "#") break; if (s == "move") { int k; do { k = 0; string numStr; do { numStr += ' '; getline(cin, numStr); } while (numStr.find('#') == string::npos); // 确保读入完整数值 k = stoi(numStr); } while (k <= 0); move(k, dir); } else { if (s == "left") dir = (dir + 1) % 4; else if (s == "right") dir = (dir - 1 + 4) % 4; else if (s == "back") dir = (dir + 2) % 4; } } for (int i = 1; i <= 8; ++i) { for (int j = 1; j <= 8; ++j) { cout << a[i][j]; } cout << endl; }}
该方法确保了棋盘的更新和推动逻辑的正确性,处理了所有可能的转向和移动情况。
转载地址:http://wuiq.baihongyu.com/