diff --git a/puissance4.c b/puissance4.c index 1fca65c0b8a8f4c9fbb0fe56dfd720f307bf8fe6..8e2b82eab5662308b128877f27f96953e461bc6c 100644 --- a/puissance4.c +++ b/puissance4.c @@ -137,13 +137,12 @@ int select_random_column(int number_of_columns, int number_of_rows, int** board) int select_smart_column(int number_of_columns, int number_of_rows, int** board) { int robot_selected_column = -999; - // Check if the player can win in the next move, if so, block it + // Check if the AI can win in the next move, if so, play it for (int col = 0; col < number_of_columns; col++) { if (!is_column_full(col + 1, number_of_rows, board)) { struct coordinate temp_coordinate = find_empty_slot(col + 1, number_of_rows, board); - // Check if the player can win in the next move - board[temp_coordinate.x][temp_coordinate.y] = PLAYER1; + board[temp_coordinate.x][temp_coordinate.y] = PLAYER2; if (does_player_win(temp_coordinate.x, temp_coordinate.y, number_of_rows, number_of_columns, board)) { robot_selected_column = col + 1; board[temp_coordinate.x][temp_coordinate.y] = EMPTY; @@ -151,18 +150,20 @@ int select_smart_column(int number_of_columns, int number_of_rows, int** board) } board[temp_coordinate.x][temp_coordinate.y] = EMPTY; } + } if (robot_selected_column != -999) { return robot_selected_column; } - // Check if the AI can win in the next move, if so, play it + // Check if the player can win in the next move, if so, block it for (int col = 0; col < number_of_columns; col++) { if (!is_column_full(col + 1, number_of_rows, board)) { struct coordinate temp_coordinate = find_empty_slot(col + 1, number_of_rows, board); - board[temp_coordinate.x][temp_coordinate.y] = PLAYER2; + // Check if the player can win in the next move + board[temp_coordinate.x][temp_coordinate.y] = PLAYER1; if (does_player_win(temp_coordinate.x, temp_coordinate.y, number_of_rows, number_of_columns, board)) { robot_selected_column = col + 1; board[temp_coordinate.x][temp_coordinate.y] = EMPTY; @@ -170,7 +171,6 @@ int select_smart_column(int number_of_columns, int number_of_rows, int** board) } board[temp_coordinate.x][temp_coordinate.y] = EMPTY; } - } // If no winning move is found, select a random column @@ -252,7 +252,11 @@ bool does_player_win(int row, int col, int rows, int cols, int** board) { int current_piece = board[row][col]; for (int i = 0; i < rows - 3; i++) { - if (board[i][col] == current_piece && board[i + 1][col] == current_piece && board[i + 2][col] == current_piece && board[i + 3][col] == current_piece) { + if (board[i][col] == current_piece + && board[i + 1][col] == current_piece + && board[i + 2][col] == current_piece + && board[i + 3][col] == current_piece) + { return true; }