December 5th, 2010, 10:04 PM
Using array for x and y coordinates?
Hey guys, I have recently been trying to redo a game I made a while back to make the code more efficient and readable, so that people looking at the source actually know what their looking at. So, I'm redoing a few parts that I did in very inefficient, bulky ways, and replacing those methods with newer compact ones.
Now, thats been working just great, until I tried to replace the way I used to do x and y coordinates with an array. The way the game used to work was that when the user typed in a command like "north" or "west", the program would add 1 to the y and subtract 1 from the x, respectively. Now, to reduce possible bugs with using the x and y directly, I assigned a number to each spot, called z, with a very long, complicated mess of code that looked like this:
This ended up making the grid look like this
int main ()
//blah blah blah
if ( x == 1 && y == 5 )
z = 1;
if ( x == 2 && y == 5 )
z = 2;
if ( x == 3 && y == 5 )
z = 3;
//blah blah blah
5|1 2 3 4 5
4|6 7 8 9 10
3|11 12 13 14 15
2|16 17 18 19 20
1|21 22 23 24 25
0 1 2 3 4 5
Now because of how unbelievably horribly long this was, I ended up just replacing all that code with an equation:
This works just fine, however, I do want to just get rid of the x, y, and z all together and replace it with a 2-dimensional array. Since I don't have much experience with arrays, however, I need a bit of help.
z = ( ( 5 - y ) * 5 ) + x;
What I want the array to do is have each of the 25 squares numbered using a slightly modified version of the above equation (to compensate for the fact that it goes from 0-4 instead of 1-5). But then, I also want to have some kind of way to be able to store the location of the player inside of one of the squares in the array and then have the program be able to compare the location of the player in an if statement, in something like this:
Any ideas? Its not really mandatory (since the way I have works, I guess) but it would help my understanding of arrays and make everything look nicer.
If ( array[x][y] == near_the_tv && strcmp (input, "watch tv" ) == 0 )
cout<<"You watch TV. There is nothing good to watch.\n\n";
Thanks in advance, guys!
Tags for this Thread
Click Here to Expand Forum to Full Width