Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

c - Chess program to know when the Queen can capture the King

There is this problem that i have to solve

Two pieces are placed on an 8x8 chessboard: the white king and the black queen. Write a function that receives the positions of the King and Queen as input and determines if the Queen is in a position to eat the King. The positions of the two pieces are identified by the row and column on which they are located, expressed as integers between 1 and 8.

Here it's the piece of code that allows the user to insert the positions of the pawns

#include <stdio.h>
#include <stdlib.h>

typedef  struct {
int row;
int column;
}pawn;

void position(pawn *King ,pawn *Queen);

int main (){
    pawn *King = (pawn *)malloc(sizeof(pawn));
    pawn *Queen = (pawn *)malloc(sizeof(pawn));

    printf("Inserting King's data
");

    do {
        printf("Insert the row of the King
");
        scanf("%d", &King->row);
    } while (King->row < 1 || King->row > 8);

    do {
        printf("Insert the column of the King
");
        scanf("%d", &King->column);
    } while (King->column < 1 || King->column > 8);

    printf("Inserting Queen's data
");

    do {
        printf("Insert the row of the Queen
");
        scanf("%d", &Queen->row);
    } while (Queen->row < 0 || Queen->row > 7);

    do {
        printf("Insert the column of the Queen
");
        scanf("%d", &Queen->column);
    } while (Queen->column < 0 || Queen->column > 7);

    position(King, Queen);

}

With this function the program tells that the Queen can capture the King if they're on the same raw/column

void position(pawn *King ,pawn *Queen){
    if (King->raw == Queen->raw) {
        printf("The Queen can capture the King
");
    } else if (King->column == Queen->column){
        printf("The Queen can capture the King
");
    }
}

There isn't any issue with the program but I need a function which allows it to say if the Queen can capture the King if they are on the same diagonal. Could you help me?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
void position(pawn *King ,pawn *Queen){
    if (King->raw == Queen->raw) {
        printf("The Queen can capture the King
");
    } else if (King->column == Queen->column){
        printf("The Queen can capture the King
");
    } else if(abs(King->raw - Queen->raw) == abs(King->column - Queen->column)) {
        printf("The Queen can capture the King
");
    }
    # abs - an absolute module
    # should be enough for your case, you need for loops if there are othr. pawns between them.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...