The Snake is moving now, its animating, but we have a few problems.
- There is no way for the user to control the direction of the Snake.
- The length of the Snake is fixed.
- The Snake moves out of the bounds of the screen or what we call “the play area”.
- The game does not end anyway unless you restart the app manually.
In this episode, you are going to address the first problem. You are going to use the provided ControlPanel widget to control the direction of movement of the Snake.
Let’s begin.
The ControlPanel widget is provided as part of the starter project inside the control_panel.dart file. To use the ControlPanel widget, you will implement the getControls method. Here is how it should look like.
Widget getControls() {
return ControlPanel(
onTapped: (Direction newDirection) {
direction = newDirection;
},
);
}
You may have to import the ControlPanel widget from control_panel.dart file if you get an error.
Here, we are simply returning the ControlPanel widget. The onTapped function of the widget is executed everytime the user taps on a button to change the direction of the Snake. All we do, is update the direction variable, which we know controls the direction of the Snake’s movement, with the new value of the direction received from the user.
The last step of this process is to add the getControls method to the build method. This is important for Flutter to render the ControlPanel widget on the screen for user interaction.
Change the build method.
@override
Widget build(BuildContext context) {
...
return Scaffold(
body: Container(
color: Color(0XFFF5BB00),
child: Stack(
// Change this
children: [
...getPieces(),
getControls()
],
),
),
);
}
In the above code, we are simply adding all the Piece widgets and the ControlPanel widget, returned by getControls method, as children of the Stack. So they all can overlap each other, ControlPanel widget always being on the top, since it is specified later in the list of children.
Save the files and restart the app. You should see 4 buttons on the screen that allow you to control the direction of the Snake. When you tap a button, the Snake starts moving in the direction specified by the button.
Isn’t this amazing?
The length of the Snake is still fixed to 5. Wouldn’t it be more amazing to have a longer Snake? Let’s do that in the next episode.