设计一个象棋游戏非常复杂,我们需要考虑很多方面,例如和棋、将军、将军解除等规则。这里提供一个简化版的象棋游戏框架,玩家可以根据提示输入棋子的当前位置和目标位置,游戏将检查移动是否合法然后执行。
#include <stdio.h>
#include <stdbool.h>
void print_board(int board[][9]);
int check_move(int src_x, int src_y, int dest_x, int dest_y, int board[][9]);
void update_board(int src_x, int src_y, int dest_x, int dest_y, int board[][9], int player);
bool can_move(int x1, int y1, int x2, int y2, int board[][9]);
bool in_bounds(int x, int y);
int main() {
// 这是简化版的象棋棋盘
int board[10][9] = {
{1, 2, 3, 4, 5, 4, 3, 2, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 6, 0, 0, 0, 0, 0, 6, 0},
{7, 0, 7, 0, 7, 0, 7, 0, 7},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{7, 0, 7, 0, 7, 0, 7, 0, 7},
{0, 6, 0, 0, 0, 0, 0, 6, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 2, 3, 4, 5, 4, 3, 2, 1},
};
int current_player = 0;
int source_x, source_y, dest_x, dest_y;
while (1) {
print_board(board);
printf("Player %d's turn. Enter the source and destination coordinates (x1 y1 x2 y2): ", current_player + 1);
scanf("%d %d %d %d", &source_x, &source_y, &dest_x, &dest_y);
if (check_move(source_x, source_y, dest_x, dest_y, board) == current_player) {
update_board(source_x, source_y, dest_x, dest_y, board, current_player);
current_player = 1 - current_player;
} else {
printf("Invalid move! Try again.\n");
}
}
return 0;
}
void print_board(int board[][9]) {
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 9; ++j) {
printf("%d ", board[i][j]);
}
printf("\n");
}
}
int check_move(int src_x, int src_y, int dest_x, int dest_y, int board[][9]) {
int src_piece = board[src_y][src_x];
int dest_piece = board[dest_y][dest_x];
if ((src_piece >= 1 && src_piece <= 7) && (dest_piece == 0 || (dest_piece >= 1 && dest_piece <= 7))) {
if (can_move(src_x, src_y, dest_x, dest_y, board)) {
return 0;
}
}
else if ((src_piece >= 8 && src_piece <= 14) && (dest_piece == 0 || (dest_piece >= 8 && dest_piece <= 14))) {
if (can_move(src_x, src_y, dest_x, dest_y, board)) {
return 1;
}
}
return -1;
}
// 这里可以添加各个棋子的合法移动规则
bool can_move(int x1, int y1, int x2, int y2, int board[][9]) {
if (!in_bounds(x1, y1) || !in_bounds(x2, y2)) {
return false;
}
int dx = x2 - x1;
int dy = y2 - y1;
if (board[y1][x1] == 1 || board[y1][x1] == 7) {
if (dx == 0 || dy == 0) {
return true;
}
}
return false;
}
bool in_bounds(int x, int y) {
return x >= 0 && x < 9 && y >= 0 && y < 10;
}
void update_board(int src_x, int src_y, int dest_x, int dest_y, int board[][9], int player) {
int src_piece = board[src_y][src_x];
board[src_y][src_x] = 0;
board[dest_y][dest_x] = src_piece;
}
这个程序仅作为起点,你可以在此基础上对 can_move 的判断进行扩展以实现更多的规则。实际上,这个框架可以用于任何其他类似的棋类游戏,只要在 can_move 函数中有效地定义每个棋子的移动规则。