// 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]) { 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("Which column do you want to place your piece?\n"); printf("Enter the column (1-7): "); scanf("%d", &input); input--; while (input < 0 || input > NUM_ROWS) { printf("Which column do you want to place your piece?\n"); printf("Enter the column (1-7): "); scanf("%d", &input); input--; } return input; } int is_valid_position(int row, int col) { return (row >= 0) && (row < NUM_ROWS) && (col >= 0) && (col < NUM_COLS); } int check_for_win(enum cell_state gameboard[NUM_ROWS][NUM_COLS]) { int cons_pieces = 0; int row = 0; while (row < NUM_ROWS) { int col = 0; while (col < NUM_COLS) { // gameboard[row][col] is each element... if (gameboard[row][col] == RED) { // found a RED piece, now check for a win // first, check across horizontally int k = col; while (k < col + 4) { if (is_valid_position(row, k) && gameboard[row][k] != RED) { cons_pieces++; if (cons_pieces == 4) { return 1; } } k++; } cons_pieces = 0; k = row; while (k < row + 4) { if (is_valid_position(k, col) && gameboard[k][col] != RED) { cons_pieces++; if (cons_pieces == 4) { return 1; } } k++; } } col++; } row++; } return 0; } 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; } // checking for a win... if (check_for_win(gameboard)) { printf("OMG you won (and our code works?)\n"); } else { printf("Still no win\n"); } print_gameboard(gameboard); } return 0; }