Since the user can specify the size of your playing board, you need to create a matrix dynamically:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, j, size;
char **board;
printf("Enter the board size: ");
if (scanf("%d", &size) != 1) {
fprintf(stderr, "Invalid input\n");
return EXIT_FAILURE;
}
/* Create the board dynamically */
board = malloc(size * sizeof *board);
/* Always test for failure */
if (board == NULL) {
fprintf(stderr, "Memory allocation failure\n");
return EXIT_FAILURE;
}
for (i = 0; i < size; i++) {
board[i] = malloc(size * sizeof *board[i]);
if (board[i] == NULL) {
fprintf(stderr, "Memory allocation failure\n");
/* Walk back and release the memory already allocated */
while (--i >= 0)
free(board[i]);
free(board);
return EXIT_FAILURE;
}
}
/* Initialize the board */
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++)
board[i][j] = '\0';
}
/* Release the memory allocated */
for (i = 0; i < size; i++)
free(board[i]);
free(board);
return EXIT_SUCCESS;
} This code doesn't do anything except take a size from standard input, build a matrix dynamically, initialize it to null characters, and destroy the matrix. Since each element is a char, you can put either an X or an O in it. To actually plot the moves, consider numbering each cell and letting the user choose which one to add the move to:
#include <stdio.h>
#include <stdlib.h>
void show_board(char **board, int size);
int main(void)
{
int i, j, size;
char **board;
printf("Enter the board size: ");
if (scanf("%d", &size) != 1) {
fprintf(stderr, "Invalid input\n");
return EXIT_FAILURE;
}
/* Create the board dynamically */
board = malloc(size * sizeof *board);
/* Always test for failure */
if (board == NULL) {
fprintf(stderr, "Memory allocation failure\n");
return EXIT_FAILURE;
}
for (i = 0; i < size; i++) {
board[i] = malloc(size * sizeof *board[i]);
if (board[i] == NULL) {
fprintf(stderr, "Memory allocation failure\n");
/* Walk back and release the memory already allocated */
while (--i >= 0)
free(board[i]);
free(board);
return EXIT_FAILURE;
}
}
/* Initialize the board */
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++)
board[i][j] = '\0';
}
/* Print the board */
show_board(board, size);
/* Release the memory allocated */
for (i = 0; i < size; i++)
free(board[i]);
free(board);
return EXIT_SUCCESS;
}
void show_board(char **board, int size)
{
int i, j, k = 1;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
if (board[i][j] == '\0')
printf("%3d", k++);
else
printf("%3c", board[i][j]);
}
printf("\n");
}
} When it comes to making sure that a cell isn't already taken, you only need to use a conditional statement:
char player_marker = 'X'; /* For example */
if (board[i][j] != '\0')
fprintf(stderr, "Cell already taken\n");
else
board[i][j] = player_marker; Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401