We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › Array shifting for snake
Page Index Toggle Pages: 1
Array shifting for snake? (Read 1068 times)
Array shifting for snake?
Jul 23rd, 2007, 4:48pm
 
Yeah I want to make a snake game, but for this I have to find a way to shift the data from an array. IE, an array contains those numbers:
{12, 95, 25, 68, 45}
Now I need to add a data at the very begining, and shift all the data right. Say I insert 89, this is how it should look:
{89, 12, 95, 25, 68}
Now I guess I could use Java's Queue class to add data and remove the last, but I cant find a way to make it work in Processing.

Anybody got an idea?
Re: Array shifting for snake?
Reply #1 - Jul 23rd, 2007, 5:22pm
 
Allow me to suggest a different data structure:  circular buffer.  The snake game is a good example for illustrating that structure (because the typically used pointer names "head" and "tail" make intuitive sense for the snake).  A circular buffer whose size is the maximum possible legnth of the snake will allow you to avoid array shifting entirely.
Re: Array shifting for snake?
Reply #2 - Jul 23rd, 2007, 5:32pm
 
if you're just doing a series of integers, using modulo (%) is the best:

Code:
int[] nums = new int[10];
int numIndex = 0;

int addNum(int what) {
nums[numIndex] = what;

if (numIndex == 0) {
numIndex = nums.length-1;
} else {
numIndex--;
}
}

void retrieveNums() {
for (int i = 0; i < nums.length; i++) {
int index = (i + numIndex) % nums.length;
// do something with 'index' here
}
}


or you can use arraycopy to shift things over:

Code:
int[] nums = new int[10];

void addNum(int what) {
arraycopy(nums, 0, nums, 1, nums.length-1);
nums[0] = what;
}


...or you can use a for() loop to shift it by hand. but the % method is best/fastest.

if you're not using int[] arrays, you can do the same thing as above with objects.
Re: Array shifting for snake?
Reply #3 - Jul 24th, 2007, 5:42pm
 
davbol, that is what I had implemented but unsuccessfully, using a for loop to manually shift 'em. I really need to think in terms of simplicity and thats what is getting me. Thanks for your answer fry, it resolves the problem.
Page Index Toggle Pages: 1