Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array assignment Snake

Working in a business environment, I don't really get to code or use the good old console anymore. My work is repetitive and thus not really challenging.

I decided to challenge myself by writing a snake game in a C# console; and boy did it make my brain work. I never have to think this hard on a day-to-day basis, but I felt like my programming skills weren't getting any better.

I have a problem though. The basic approach I took was to create a snake class and a food class. The snake class uses an array to store all coordinates and then a drawing class decides what coords to draw on-screen.

The problem is that as you move the snake, the array fills up (maxsize is 250 for performance), so when I reach the end of the array I want to copy the last few coords to a temp array, flush the original array and copy the temp coords back to the main array.

The problem I have is copying x coords back to the original array. I decided to do it manually to test but this solution always makes my poor snake leave behind one of its segments on the screen when it shouldn't be there.

How would I go about doing this programmatically?

spoints[4, 0] = stemp[249, 0];
spoints[4, 1] = stemp[249, 1];
spoints[4, 2] = stemp[249, 2];

spoints[3, 0] = stemp[248, 0];
spoints[3, 1] = stemp[248, 1];
spoints[3, 2] = stemp[248, 2];

spoints[2, 0] = stemp[247, 0];
spoints[2, 1] = stemp[247, 1];
spoints[2, 2] = stemp[247, 2];

spoints[1, 0] = stemp[246, 0];
spoints[1, 1] = stemp[246, 1];
spoints[1, 2] = stemp[246, 2];

spoints[0, 0] = stemp[245, 0];
spoints[0, 1] = stemp[245, 1];
spoints[0, 2] = stemp[245, 2];

I really don't mind posting the whole game here if someone really wants to dig into the code.

like image 526
Batista Avatar asked Jan 26 '12 10:01

Batista


2 Answers

It sounds like an array is the wrong data type for your purposes. Consider using a List instead, since it allows for more flexibility when moving entries around.

like image 97
Heinzi Avatar answered Sep 28 '22 08:09

Heinzi


Consider using an array for 'general points' not drawing points, create another class called something like SnakePart so your Snake class has manageable parts.

You could also create a custom array class so in each part of the grid you would only have a value hasSnakePart and manipulate that.

like image 24
hyp Avatar answered Sep 28 '22 08:09

hyp