Your problem seems to be conceptual/organizational.
Take a look at lines 55 through 58:
1 2 3 4
|
for (int y = 0; y<20; y++)
{
for (int x = 0; x<20; x++)
{
| |
You are looping through the entire map. In this loop, you are checking the user's keypresses and moving the user.
So.. for example.. let's say the player is at x=1... and they press the right key. This is what happens:
- x=0. You check to see if the map character is '@'. It isn't.
- x=1. You check to see if the map character is '@'. It is, so you move the character to the right
- x=2. You check to see if it's '@'. It
is (because you just moved it), so you move it again
- x=3. You check for '@'. It
is, so you move it again
and again
and again
until you hit a wall or until the loop ends.
Same thing happens when you press down.
The solution is to move that logic out of the loop (it's wasteful to have it in a loop anyway... you shouldn't check the buttons 400 times... you should only have to do it once).
The problem is.... you do not keep track of the player's position in dependently. You only know where the player is because he's a '@' symbol on the map.
<side rant>This is one reason why I really dislike console as a medium for games, as it kind of hints at these types of tricks. I strongly consider leaving the console and using an actual graphics lib like SFML. It really is much easier that you'd think.</side rant>
So you need to do a few things.
1) You need to keep track of player position in a better way. I'd create 2 vars named 'playerx' and 'playery' or something... and keep them updated as the player moves.
2) You need to change how the player is drawn. The player and the map are 2 different things and should be drawn separately. This is slightly harder to do on the console that it would be with traditional graphics, but is not impossible.
3) Your move function(s) would need to update the player position, rather than update the map.
I also recommend the following changes:
4) Combine MoveLeft/MoveRight/etc functions into one 'Move' function. Notice how they're largely copy/pastes of each other.
5) Convert your '#' symbols to blocks
once at startup (or really, when the map is loaded), rather than every frame.
6) Possibly even make some defines rather than use magic numbers/symbols.
7) The correct way to use GetAsyncKeyState is to check the high bit of the return value... not to check for nonzero.
8) Only redraw if you need to (to minimize flickering) -- ie, only redraw if the player moved.
9) Eventually you'll probably want to get rid of those globals and put things in a class... but it's fine for now.
I made those changes (except for #9) here. I also added comments so you can follow what I did. Let me know if you have questions.