Build a Snake Game in SwiftUI Using GeometryReader | by Mark Lucking | Feb, 2022

See find out how to leverage Preferences protocol

Photograph by on

Though I’m fairly certain Confucius, who was round in 450BC, wasn’t a programmer, some recommendation he had about studying issues couldn’t have been extra true relating to coding.

Inform Me and I Will Neglect;
Present Me and I Could Keep in mind;
Contain Me and I Will Perceive.

So be part of me on this article to determine find out how to construct a easy snake-like sport. Code during which I’ll contact on the preferences protocol in SwiftUI, the GeometryReader, and many others.

As you might need guessed, I didn’t design a sport to run left to proper — however I wanted to roll to the facet to point out you. So flip your display screen to the suitable to see it appropriately.

You’re a for every loop of shapes, linked with a for every loop of traces by preferences protocol. I exploit a delay to maneuver the completely different segments after I drag the top as a result of it seems to be higher. The shapes passing left to proper begin out as circles that you might want to catch. Fail to take action by the point they get to mid-screen and so they turn into stars. Stars you don’t wish to catch. Whenever you catch a circle, the snake grows by one section. Catch a star accidentally or fully miss a circle [which becomes a star], and the snake shrinks by a section. The tip sport is when the snake has no extra segments to lose.

Final week I revealed an article on one other sport I simply constructed that you simply discover . It, too, relied on circles and contours; However I made it fairly otherwise. To assemble the graph like construction inside it, I predefined all of the coordinates. However on this case, I wanted to have the ability to construct it dynamically, which is why I turned to the SwiftUI preferences protocol.

The animated GIF exhibits a POC with all of the important parts in place — I received a snake, passing issues to catch or not, and a few scoring happening, the place to subsequent. Upmost in my thoughts is the phrase much less is extra.

  • Most video games have some levels or challenges — have to do.
  • Most video games have some ranges at which level you may be part of — have to do.
  • Most video games have a league desk of types — have to do.

Bon, at this level, I’ve “berries”, if you’ll, that fall at a continuing fee. If the snake misses them mid-screen, then he must keep away from them. What are some straightforward wins? Listed below are some ideas on how I may make the sport more difficult with out an excessive amount of extra code.

  • I may introduce “berries” that he must keep away from altogether?
  • I may introduce “berries” that fall at completely different charges, some sooner, some slower?
  • I may introduce “berries” that change their pores and skin at some random level on their journey?
  • I may make some “berries” extra beneficial than others and have some scoring mechanism.
  • I may make the “berries” fall at completely different speeds?
  • On the snake facet of issues, altering the segments’ form could be a superb technique to management the problem stage; the bigger the snakehead, the better it to seize “berries”?
  • I may gradual the slithering of the snake because it will get greater.
  • I may make his physique some extent of vulnerability at present. Nothing occurs past the top.
  • Going again to the worth of the berries, I may make the snake develop sooner or slower.

Okay, what does that seem like this — . The format of the snake has modified a tad however is kind of the identical — besides the animation of the tail that will get slower because it will get longer. The berries now are available 4 flavours; the darker ones you wish to catch, the lighter you don’t. They’re all transferring at completely different speeds now too.

The identical guidelines apply: catch a berry the tail will get longer, drop one and will get shorter. Catch the fallacious berry the tail will get shorter. It’s a far sooner sport than POCI.

Bon — sufficient textual content and photos — how did I do it. As I stated, the bottom line is in implementing the SwiftUI preferences protocol that appears like this.

I created a struct during which I retailer an index worth and CGRect. I named that struct to avoid wasting within the preferences protocol template after which made a 3rd struct to make use of it.
Past that, I make the PreferenceViewSetter struct because the background of the snake segments. So with this snippet of code.

RoundedRectangle(cornerRadius: 8)
.stroke(, lineWidth: 2)
.body(width: 24, top: 24)
.background(PreferenceViewSetter(idx: idx))

Code I name inside a loop that claims what number of segments I would like. It’s a loop the dimensions of which I modify as the sport progresses. I received this code in place exterior the loop, drawing the segments.

.onPreferenceChange(TextPreferenceKey.self) { preferences in
for p in preferences
self.rects[p.viewIdx] = p.rect

It saves the CGRects as every section is drawn inside to an exterior array that I subsequently reference with this struct once more inside the identical run because the drawing of the segments.

Once more referred to as inside a loop, this routine attracts a line between every snake section. Placing all of it collectively, it seems to be like this. SnakeView right here attracts the segments updates preferences that replace the reacts array — an array that’s previous again to the drawing of the traces.

Implementing the berry drops is much extra simple and easily makes use of a timer to set off an array of berry information to behave upon.

All of which brings me to the top of this quick piece. Obtain the complete code base from bitbucket on to get extra concerned, as Confucius recommended you must. Use it as a foundation to construct your personal snake sport!

More Posts