-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAI.java
More file actions
64 lines (53 loc) · 1.74 KB
/
AI.java
File metadata and controls
64 lines (53 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.example.csce314ffl;
import java.util.Random;
public class AI {
private GameBoard gameBoard;
private Random random;
public AI(GameBoard gameBoard) {
this.gameBoard = gameBoard;
this.random = new Random();
}
public void playMove() {
if (!playWinningMove() && !playBlockingMove()) {
playRandomMove();
}
}
private boolean playWinningMove() {
for (int col = 0; col < gameBoard.getColumns(); col++) {
int row = findAvailableRow(col);
if (row != -1 && gameBoard.isWinningMove(row, col, Chip.AI)) {
gameBoard.dropChip(col, Chip.AI);
return true;
}
}
return false;
}
private boolean playBlockingMove() {
for (int col = 0; col < gameBoard.getColumns(); col++) {
int row = findAvailableRow(col);
if (row != -1 && gameBoard.isWinningMove(row, col, Chip.PLAYER)) {
gameBoard.dropChip(col, Chip.AI);
return true;
}
}
return false;
}
private void playRandomMove() {
int col;
do {
col = random.nextInt(gameBoard.getColumns());
} while (!isColumnPlayable(col));
gameBoard.dropChip(col, Chip.AI);
}
private boolean isColumnPlayable(int col) {
return gameBoard.getBoardChip(0, col) == Chip.EMPTY;
}
private int findAvailableRow(int col) {
for (int row = gameBoard.getRows() - 1; row >= 0; row--) {
if (gameBoard.getBoardChip(row, col) == Chip.EMPTY) {
return row;
}
}
return -1; // Column is full
}
}