Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data structure should I use for a snake game?

I have some homework for my school and I have to make a snake game, like Nokia's, in Delphi. I wonder which solution is the best. I want my snake be a class and the body is an array of points (parent class) or a linked list of points. What's the best? An array or a linked list?

like image 653
bAN Avatar asked Dec 22 '09 09:12

bAN


People also ask

Which data structure is used for snake game?

The game is played on a 2-dimensional grid of cells, where each cell is either 0, 1, or 2. Snakes can pass through 0s freely, and eat 1s for food.

Which data structure is used in snake and ladder game?

Since movement in Snakes/Chutes and Ladders is usually in a single direction, rather than the multiple directions possible in Chess, a 1D array or list should definitely work.

Which data structure is used in Ludo?

2-player Board game developed using Data Structure(Singly-Linked List), HTML and javascript.


2 Answers

A Linked list is better. (Each node can point to the previous and next node) It is easier to add nodes to the end of a linked list.

If you use an array you would either need to resize it or initialise it to the Maximum possible snake length to start with which can be wasteful on memory.

UPDATE This article talks about pointers in Delph and even suggests a simple Node definition delphi article

like image 174
Andrew Avatar answered Oct 14 '22 05:10

Andrew


A simple solution is to make an array[horizontal][vertical] of type, so that there is one item for each coordinate on the screen. Each type can be a snake-direction, food, poison, wall or empty. This means that you only need to remember the head and tail position of the snake, and the count of food and poisons, and the array describes how the screen looks like.

This removes the hassle of handling the snake's elements, and makes it easy to position new food or poison items on the screen, ensuring that you're not putting it into a place that is already occupied.

When you need to remove the tail element of the snake, get the direction of the tail using direction:=array[tailx,taily]; and then set array[tailx,taily]:=empty. Afterwards, update tailx and taily depending on the direction. That's it.

like image 25
Lars D Avatar answered Oct 14 '22 06:10

Lars D