Using ChatGPT for making β€˜Snake Game’ in Flutter

Photo by Lorenzo Herrera on Unsplash

Traditionally making a snake game in flutter requires quite a experience. You firstly have to learn the dart and flutter libraries, then the logical roadmap is made to make the game. But, using ChatGPT, it is done in few seconds.

For following, you have to use ChatGPT 3.5 available here (openai.com)

The prompt I used was:

The generated results were like this:

Here, ChatGPT explained the complexity of building of Snake game.

After this, the dart code generated was like below:

Packages like material, math and async is called.

As usual void main() => runApp(SnakeGame()); is written for running app. A stateless widget β€˜SnakeGame’ is made with home screen in β€˜SnakeGameScreen()’

After this, SnakeGameScreen is called as stateful widget where gridSize and cellSize both are defined as 20. A list snake has elements as 44, 43 and 42. The integer variable food stores random location in the grid. The function startGame starts the game.

Here, updateSnake() is used to update the position of snake head from left to right and down to up.

If the snake head gets larger than grid, head gets smaller than zero or snake has head, then game starts again.

i

Here the logic of snake food is done. If newHead has size equal to food, then food gets random generated value, else removeLast() is returned.

In above part, AppBar is made with title Snake Game. Then, GestureDetector() is used for sending input to make the snake move up, down, left or right.

At last, inside a Container(), width and height are set with border color black. The snake block is set green by default but if current index of snake is equal to value food, then red is set.

To run this code, I used online DartPad https://dartpad.dev

This is the result I got on Dartpad. It was fun to play. I used my mouse to move the snake in different directions.

So, here is how did it. Try it and have fun.

Follow me for more content.

--

--