Friday, May 3, 2024
HomeProgrammingCode a Snake Sport With Button Controls Utilizing SwiftUI | by Mark...

Code a Snake Sport With Button Controls Utilizing SwiftUI | by Mark Lucking | Sep, 2022


A have a look at what it takes to construct one other basic sport

The snake sport in SwiftUI

The opposite week I revealed an article about my journey to construct the Tetris sport a problem. You’ll be able to examine it right here. One other related however totally different sport that predated Tetris; one other basic a extra simple implementation is the snake sport. Be part of me on this quick paper to construct your copy of the snake sport utilizing pure SwiftUI.

At its most simple, the snake sport is nothing greater than a sq.. You need to navigate the display screen to “eat” single squares that seem randomly on it. As you eat the singles, the snake absorbs them and turns into simply that little bit longer.

The problem is that the snake, because it turns into longer, should not hit the edges or itself self; a sport that will get progressively more durable because the snake will get longer, and the case of this implementation will get sooner as nicely.

To begin, I want a loop because the snake strikes repeatedly, so a timer like that is the apparent selection.

var timer = Timer.publish(each: 0.5, on: .essential, in: .widespread).autoconnect()

Past that, I want a view representing every section of the snake. A view that should bear in mind its place.

Inside the primary loop of the sport, I want to attract a slice of the snake’s segments because it progresses; the snake itself rising in dimension provided that you handle to eat singles.

Word the code defining the primary entry into this array is equivalent to the snake physique struct. However I couldn’t use the struct because the struct had not been initialised earlier than the compiler wished to initialise the @State variable right here.

Throughout the identical loop, I draw a special coloured sq. that represents the meals that the snake should eat to develop, with one essential caveat I want to concentrate to; the situation of the meals have to be saved inside a @State variable that I can match to the top of the snake.

ZStack {
ForEach((snakeStart..<snakeParts.rely), id: .self) {
snakeParts[$0]
}
}.id(snakeCount)

Lastly, I want a set of controls by which I can sign to the snake that they should change course, with the one barely uncommon code here’s a longPressGesture with a minimal time of zero — aka a contact. Code that appears like this.

Textual content("Up")
.font(Fonts.avenirNextCondensedBold(dimension: 24))
.onLongPressGesture(minimumDuration: 0) {
snakeDirection = .up
}.padding()

I didn’t point out it, however you may see it right here. I additionally created an enum with my 4 instructions to make issues a bit extra readable.

Now, because the timer ticks, I want to maneuver the top of the snake by creating a brand new section in the identical course because the beforehand commanded course. A process I do with this code.

Subsequently, I then add a section to the array and assuming he hasn’t simply eaten the meals sq. transfer the slice to view up by one.

let newPart = SnakeBody(snakeHead: snakeHead)
snakeParts.append(newPart
.eraseToAnyView())
snakeStart += 1

The eraseToAnyView is likely one of the normal extensions I talked about on this paper. Bon — now once you handle to eat some a snake meals, I must do two issues — I must create and place some extra meals, and I wish to make it a tad extra difficult so I shave off a couple of nanoseconds from the timer.

Word these odd-looking magic formulae I’ve in place for the rndX and rndY values are the way in which it’s as a result of I want to verify every meals morsel is positioned at an X/Y place I can match in opposition to my shifting snake head.

All of which brings me to an finish — I feel I made it sound a bit simpler than it was — I can not deny that it took me a number of hours, ultimately, to get all of it proper.

You’ll discover the entire code right here — must you wish to try to create your personal model of the snake sport.

After all, it isn’t fairly completed — I depart so that you can do as a ultimate problem.

  • At present, the snake can disappear of the display screen; some boundary checks have to be added to the code, a game-over situation.
  • On the identical notice, the snake can run into itself with out consequence, a second game-over situation that you might want to add.
  • Lastly, some type of rating and/or message could be good when the sport ends in order that the participant can see if they’re getting any higher.

Now, though this little app works completely on iPhone 14 and a 12.9′ iPad Professional simulator, it didn’t work accurately on my iPhone 8. It failed as a result of the if assertion on the lookout for the snake’s seize of the meals is simply too exact; a ultimate problem for you, the reader, is so as to add a perform that is a bit more forgiving that may look to see if the coordinates are a close to sufficient match!



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments