...

/

Solution: Build a Tic-Tac-Toe Game using Flutter BLoC

Solution: Build a Tic-Tac-Toe Game using Flutter BLoC

View the solution of the tic-tac-toe exercise built with Flutter BLoC.

The tic-tac-toe game is a great way to test what you learned about Flutter BLoC in this course. Now, let’s see a possible solution to the challenge.

Implementing GameCubit

The first Cubit we have to implement is the GameCubit located in lib/cubits/game_cubit/game_cubit.dart. This is the Cubit that handles all the game states.

The startGame() function

In the startGame() function, our goal is to do the following:

  1. Randomly choose who to start, the user or the computer.

  2. If the choice is the computer:

    1. Play the first move.

    2. Set the current player to the user.

    3. Update the game state.

  3. If the choice is the user:

    1. Update the game state.

Press + to interact
void startGame() {
Players player = Random().nextBool() ? Players.USER : Players.COMPUTER;
if (player == Players.COMPUTER) {
List<TileOptions> updatedTiles =
_gameService.playAsComputer(List.filled(9, TileOptions.EMPTY));
emit(
GameInProgress(
tiles: updatedTiles,
player: Players.USER,
),
);
} else {
emit(
GameInProgress(
tiles: List.generate(9, (index) => TileOptions.EMPTY),
player: Players.USER,
),
);
}
}
  • Line 2: The Random() method provided in dart:math is used to choose a random player.

  • Lines 5 and 6: In case of the random player is set to be the computer, the playAsComputer() function provided in _gameService is used to play the computer’s move. The function returns the new tiles after the computer’s move.

  • Lines 7–12: The GameInProgress state is emitted with the updated tiles after the computer plays and the player is set to the user.

  • Lines 14–19: In case of the random player is set to be the user, the GameInProgress state is emitted with an empty board, and the player is set to be the user. ...