AI improvements

This commit is contained in:
Malte Tammena 2017-10-20 17:38:32 +02:00
parent 7f83c6f01f
commit dbc2d5b2d8

View file

@ -6,6 +6,7 @@ import java.util.HashSet;
import java.util.Arrays;
import player.Player;
import game.Game;
/**
* Maltes artificial intelligence for playing a game of Connect Four
@ -64,14 +65,21 @@ public class MalteAI implements Player{
}
// Get options which would lead to instant win.
Set<Integer> winningOptions = getRowCompletionOptions(options, board, id);
System.out.println("WINNING: " + winningOptions);
for (Integer i: winningOptions) {
return i.intValue();
}
// Get options which would prevent an instant win of the enemy.
enemyID = enemyID == 0 ? 1: enemyID;
Set<Integer> preventionsOptions = getRowCompletionOptions(options, board, enemyID);
System.out.println("PREVENT: " + preventionsOptions);
for (Integer i: preventionsOptions) {
// Only accept options, that would not cause a winning opportunity for the enemy.
return i.intValue();
}
Set<Integer> choosewisely = new HashSet<>(options);
while (choosewisely.size() > 0){
Integer i = takeRandom(choosewisely);
choosewisely.remove(i);
int[][] fakeBoard = makeMove(copyBoard(board), i, id);
if (getRowCompletionOptions(options, fakeBoard, enemyID).size() == 0) {
return i.intValue();
@ -109,17 +117,17 @@ public class MalteAI implements Player{
* @return The modified board.
*/
private int[][] makeMove(int[][] board, int choice, int id) {
int column = 0;
int row = 0;
// If the column is full, do nothing.
if (board[choice][column] != 0) {
if (board[choice][row] != 0) {
return board;
}
// Find the last empty row.
while (board[choice][column + 1] == 0) {
column++;
while (row < Game.GAME_ROWS - 1 && board[choice][row + 1] == 0) {
row++;
}
// Add the players piece.
board[choice][column] = id;
board[choice][row] = id;
return board;
}