Character Not Moving Correctly

I have written a program that moves a character around a map using a 2D array.
My program behaves as expected when moving to the left and moving upwards. It does not behave correctly when attempting to move to the right and moving down.
I can't find the reason why this is happening. Any help is appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define ROW 10
#define COL 20

int main()
{
    int i, j;
    char player = '*';
    char key = ' ';
    char map[ROW][COL] =
    {
        {"------------------"},
        {"|                |"},
        {"|                |"},
        {"|                |"},
        {"|                |"},
        {"|                |"},
        {"|                |"},
        {"|                |"},
        {"|                |"},
        {"------------------"}
    };

    // Assign initial player position
    map[5][5] = player;

    do
    {
        // Clear console
        for(i = 0; i < 50; i++)
        {
            printf("\n");
        }

        // Draw map
        for(i = 0; i < ROW; i++)
        {
            for(j = 0; j < COL; j++)
            {
                printf("%c", map[i][j]);
            }
            printf("\n");
        }

        // Accept input
        key = getch();

        switch(key)
        {
            // Up works
            case 'u':
            {
                for(i = 0; i < ROW; i++)
                {
                    for(j = 0; j < COL; j++)
                    {
                        if(map[i][j] == player)
                        {
                            map[i - 1][j] = player;
                            map[i][j] = ' ';
                        }
                    }
                }
            }
            break;

            // Down does not work
            case 'd':
            {
                for(i = 0; i < ROW; i++)
                {
                    for(j = 0; j < COL; j++)
                    {
                        if(map[i][j] == player)
                        {
                            map[i + 1][j] = player;
                            map[i][j] = ' ';
                        }
                    }
                }
            }
            break;

            // Left works
            case 'l':
            {
                for(i = 0; i < ROW; i++)
                {
                    for(j = 0; j < COL; j++)
                    {
                        if(map[i][j] == player)
                        {
                            map[i][j - 1] = player;
                            map[i][j] = ' ';
                        }
                    }
                }
            }
            break;

            // Right does not work
            case 'r':
            {
                for(i = 0; i < ROW; i++)
                {
                    for(j = 0; j < COL; j++)
                    {
                        if(map[i][j] == player)
                        {
                            map[i][j + 1] = player;
                            map[i][j] = ' ';
                        }
                    }
                }
            }
            break;

            default:
            {
                return 0;
            }
        }// end switch()

    }while(1);

    return 0;
}// end main()
Seems rather tedious to search the map for the player for each direction. Wouldn't it be easier to store the player's row and column and update that?

Please describe what you mean by "does not behave correctly".

Line 41: This is going to cause an out of bounds reference. What happens when i= 0? You're going to try and access map[-1][j]. That's illegal.

Line 78: Ditto, except the out of bounds reference will occur when i=9.

Line 95: Ditto, out of bounds reference when j =0

Line 112: Ditto, out of bounds reference when j=9.

Seems rather tedious to search the map for the player for each direction. Wouldn't it be easier to store the player's row and column and update that?

The way I have done it is the only way I could figure out how to do it.


Please describe what you mean by "does not behave correctly".

What I mean is that when I enter 'd', the program crashes, and when I enter 'r', the player character flies off the screen.


How would I fix the out of bounds problem?
Last edited on
Any help on my original question?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  int player_x = 5;
  int player_y = 5;
...
bool legal_move (int x, int y)
{   return  (x >= 0 && x < ROW && y >= 0 && y < COL); 
}

void move_player (int x_incr, int y_incr)
{    if (! legal_move(player_x + x_incr, player_y + y_incr))
      {  cout << "Can't move any further in that direction"  << endl;
          return;
      }
      map[player_x+x_incr][player_y+y_incr] = player;
      map[player_x][player_y] = ' ';
      player_x += x_incr;
     player_y += y_incr;
}

...
  switch (key) 
  { 
   case 'u':
    move_player (-1, 0); 
    break; 
  case 'd':
    move_player (1, 0);
    break;
  case 'r'
     move_player (0, 1);
     break;
  case 'l':
    move_player (0,-1);
    break;
  }


Don't forget you have a border on your map. You don't want to overlay the border.

Last edited on
I don't understand most of that, but it works if I make a few variables global.

