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

04. Create Piece Positions

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 03. Understanding the Starter Project Next episode: 05. Move the Pieces to Next Position

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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(),
        ),
      ),
    );
  }
}