Saturday, March 18, 2017

objective c - Snake game logic


So I'm thinking about making snake game. I started thinking about it. I figured out almost everything, but I have found one fundamental problem I can not fix myself and I need your help. The logic here is simplified.


We have a grid 10 by 10. A snake is 3 segment long thing that occupies 3 sectors of the grid. I think of implementing the container for snake body as two-dimensional array. So if the snake is somewhere in the middle horizontally and we calculate position from lower left, it might be in positions array[5][5], array[5][6], array[5][7].


Now, to move snake we need to add another segment at the direction it moves and remove segment from its tail. For that we need int direction that holds 4 possible directions and two Structures each of which contains x and y coordinate of segment in array. We may set the length and coordinates of snake in the init steps. So we have structures preset for us at start. Lets imagine they are


Tail.y = 5, Tail.x = 5; Head.y = 5, Head.y = 7;


And the direction will be some arbitary number that we decided says it is east.



So when we move our snake, we look for head, check direction, and add a segment in that spot, and set our head struct to point at that spot. So our new head is array[5][8]. Then we check for tail. Our struct says its array[5][5]. We remove it from array. Here comes the problem with my logic. How do we get our struct to point on the last element of our snake that becomes a new tail?


Easy solution seems to check direction and look for segment next after last tail in that direction, but if our snake is not straight line it will fail.


I understand that my question is huge but it is all simple, just need some guidance.


The language I use is Objective-C.


EDIT:


As nobody suggested, I used NSMutableArray of CGPoints (wrapped in NSValue). I can freely add objects to array and remove from it. This way the first object is always head and the last object is always tail. It gets trivial at that point.



Answer



You could go for a linked list, as others suggested. But basically, a snake is just a FIFO stack (sometimes called a queue) of grid coordinates:



  • When the snake grows one bit, you just push an element on top of the stack


  • When it moves one square, you push an element on top and pop an element off the bottom


For an implementation of a queue in Objective-C, you can check this answer on SO, it seems OK by looking at all the upvotes.


Also, check this answer for some more snake implementation tips.


[self-promotion] Oh, and for an interesting snake implementation, you could check the source code for SnakeDemocracy! [/self-promotion]


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...