In: Computer Science
C Programming Language.
A chessboard consists of 8 squares x 8 squares for a total of 64 squares. The squares of the chessboard are identified, from the perspective of the player with the white pieces, by the letters a – h for the 8 columns or files (starting from that player’s left), and 1 – 8 for the 8 rows or ranks (starting closest to that player). One of the chess pieces, the knight, can move in any direction by moving 2 rows up or down and 1 column left or right, or by moving 1 row up or down and 2 columns left or right. The knight can jump over pieces with the only restrictions being that the knight can’t move off the board and the knight can’t move to a square already occupied by a piece of the same color. Assume no other pieces on the board will be captured by, or block the movement of, the knight. Write a C language function that reads in a two character file and rank location (e.g., a5, g6, etc.). The function will then compute and display all the different squares by two character file and rank location to identify where the knight could move. You may use multiple functions, rather than only one, if you prefer.
Include a commented listing with your report.
Hi,
The code below will help you find all possible knight moves from a given postion on the chess board.
#include <stdio.h>
//Function to see if move is valid or not
void moves(char ch, int rank, int m,int n)
{
// Position of knight after move
int x = ch + m;
int y = rank + n;
//Condition check
if (x>=97 && x <=103 && y >=1 && y <=8)
printf("%c%d\n", x,y);
}
int main()
{
char string[] = "e4";
char ch = string[0];
int rank = string[1] - 48;
//All possibilities
int X[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int Y[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
// Check if each possible move is valid or not
for (int i = 0; i < 8; i++)
{
moves(ch,rank,X[i],Y[i]);
}
}
Here, we taking the input string and breaking it into the character and the integer part. The -48 is to convert ASCII value to integer value. X[] and Y[] indicate all possible move sets from any position for a knight piece. As there are 8 possible sets we run a loop which runs 8 times and calls the function moves() with a set of values each time.
The function moves(), takes in the char, rank and also possible moves in x and y direction as arguments. We then calculate the next position of the knight by adding the x and y values. If the x value is in [a,g] and y value is in [1,8] the new position is valid and we print it.
Output for pos = "e4":
Reference:
Hope the code helps you. The question was really fun to solve :)
Thanks and All the Best :D