Thanks for your effort, but would it be possible to fix my code to make the program work?

I'd like to stick as close to my code as possible. Even if it's not the best, I at least have a good understanding of how it works.
I don't understand most of that

legal_move() simply determines if a proposed x and y are in bounds.

The only tricky part here is move_player(). move_player is passed an increment (+1) or decrement (-1) to either x or y depending on the direction selected. The first thing move_player() does is to check if the proposed new position is legal. If not, an error messaage is displayed and move_player() exits. Line 13. We now know the proposed position is legal so we can place the player marker in that new position. The only confusing part really is that even though the argument names are x_incr and y_incr, their value may be 1, 0 or -1. Line 14: We put a space in the player's current position. Lines 15-16: We adjust player_x and player_y to the new position.

would it be possible to fix my code to make the program work?

Lne 61,78,95,112: You need to check that the proposed position is legal before placing the player there. You can't move the player there if either index would cause an out of bounds condition.

1
2
3
4
5
6
7
8
9
10
11
12
13
  case 'd':
            {
                for(i = 0; i < ROW; i++)
                {
                    for(j = 0; j < COL; j++)
                    {
                        if(map[i][j] == player && legal_move(i+1,j) )                  
                       {   map[i + 1][j] = player;
                            map[i][j] = ' ';
                        }
                    }
                }
            }

You can figure the other directions out.

Edit: +1 @ dhayden. I missed that.
Last edited on
Here's why your original code doesn't work. The player starts at position 5,5 and you want to move down. The loop goes through the board and finds the player. The code moves the player to position 6,5. The loop continues to run and finds the player in his new position... and moves him to 7,5. This continues, pushing the player down until it's right off the board.

The same is true when you move right. You move the player to the right and the very next time through the loop you find him in the new position and move to the right again.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
case 'd':
            {
                for(i = 0; i < ROW; i++)
                {
                    for(j = 0; j < COL; j++)
                    {
                        if(map[i][j] == player)
                        {
                            map[i + 1][j] = player;
                            map[i][j] = ' ';
                            break;
                        }
                    }
                }
            }
            break;


@dhayden:
I added in a break at the end of the if statement for the 'd' and 'r' cases. The idea here is to break out of the loop once the if statement has executed. This has fixed the problem for the 'r' case, but the 'd' case is still crashing the program. Any ideas?

@AbstractionAnon:
Thanks for the detailed reply. It's late and I'm too tired right now, but I'll go through your explanation in more detail later.
That added break only breaks you out of the inner loop, not both loops.
You also have not addressed the problem of map[i+1][j] being out of bounds when i = 9.
I managed to get all of the directions to work properly so I moved onto breaking my code up into functions, but I'm getting errors.

Prototypes:
1
2
void drawmap(void);
void initplayerpos(char);


Functions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
void drawmap()
{
    int i, j;
    char map[ROW][COL] =
    {
        {"------------------"},
        {"|                |"},
        {"|                |"},
        {"|                |"},
        {"|                |"},
        {"|                |"},
        {"|                |"},
        {"|                |"},
        {"|                |"},
        {"------------------"}
    };

    initplayerpos(map);

    // Clear console
    for(i = 0; i < 50; i++)
    {
        printf("\n");
    }

    // Draw map
    for(i = 0; i < ROW; i++)
    {
        for(j = 0; j < COL; j++)
        {
            printf("%c", map[i][j]);
        }
        printf("\n");
    }
}// end drawmap()

void initplayerpos(char map[][COL])
{
    char player = '*';
    int position_x = 0, position_y = 0;

    printf("Enter the co-ordinates for the players starting position:\n");
    printf("X co-ordinate(1 - 8): ");
    scanf("%d", &position_x);
    printf("Y co-ordinate(1 - 18): ");
    scanf("%d", &position_y);

    map[position_x][position_y] = player;
}// end initplayerpos() 


