Text based game problem.

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
#include "stdafx.h"


#include <iostream>
int win();
int whoWins;

int main(){
	int playerHorizontal;
	int playerVertical;
	char player = 'P';
	char comp = 'C';
	char grid[7][6];
	int i;
	int j;

	for (i = 0; i < 7; i++){
		for (j = 0; j < 6; j++){

			grid[i][j] = 'O';
			std::cout << grid[i][j];

		}
		std::cout << std::endl;
		
	}

	
	std::cout << "write the horizontal and vertical coordinates for your target place." << std::endl;
	
	std::cin >> playerHorizontal;
	std::cin >> playerVertical;
	grid[playerHorizontal][playerVertical] = player;
	std::cout << grid[i][j];
}

It doesn't change the O to P but instead prints a different strange character each time (after I write playerHorizontal and playerVertical).Please help.
Last edited on
What are the values of i and j at line 34?
should I write the for loops again? I don't understand :/
After the end of the for loops, both i and j have values one greater than the array size. Thus the location they index is somewhere outside the array.

It might be simpler to break up your code into functions, as some of it will probably be reused many times.

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
#include <iostream>
#include <windows.h>

const int HEIGHT = 7;
const int WIDTH  = 6;

void gotoxy( int column, int line );
void init(char grid[HEIGHT][WIDTH]);
void display(char grid[HEIGHT][WIDTH]);

int main()
{
    const char player = 'P';
    const char comp   = 'C';

    char grid[HEIGHT][WIDTH];
 
    init(grid);       // set all 'O'
    display(grid);    // show the grid
    
    std::cout << "write the horizontal and vertical coordinates for your target place." << std::endl;
    
    int playerHorizontal;
    int playerVertical; 
    
    std::cin >> playerHorizontal;
    std::cin >> playerVertical;
    grid[playerHorizontal][playerVertical] = player;
    
    display(grid);
}

void gotoxy( int column, int line )
{
    COORD coord;
    coord.X = column;
    coord.Y = line;
    SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), coord );
}

void init(char grid[HEIGHT][WIDTH])
{
    for (int i = 0; i < HEIGHT; i++)
        for (int j = 0; j < WIDTH; j++)
            grid[i][j] = 'O';
}

void display(char grid[HEIGHT][WIDTH])
{
    gotoxy(0,0);
    for (int i = 0; i < HEIGHT; i++)
    {
        for (int j = 0; j < WIDTH; j++)
            std::cout << grid[i][j];
        std::cout << '\n';
    }
    
    gotoxy(0, HEIGHT+2);
}

Last edited on
Thanks so much!
Topic archived. No new replies allowed.