Better Programming

Advice for programmers.

Member-only story

Build a Snake Game in SwiftUI Using GeometryReader

Mark Lucking
Better Programming
Published in
5 min readFeb 9, 2022

--

Photo by Riho Kroll on Unsplash

Although I am reasonably sure Confucius, who was around in 450BC, wasn’t a programmer, some advice he had about learning things couldn’t have been more true when it comes to coding.

Tell Me and I Will Forget;
Show Me and I May Remember;
Involve Me and I Will Understand.

So join me in this article to figure out how to build a simple snake-like game. Code in which I will touch on the preferences protocol in SwiftUI, the GeometryReader, etc.

The Game

As you might have guessed, I didn’t design a game to run left to right — but I needed to roll to the side to show you. So turn your screen to the right to see it correctly.

You’re looking at a for each loop of shapes, connected with a for each loop of lines through preferences protocol. I use a delay to move the different segments when I drag the head because it looks better. The shapes passing left to right start out as circles that you need to catch. Fail to do so by the time they get to mid-screen and they change into stars. Stars you don’t want…

--

--

Mark Lucking
Mark Lucking

Written by Mark Lucking

Coding for 35+ years, enjoying using and learning Swift/iOS development. Writer @ Better Programming, @The StartUp, @Mac O’Clock, Level Up Coding & More