...
/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.
We'll cover the following...
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:
Randomly choose who to start, the user or the computer.
If the choice is the computer:
Play the first move.
Set the current player to the user.
Update the game state.
If the choice is the user:
Update the game state.
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 indart: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. ...