The errors I'm getting are:
||=== Build: Debug in map1.1 (compiler: GNU GCC Compiler) ===|
C:\Users\dell\Desktop\map1.1\main.c||In function 'drawmap':|
C:\Users\dell\Desktop\map1.1\main.c|137|warning: passing argument 1 of 'initplayerpos' makes integer from pointer without a cast [enabled by default]|
C:\Users\dell\Desktop\map1.1\main.c|9|note: expected 'char' but argument is of type 'char (*)[20]'|
C:\Users\dell\Desktop\map1.1\main.c|156|error: conflicting types for 'initplayerpos'|
C:\Users\dell\Desktop\map1.1\main.c|9|note: previous declaration of 'initplayerpos' was here|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|


I'm working on the moveplayer() function as well but that is commented out, so that's not the problem.
Last edited on
Your prototype for initplayerpos says it takes one char, while the implementation takes a 2D array. The prototype and implementation must agree.





the line numbers on the errors you posted don't really match up with the code you posted. It looks like you declared initplayerpos twice which is a problem.
Here is my program, working as intended.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define ROW 10
#define COL 20

// Function prototypes
void initplayerpos(char[][COL]);
void drawmap(char[][COL]);
void moveplayer(char[][COL]);

int main()
{
    char map[ROW][COL] =
    {
        {"--------------------"},
        {"|                  |"},
        {"|                  |"},
        {"|                  |"},
        {"|                  |"},
        {"|                  |"},
        {"|                  |"},
        {"|                  |"},
        {"|                  |"},
        {"--------------------"}
    };

    // Initialise the players position
    initplayerpos(map);

    /*
        Draw the map and update the players position
        based on user input in an infinite loop
    */
    do
    {
        drawmap(map);
        moveplayer(map);
    }while(1);

    return 0;
}// end main()

void initplayerpos(char map[][COL])
{
    char player = '*';
    int position_x = 0, position_y = 0;

    printf("Enter the co-ordinates for the players starting position:\n");
    printf("X co-ordinate(1 - 8): ");
    scanf("%d", &position_x);

    // While input is outside specified range
    while(position_x < 1 || position_x > 8)
    {
        printf("Co-ordinate not allowed.\nX co-ordinate(1 - 8): ");
        scanf("%d", &position_x);
    }

    printf("Y co-ordinate(1 - 18): ");
    scanf("%d", &position_y);

    // While input is outside specified range
    while(position_y < 1 || position_y > 18)
    {
        printf("Co-ordinate not allowed.\nY co-ordinate(1 - 18): ");
        scanf("%d", &position_y);
    }

    printf("\nYour co-ordinates are: %d,%d", position_x, position_y);

    // Set player position
    map[position_x][position_y] = player;
}// end initplayerpos()

void drawmap(char map[][COL])
{
    int i, j;

    // Clear console
    for(i = 0; i < 50; i++)
    {
        printf("\n");
    }

    // Draw map
    for(i = 0; i < ROW; i++)
    {
        for(j = 0; j < COL; j++)
        {
            printf("%c", map[i][j]);
        }
        printf("\n");
    }
}// end drawmap()

void moveplayer(char map[][COL])
{
    int i, j;
    int flag = 0;
    char player = '*';
    char key = ' ';

    // Accept input
    key = getch();

    switch(key)
    {
        // Up
        case '5':
        {
            for(i = 0; i < ROW; i++)
            {
                for(j = 0; j < COL; j++)
                {
                    if(map[i][j] == player)
                    {
                        // If hitting wall, move back
                        if(map[i - 1][j] == '-')
                        {
                            map[i - 1][j] = '-';
                            map[i][j] = player;
                        }
                        else
                        {
                            // Move up
                            map[i - 1][j] = player;
                            map[i][j] = ' ';
                        }
                    }
                }
            }
        }
        break;

        // Down
        case '2':
        {
            for(i = 0; i < ROW; i++)
            {
                for(j = 0; j < COL; j++)
                {
                    if(map[i][j] == player)
                    {
                        // If hitting wall, move back
                        if(map[i + 1][j] == '-')
                        {
                            map[i + 1][j] = '-';
                            map[i][j] = player;
                        }
                        else
                        {
                            // Move down
                            map[i + 1][j] = player;
                            map[i][j] = ' ';
                            flag = 1;
                        }
                    }
                }

                // Reset flag to stop loop after player movement
                if(flag == 1)
                {
                    flag = 0;
                    break;
                }
            }
        }
        break;

        // Left
        case '1':
        {
            for(i = 0; i < ROW; i++)
            {
                for(j = 0; j < COL; j++)
                {
                    if(map[i][j] == player)
                    {
                        // If hitting wall, move back
                        if(map[i][j - 1] == '|')
                        {
                            map[i][j - 1] = '|';
                            map[i][j] = player;
                        }
                        else
                        {
                            // Move left
                            map[i][j - 1] = player;
                            map[i][j] = ' ';
                        }
                    }
                }
            }
        }
        break;

        // Right
        case '3':
        {
            for(i = 0; i < ROW; i++)
            {
                for(j = 0; j < COL; j++)
                {
                    if(map[i][j] == player)
                    {
                        // If hitting wall, move back
                        if(map[i][j + 1] == '|')
                        {
                            map[i][j + 1] = '|';
                            map[i][j] = player;
                        }
                        else
                        {
                            // Move right
                            map[i][j + 1] = player;
                            map[i][j] = ' ';
                            break;
                        }
                    }
                }
            }
        }
        break;
    }// end switch()
}// end moveplayer() 


