Tuesday, July 28, 2009

Simple snake in C program?

Hi i'm creating a snake program,





first this is how it will be look like:





"x0000" at a fix location in the map





x= head


0=body


when the head touch a food 0 +1





how do i code this x0000 move in the map?


how do i code when head touch the food in the map?

Simple snake in C program?
First, I assume your map will be a 2-dimensional array. So, say you have a 10 x 10 array of characters: char map[10][10].





The first element value represents rows, the second, columns.


Next, let's say that the head of the snake is at [4][5]. That means, somewhere along the line, you set map[4][5] = 'x'. Given the body length of 4 you show above, this means map[4][6] = '0', map[4][7] = '0', map[4][8] = '0', and map[4][9] = '0'.





To move the snake left, you have to update the array values. So, map[4][4] = 'x', map[4][5] now = '0', etc. and you'll have to make map[4][9] =''





Food exists in your array as 1. So, if food is at (3, 3), map[3][3] = '1'. When you move the snake, before changing the value, check the value of where the head is about to go. So, if the snake is about to goto map[3][3], check...





if ( map[3][3] == '1' )


{


...// found_food is true... do something about it.


}


// done managing food; now just move snake where it was going to go


map[3][3] = 'x' // the new head location





I've hard-coded map[3][3], you'll need to make a function that takes as its argument any values of the multidimensional array so it check the value.





You'll also need to keep track of length of the snake as I assume it grows when it eats food.
Reply:Appart from the two dimensional array, and the snake growth, you will also need to create a timer (thread). This will allow you to "refresh" the current snake position according to the momentum you defined from your keystrokes. You will need a while loop, and a way of determening the current_time - last_update.





One other thing is to ensure that you have a variable which stores the last pressed keystroke.





Interesting project mate :)
Reply:you can login for free at www.dreamincode.net , read the forum rules, then post your programming questions there. There are a lot great hardcore programmers there around the world.





My screenname is 'nirvanarupali'


No comments:

Post a Comment