Moving a value along a grid

I am trying to make a program in which you input an integer, to move one unit (up, down, left, or right) along a grid. I am not entirely sure what I have wrong. Any help would be 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
#include "stdafx.h"
#include <iostream>

using namespace std;

char player = 'x';
char grid[3][3] = {{ player, '.' ,'.'},{'.', '.', '.' },{'.', '.', '.' } };

void Draw() {
	for (int row = 0; row <= 2; row++) {
		for (int col = 0; col <= 2; col++) {
			cout << grid[row][col];
		}
		cout << endl;
	}
}

int main() {
	int posX = 0;
	int posY = 0;
	int in;
	int turns = 0;
	Draw();
	while (turns < 10) {
		cin >> in;
		if (in == 1) {
			grid[posY][posX] = '.';
			posY = posY - 1;
			grid[posY][posX] = player;
		}
		else if (in == 2) {
			grid[posY][posX] = '.';
			posY = posY + 1;
			grid[posY][posX] = player;
		}
		else if (in == 3) {
			grid[posY][posX] = '.';
			posX = posX - 1;
			grid[posY][posX] = player;
		}
		else if (in == 4) {
			grid[posY][posX] = '.';
			posX = posX + 1;
			grid[posY][posX] = player;
		}
		else {
			grid[posY][posX] = player;
		}
		system("cls");
		Draw();
		turns++;
	}
	cin.get();
	return 0;
}
Last edited on
@joohoo200

You have to check first that the move does not take you past the scope of your array.

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
#include <iostream>

using namespace std;

char player = 'x';
char grid[3][3] = { { player, '.', '.' }, { '.', '.', '.' }, { '.', '.', '.' } };

void Draw() {
	for (int row = 0; row <= 2; row++)
	{
		for (int col = 0; col <= 2; col++)
		{
			cout << grid[row][col];
		}
		cout << endl;
	}
}

int main() {
	int posX = 0;
	int posY = 0;
	int in;
	int turns = 0;
	Draw();
	while (turns < 10) {
		cin >> in;
		if (in == 1)
		{
			if (posY - 1 >= 0)//Only allow a move IF you stay within grid
			{
				grid[posY][posX] = '.';
				posY--; // Same as posY = posY -1;
				grid[posY][posX] = player;
			}
		}
		else if (in == 2) {
			if (posY + 1 < 3)
			{
				grid[posY][posX] = '.';
				posY++; // Etc.
				grid[posY][posX] = player;
			}
		}
		else if (in == 3) {
			if (posX - 1 >= 0)
			{
				grid[posY][posX] = '.';
				posX--; // Same as posX = posX -1;
				grid[posY][posX] = player;
			}
		}
		else if (in == 4) {
			if (posX + 1 < 3)
			{
				grid[posY][posX] = '.';
				posX++;// Etc.
				grid[posY][posX] = player;
			}
		}
		// Now, no need for this
		/*else 
		{
			grid[posY][posX] = player;
		}*/
		system("cls");
		Draw();
		turns++;
		// And here, we'll keep track of moves remaining
		cout << endl << "Moves left : " << 10-turns << endl;
	}
	cin.get();
	return 0;
}
Topic archived. No new replies allowed.