The player moves around the map without error and is contained within the borders. I think the way I have done this prevents out of bounds errors. At the very least, it prevents erroneous output.

While I am pleased with getting my program to work, there are a number of things I would like to know.

Is the way I have structured my functions correct, semantically? I know that you can call functions from inside other functions, but I feel as though calling everything from main() is the best way to stop the code from becoming jumbled. If it is deemed correct and acceptable to call functions from within other functions, liberally or otherwise, please let me know.

The output of the map is quite flickery when moving the player around. I understand that this is due to the fact that the map is re-drawn every time the player moves, but I was wondering if it was possible to reduce the flickering or remove it altogether. Please bear in mind, if suggesting functions, that I am writing this in C, not C++, so I do not have access to C++ functions. Also, I hear that system("cls") is something that should be avoided, so please do not recommend it.

Other than that, any tips, suggestions, constructive criticism or general feedback is very welcome. Thank you.
but I feel as though calling everything from main() is the best way to stop the code from becoming jumbled.


That's not really a healthy way to look at things.

In this case it's fine because main is relatively simple, but I wouldn't recommend keeping that mindset.

It not only is acceptable to call functions from within other functions, but it is also extremely necessary as projects grow larger.


Ultimately, the goal is to keep functions simple. Have them do one job and one job only. If the job is complex, you break it into smaller parts by making more functions to do each individual part. You might have a function that does a large job by doing nothing other than calling a series of smaller functions to do each of its smaller parts -- and those functions in turn might break it down into even smaller parts.

So yeah, don't be afraid of calling functions, or of having too many functions. It's much more common for newbies to have too few functions than too many.


The output of the map is quite flickery when moving the player around. I understand that this is due to the fact that the map is re-drawn every time the player moves, but I was wondering if it was possible to reduce the flickering or remove it altogether


This is mostly due to the fact that the console flushes on newlines.

Whenever it "flushes", it means that whatever you output becomes visible. In effect, this means that someone looking at the screen can see it being drawn, as it is drawn line at a time.

To solve this, you will have to prevent it from flushing, do all your drawing, then flush to make the final changes visible. That way, instead of it being drawn line at a time, the entire screen is drawn at once. This will eliminate flicker as it will appear to update instantly.


The problem is, the console is not really designed to do this easily, and the C standard library does not offer any functions to do this. So to accomplish this, you'll either have to use platform specific APIs (like WinAPI console functions if you're on windows), or you'll have to use a 3rd party lib like NCurses.

OR, instead... you can just ditch the console and use a graphical lib like SDL -- which would probably be easier anyway. It's way easier to make simple games with something like SDL than it is to try to do it with the console. Also, SDL is C, so you don't need C++ for it.

Also, I hear that system("cls") is something that should be avoided, so please do not recommend it.


It's a security hole for sure, and it wouldn't completely solve the flickering problem anyway. So yeah I wouldn't recommend it.

Other than that, any tips, suggestions, constructive criticism or general feedback is very welcome. Thank you.


