gpt4 book ai didi

C++ - 国际象棋主教 MoveCode 错误?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:39 24 4
gpt4 key购买 nike

所以我正在制作国际象棋游戏,但是我无法让象棋正确移动。

这是我的棋盘:

string board[8][8] = {

{"_" , "_", "_" , "_" ,"_", "_" , "_" , "_"},
{"_" , "_", "_" , "_" ,"_", "_" , "_" , "_"},
{"_" , "_", "_" , "_" ,"_", "B" , "_" , "_"},
{"_" , "_", "_" , "_" ,"_", "_" , "_" , "_"},
{"_" , "_", "_" , "_" ,"_", "_" , "_" , "_"},
{"_" , "_", "_" , "_" ,"_", "_" , "_" , "_"},
{"_" , "_", "_" , "_" ,"_", "_" , "_" , "_"},
{"_" , "_", "_" , "_" ,"_", "_" , "_" , "_"} };

这里是画板的Draw函数。

void Draw()
{
for( int i = 0; i < 8; i++ )
{
for( int j = 0; j < 8; j++ )
std::cout << board[ i ][ j ] << ' ';

std::cout << '\n';
}
cout<<"\n";
}

到目前为止的主教运动代码。

 if (board[x][y] == "B")
{ //Highlight the users chosen piece
board[x][y] = "\033[0;31mB\033[0m";
//Now showing available moves the chosen bishop can move to
for(int counter=1; counter <=7; counter++) {
if(board[x+counter][y+counter] == "_") { //if there is an empty space, then place X to show peice can move there
board[x+counter][y+counter] = "X";
}
else { //if cannot move their ,then break
break;
}
}
}

这是我的问题。它在棋盘上的某些位置向用户显示棋子能够移动到的 X 空间。然而,当棋子位于数组的某些位置时,比如它在棋盘代码中的位置。它重叠并在板的不同侧显示 X,而不是在没有可用的“_”时停止绘制 X。

最佳答案

您需要检查 x + countery + counter 是否落在棋盘内。

if (board[x][y] == "B")
{ //Highlight the users chosen piece
board[x][y] = "\033[0;31mB\033[0m";
//Now showing available moves the chosen bishop can move to
for(int counter = 1; (x + counter) <= 7 && (y + counter) <= 7; counter++){
if(board[x + counter][y + counter] == "_") {
//if there is an empty space, then place X to show peice can move there
board[x + counter][y + counter] = "X";
}
else { //if cannot move their ,then break
break;
}
}
}

当然,这只是一个方向的标记,而主教实际上可以向四个方向移动。

此外,这不会检查路径之间是否有任何片段。

要考虑所有四个方向,您可以创建一个方向矩阵,其中存储每个方向的 x 和 y 变化。

// 4 directions in which bishop can move
int dx[4] = {-1, -1, 1, 1};
int dy[4] = {-1, 1, -1, 1};


if (board[x][y] == "B")
{
// for each direction
for(int dir = 0; dir < 4; dir++) {

// the bishop can move to a maximum of 7 squares
for(int counter = 1; counter < 8; counter++) {

// calculate where the bishop will be
// after moving "counter" number of squares
int new_x, new_y;
new_x = x + dx[dir] * counter;
new_y = y + dy[dir] * counter;

// check if the square lies within the board
if(new_x >= 0 && new_x < 8 && new_y >= 0 && new_y < 8) {

// if there is an empty space, then place X to show peice can move there
if(board[cur_x][cur_y] == "_") {
board[cur_x][cur_y] = "X";
}

// if there is any other piece in between, the bishop can't move further
else {
break;
}
}

// break if the square is outside the board
else {
break;
}
}
}
}

关于C++ - 国际象棋主教 MoveCode 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41636093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com