// Connect 4 #include #define NUM_ROWS 6 #define NUM_COLS 7 enum cell_state { EMPTY, RED, YELLOW }; void print_gameboard(enum cell_state gameboard[NUM_ROWS][NUM_COLS]) { // clears the terminal printf("\e[1;1H\e[2J"); int i = 0; while (i < NUM_ROWS) { int j = 0; while (j < NUM_COLS) { printf("%d ", gameboard[i][j]); j++; } printf("\n"); i++; } } int read_player_input() { int input; printf("\nWhich column do you want to place your piece?\n"); printf("Enter the column (1-7): "); scanf("%d", &input); input--; while (input < 0 || input >= NUM_COLS) { printf("Invalid column. Enter the column (1-7): "); scanf("%d", &input); input--; } return input; } int check_horizontal(enum cell_state gameboard[NUM_ROWS][NUM_COLS]) { for (int row = 0; row < NUM_ROWS; row++) { for (int col = 0; col < NUM_COLS - 3; col++) { if (gameboard[row][col] == RED && gameboard[row][col + 1] == RED && gameboard[row][col + 2] == RED && gameboard[row][col + 3] == RED) { return 1; } } } return 0; } int check_diagonal_from_bottom_left( enum cell_state gameboard[NUM_ROWS][NUM_COLS]) { for (int row = 3; row < NUM_ROWS; row++) { for (int col = 0; col < NUM_COLS - 3; col++) { if (gameboard[row][col] == RED && gameboard[row - 1][col + 1] == RED && gameboard[row - 2][col + 2] == RED && gameboard[row - 3][col + 3] == RED) { return 1; } } } return 0; } int check_diagonal_from_top_left( enum cell_state gameboard[NUM_ROWS][NUM_COLS]) { for (int row = 0; row < NUM_ROWS - 3; row++) { for (int col = 0; col < NUM_COLS - 3; col++) { if (gameboard[row][col] == RED && gameboard[row + 1][col + 1] == RED && gameboard[row + 2][col + 2] == RED && gameboard[row + 3][col + 3] == RED) { return 1; } } } return 0; } int check_vertical(enum cell_state gameboard[NUM_ROWS][NUM_COLS]) { for (int col = 0; col < NUM_COLS; col++) { for (int row = 0; row < NUM_ROWS - 3; row++) { if (gameboard[row][col] == RED && gameboard[row + 1][col] == RED && gameboard[row + 2][col] == RED && gameboard[row + 3][col] == RED) { return 1; } } } return 0; } int check_for_win(enum cell_state gameboard[NUM_ROWS][NUM_COLS]) { return check_horizontal(gameboard) || check_vertical(gameboard) || check_diagonal_from_top_left(gameboard) || check_diagonal_from_bottom_left(gameboard); } int main(void) { enum cell_state gameboard[NUM_ROWS][NUM_COLS] = {}; int p_1_pos; while (1) { p_1_pos = read_player_input(); // check if piece can go into column int row_to_check = NUM_ROWS - 1; while (row_to_check >= 0 && gameboard[row_to_check][p_1_pos] != EMPTY) { row_to_check--; } if (row_to_check < 0) { // here, we have no position to printf("That's an invalid placement\n"); } else { // placing the piece gameboard[row_to_check][p_1_pos] = RED; } print_gameboard(gameboard); // checking for a win... if (check_for_win(gameboard)) { printf("Win detected!\n"); } else { printf("Still no win\n"); } } return 0; }