Categories
SwiftUI

How to Create the Snake Game in SwiftUI

Create the classic snake game in SwiftUI without a grid

snake game swiftui, swift
Snake Game in SwiftUI

Enum and Variables

We are going to detect the swipe direction and have the snake move in that direction constantly until the direction changes. Let’s first create an enum for the directions:

We will have a timer to control the snake’s speed. To make the snake slower or faster, we can change the timer’s intervals. The snake size is used instead of a grid. It will help us control the position of the snake and its food. We will need the following variables in our game:


Snake View Elements

Inside our body, add a ZStack. Inside of that, you can add color for your background. We are going to need another ZStack for our snake rectangle and the food rectangle. To create the snake body, we are going to iterate the array that holds the snake body position. Give both rectangles the width and height of our snakeSize variable. The last element inside our view is a text view that appears when our gameOver variable is toggled on:


Functions

Create a function that determines the position of our rectangles. To position the snake and food in an invisible grid, we need to utilize the snake size to find how many rows and columns we can have inside our view:

To one of our ZStacks, we can add .onAppear to set the position for our snake and food using the function we created above:

Create a function that checks whether the snake is inside or outside the screen borders, checks the direction of the user’s swipe, and then moves the snake in that direction:

We can determine which direction the user has swiped in with the following code that uses the DragGesture to get the start and end positions of the swipe and then calculates the differences between the x-coordinates and y-coordinates to determine the swipe direction. Add the following function to our first ZStack:

All we need to add to our ZStack to finish up the game is a .onReceieve function that takes our timer and updates the snake and food’s positions. When the snake is on top of the food, append a new position to our array of snake body positions to make the snake longer:

snake game ios development, swiftui, swift
Snake Game in SwiftUI

All done! Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *