Create a 2D chess game - Tech Info
Create a 2D chess game - Tech Info
#include <stdio.h>
int main() {
char board[8][8] = {
{'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'},
{'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
{' ', '.', ' ', '.', ' ', '.', ' ', '.'},
{'.', ' ', '.', ' ', '.', ' ', '.', ' '},
{' ', '.', ' ', '.', ' ', '.', ' ', '.'},
{'.', ' ', '.', ' ', '.', ' ', '.', ' '},
{'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'},
{'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'}
};
int player = 1;
int row1, col1, row2, col2;
printf("Welcome to Chess!\n");
while (1) {
// Print the board
printf("\n A B C D E F G H\n");
for (int i = 0; i < 8; i++) {
printf("%d ", i + 1);
for (int j = 0; j < 8; j++) {
printf("%c ", board[i][j]);
}
printf("%d", i + 1);
printf("\n");
}
printf(" A B C D E F G H\n");
// Get the player's move
printf("\nPlayer %d's turn.\n", player);
printf("Enter the row and column of the piece you want to move: ");
scanf("%d %d", &row1, &col1);
printf("Enter the row and column of the destination: ");
scanf("%d %d", &row2, &col2);
// Move the piece
if (board[row1 - 1][col1 - 1] == ' ') {
printf("There is no piece at that location.\n");
} else if (player == 1 && board[row1 - 1][col1 - 1] >= 'a' && board[row1 - 1][col1 - 1] <= 'z') {
printf("You cannot move your opponent's piece.\n");
} else if (player == 2 && board[row1 - 1][col1 - 1] >= 'A' && board[row1 - 1][col1 - 1] <= 'Z') {
printf("You cannot move your opponent's piece.\n");
} else {
board[row2 - 1][col2 - 1] = board[row1 - 1][col1 - 1];
board[row1 - 1][col1 - 1] = ' ';
}
// Switch players
player = player == 1 ? 2 : 1;
}
return 0;
}
Comments
Post a Comment