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:

enum direction {
	    case up, down, left, right
	}

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:

@State var startPos : CGPoint = .zero // the start poisition of our swipe@State var isStarted = true // did the user started the swipe?@State var gameOver = false // for ending the game when the snake hits the screen borders@State var dir = direction.down // the direction the snake is going to take@State var posArray = [CGPoint(x: 0, y: 0)] // array of the snake's body positions@State var foodPos = CGPoint(x: 0, y: 0) // the position of the foodlet snakeSize : CGFloat = 10 // width and height of the snake let timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect() // to updates the snake position every 0.1 second

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:

 var body: some View {
	        ZStack {
	            Color.pink.opacity(0.3)
	            ZStack {
	                ForEach (0..<posArray.count, id: \.self) { index in
	                    Rectangle()
	                        .frame(width: self.snakeSize, height: self.snakeSize)
	                        .position(self.posArray[index])
	                }
	                Rectangle()
	                    .fill(Color.red)
	                    .frame(width: snakeSize, height: snakeSize)
	                    .position(foodPos)
	            }

	            if self.gameOver {
	                Text("Game Over")
	            }
	        }
	    }

#swiftui #swift #programming #mobile #ios

How to Create the Snake Game in SwiftUI
8.70 GEEK