Making Your Move

Selecting which move to make next is a matter of looking at all the possible moves and evaluating each position. Then we go with the choice that gives the lowest score. (Remember, low means good for the computer.)

Picking the Right Move

Here’s the code to add to GameFragment.java to pick the next move:

ticTacToev3/src/main/java/org/example/tictactoe/GameFragment.java
 
private​ ​void​ pickMove(​int​ move​[]​) {
 
Tile.Owner opponent = mPlayer == Tile.Owner.X ? Tile.Owner.O : Tile
 
.Owner.X;
 
int​ bestLarge = -1;
 
int​ bestSmall = -1;
 
int​ bestValue = ​Integer​.MAX_VALUE;
 
for​ (​int​ large = 0; large < 9; large++) {
 
for​ (​int​ small = 0; small < 9; small++) {
 
Tile smallTile = mSmallTiles[large][small];
 
if​ (isAvailable(smallTile)) ...

Get Hello, Android, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.