How to Create a 2D Snake Game in Flutter

Jan 17 2023 Dart 2.17, Flutter 3.0, Android Studio or VS Code

Part 1: How to Create a 2D Snake Game in Flutter

4. Create Piece Positions

Episode complete

Play next episode

Next
Save for later
About this episode
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 3. Understanding the Starter Project Next episode: 5. Move the Pieces to Next Position

This video Create Piece Positions was last updated on Jan 17 2023

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

In this video, you will be displaying the Piece widget at a random position on the screen within the play area. To do this, first you will be generating a random position on the screen within the bounds of the play area and then render a Piece at the generated position.

draw() {
    if(positions.length == 0) {
        
    }
}
draw() {
    if(positions.length == 0) {
        positions.add(getRandomPositionWithinRange()); //add this
    }
}
getPieces() {
    List<Piece> pieces = [];
}
getPieces() {
    List<Piece> pieces = [];
    draw(); // Add this
}
getPieces() {
    List<Piece> pieces = [];
    draw();

    // Add this
    for(int i = 0; i < positions.length; i++) { 
        Piece p = Piece(
            posX: positions[i].dx.toInt(),
            posY: positions[i].dy.toInt(),
            size: step,
            color: Colors.red,
        );
    }
}
getPieces() {
    List<Piece> pieces = [];
    draw();

    for(int i = 0; i < positions.length; i++) {
        Piece p = Piece(
            posX: positions[i].dx.toInt(),
            posY: positions[i].dy.toInt(),
            size: step,
            color: Colors.red,
        );

        pieces.add(p); // Add this
    }

    return pieces; // Add this
}
@override
Widget build(BuildContext context) {
    ...
    return Scaffold(
      body: Container(
        color: Color(0XFFF5BB00),
        child: Stack(
          children: [],
        ),
      ),
    );
  }
}
@override
Widget build(BuildContext context) {
    ...
    return Scaffold(
      body: Container(
        color: Color(0XFFF5BB00),
        child: Stack(
          children: getPieces(),
        ),
      ),
    );
  }
}