I'm sure this has been mentioned before, but you should not keep track of player position by examining the contents of the map. The map should essentially just keep track of walls and static objects, and any moving objects like a player or enemies or whatever should be tracked separately (with just X,Y coordinates). That way to move him you already know where he is and where he's going without having to scan the entire map.

This will complicate [console] drawing, though, because you'll have to inject the player into the map before drawing... but with a graphic lib it's a non-issue because you can draw the map and the player separately. So yeah -- get a graphic lib.
You still have what "appears" to be an out of bounds reference.

Lines 119: What happens when i = 0? You appear to be trying to reference map[-1][j], which is not legal. This only works because you're checking that map[i][j] == player at line 116 and player can never be in row 0. Very poor style to have what looks like an out of bounds reference when i=0. It's better to start your loop at 1. Ditto for the other directions.

Line 119-121: What's the point of storing '-' back into map[i-1][j]? You've just verified that it contains a '-' via the if statement. Ditto for the other directions.

As for calling functions, Disch has eloquently stated why funtions are a good thing. Guaranteed your program is going to get jumbled if you keep everything in main.

Last edited on
@Bogeyman

I fiddled with your program, added in a clearscreen function and changed the keys to check for 'wasd', instead. Hope this is what you were wanting your program to do..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>

#define ROW 10
#define COL 21 // Was getting error with COL as a 20. Made it 21

HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);

void cls(HANDLE hConsole);

// Function prototypes
void initplayerpos(char[][COL]);
void drawmap(char[][COL]);
void moveplayer(char[][COL], int x,int y); // Changed to keep track of player location

int main()
{
	int move = 0, x,y;
	char map[ROW][COL] =
	{
		{ "--------------------" },
		{ "|                  |" },
		{ "|                  |" },
		{ "|                  |" },
		{ "|                  |" },
		{ "|                  |" },
		{ "|                  |" },
		{ "|                  |" },
		{ "|                  |" },
		{ "--------------------" }
	};

	// Initialise the players position
	initplayerpos(map);
	for (int map_x = 0; map_x < ROW; map_x++)
		for (int map_y = 0; map_y < COL; map_y++)
			if (map[map_x][map_y] == '*')
			{
				x = map_x;
				y = map_y;
			}
	/*
	Draw the map and update the players position
	based on user input in an infinite loop
	*/
	drawmap(map);
	do
	{
		moveplayer(map, x, y);
		for (int map_x = 0; map_x < ROW; map_x++)
			for (int map_y = 0; map_y < COL; map_y++)
				if (map[map_x][map_y] == '*')
				{
					x = map_x;
					y = map_y;
				}
		drawmap(map);
	} while (1);

	return 0;
}// end main()

void initplayerpos(char map[][COL])
{
	char player = '*';
	int position_x = 0, position_y = 0;

	printf("Enter the co-ordinates for the players starting position:\n");
	printf("X co-ordinate(1 - 8): ");
	scanf_s("%d", &position_x);

	// While input is outside specified range
	while (position_x < 1 || position_x > 8)
	{
		printf("Co-ordinate not allowed.\nX co-ordinate(1 - 8): ");
		scanf_s("%d", &position_x);
	}

	printf("Y co-ordinate(1 - 18): ");
	scanf_s("%d", &position_y);

	// While input is outside specified range
	while (position_y < 1 || position_y > 18)
	{
		printf("Co-ordinate not allowed.\nY co-ordinate(1 - 18): ");
		scanf_s("%d", &position_y);
	}

	printf("\nYour co-ordinates are: %d,%d", position_x, position_y);

	// Set player position
	map[position_x][position_y] = player;
}// end initplayerpos()

void drawmap(char map[][COL])
{
	int i, j;

	// Clear console
	cls(console);

	// Draw map
	for (i = 0; i < ROW; i++)
	{
		for (j = 0; j < COL; j++)
		{
			printf("%c", map[i][j]);
		}
		printf("\n");
	}
}// end drawmap()

void moveplayer(char map[][COL], int x, int y)
{
	int i=x, j=y;
	int flag = 0;
	char player = '*';
	char key = ' ';
	
	// Accept input
	key = _getch();
	key = tolower(key);
	switch (key)
	{
		// Up
	case 'w':
		if (map[i - 1][j] == ' ')
		{
			map[i - 1][j] = player;
			map[i][j] = ' ';

		}
		break;

		// Down
	case 's':
		if (map[i + 1][j] == ' ')
		{
			map[i + 1][j] = player;
			map[i][j] = ' ';

		}
		break;

		// Left
	case 'a':
		if (map[i][j - 1] == ' ')
		{
			map[i][j - 1] = player;
			map[i][j] = ' ';

		}
		break;

		// Right
	case 'd':
		if (map[i][j + 1] == ' ')
		{
			map[i][j + 1] = player;
			map[i][j] = ' ';

		}
		break;
	}// end switch()
	// end moveplayer() 
}

void cls(HANDLE hConsole)
{
	COORD coordScreen = { 0, 0 };    // home for the cursor 
	DWORD cCharsWritten;
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	DWORD dwConSize;

	// Get the number of character cells in the current buffer. 

	if (!GetConsoleScreenBufferInfo(hConsole, &csbi))
		return;

	dwConSize = csbi.dwSize.X * csbi.dwSize.Y;

	// Fill the entire screen with blanks.

	if (!FillConsoleOutputCharacter(hConsole,        // Handle to console screen buffer 
		(TCHAR) ' ',     // Character to write to the buffer
		dwConSize,       // Number of cells to write 
		coordScreen,     // Coordinates of first cell 
		&cCharsWritten))// Receive number of characters written
	{
		return;
	}

	// Get the current text attribute.

	if (!GetConsoleScreenBufferInfo(hConsole, &csbi))
		return;

	// Set the buffer's attributes accordingly.

	if (!FillConsoleOutputAttribute(hConsole,         // Handle to console screen buffer 
		csbi.wAttributes, // Character attributes to use
		dwConSize,        // Number of cells to set attribute 
		coordScreen,      // Coordinates of first cell 
		&cCharsWritten)) // Receive number of characters written
		return;

	// Put the cursor at its home coordinates.
	SetConsoleCursorPosition(hConsole, coordScreen);
}

@Disch:
Thank you very much for the informative reply.


It not only is acceptable to call functions from within other functions, but it is also extremely necessary as projects grow larger.

Thank you for clearing that up.


Ultimately, the goal is to keep functions simple. Have them do one job and one job only.

I'll be sure to remember that.


you can just ditch the console and use a graphical lib like SDL

That would be a good idea for any future game related programs I might wish to write. After writing this program, I've gone as far with the console alone as I wish to go for making games. I just wanted to see if I could use the console by itself to make this kind of program, and I'm glad I was able to pull it off at least once.


I'm sure this has been mentioned before, but you should not keep track of player position by examining the contents of the map. The map should essentially just keep track of walls and static objects, and any moving objects like a player or enemies or whatever should be tracked separately (with just X,Y coordinates). That way to move him you already know where he is and where he's going without having to scan the entire map.

How would I change my code so that I can update the co-ordinates without having to loop through the entire array?


@AbstractionAnon:

It's better to start your loop at 1.

Thanks for pointing that out. Would something like this do?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
        // Up
        case '5':
        {
            for(i = 1; i < ROW + 1; i++)
            {
                for(j = 1; j < COL + 1; j++)
                {
                    if(map[i][j] == player)
                    {
                        // If hitting wall, move back
                        if(map[i - 1][j] == '-')
                        {
                            map[i][j] = player;
                        }
                        else
                        {
                            // Move up
                            map[i - 1][j] = player;
                            map[i][j] = ' ';
                        }
                    }
                }
            }
        }
        break;



What's the point of storing '-' back into map[i-1][j]?

Quite right. I'm not entirely sure why I thought that was necessary. I've changed it now.


@whitenite1:
Thank you for taking the time to write that. There seem to be several errors, however, when I try to run the code, the foremost of which appears to be on line 9.
Would something like this do?

That's the idea, but I would not be adding 1 to ROW and COL.
To do so is going to generate an out of bounds reference. In fact, I would be subtracting 1 from ROW and COL since the player can never be in the last row or column.

Line 6: Debatable whether to start j at 1. Since you're subtracting 1 only from i, starting j at 1 makes sense since the player can never be column 0 because of the border.
Topic archived. No new replies allowed.