how to make a char move in a grid using 2d arrays and gotoxy().

I am making a game for a school project with gotoxy and getch and 2d character arrays. there is supposed to be a robot type figure that can move left and right by pressing 'a' and 'd'. so far i've been able to make the cursor go left or right on the grid but can't make a charactar appear at its place. my code,


#include <iostream.h>
#include<conio.h>
#include <windows.h>


// char moveR;
// char moveL;
int mx=30;
int my=10;
int i, j;
char direction;
const char left_key='a', right_key='d';
char keypress;
char a[24][79];


void gotoxy(short x, short y)
{
HANDLE hConsoleOutput;
COORD Cursor = {x,y};
hConsoleOutput = GetStdHandle (STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hConsoleOutput, Cursor);
}

/* void loadgrid()
{
for (i=0; i<24; i++)
{
for (j=0; j<79; j++)
{
a[i][j]='.';
}
}
}*/

void printgrid()
{
for (i=0; i<24; i++)
{
for (j=0; j<79; j++)
{
cout<<a[i][j];
}
cout<<endl;
}
}

void main()
{

/* HANDLE hOut;

hOut = GetStdHandle(STD_OUTPUT_HANDLE);

SetConsoleTextAttribute(hOut, BACKGROUND_BLUE);*/


//loadgrid();
printgrid();

while (mx>0 && my>0)
{
if (kbhit())
{
keypress=getch(); //keypress=(char)getchar()
if ((keypress == right_key) || (keypress == left_key))
direction = keypress;
if (direction == 'a')
{
gotoxy(mx,my);
cout<<"@";
mx=mx-1;
gotoxy(mx,my);
cout<<"@";
gotoxy(mx,my);
}
if (direction == 'd')
{
gotoxy(mx,my);
cout<<" ";
mx=mx+1;
gotoxy(mx,my);
cout<<"@";
gotoxy(mx,my);
}
direction = ' ';
}
}



// cout << "NOTE: MAKE SURE ALL ENTERED LETTERS ARE LOWER CASE!!!!!!!";



}














@jimm78

Place
1
2
gotoxy(mx,my);
	cout<<"@";

after printgrid(); in the main function so that your character will appear before you press a key. Also

1
2
3
4
5
6
7
8
9
if (direction == 'a')
{
gotoxy(mx,my);
cout<<"@"; // Use a space here instead, like in direction == 'd' section
mx=mx-1;
gotoxy(mx,my);
cout<<"@";
gotoxy(mx,my);
}
Last edited on
There is still no change.
#include <iostream.h>
What decades-old compiler are you using?

void main()
main's return type should be int.

Works fine for me. Possibly you need an explicit flush, though.

1
2
3
4
5
6
7
8
9
10
11
#include <iomanip>
//...
            if (direction == 'a')
            {
                gotoxy(mx,my);
                cout<< ' ' << flush ; 
                mx=mx-1;
                gotoxy(mx,my);
                cout<< '@' << flush ;
                gotoxy(mx,my);
            }

Thanks cire now it works, only flush was needed. but i have to make a robot type figure out of characters and it has to move, how can i alot them different coordinates
Last edited on
What decades-old compiler are you using?

Jimm78, The only change I made was to correct the iostream.h, as CIRE pointed-out.

When running, it prints a line of "@"'s to the left,
and a single "@" to the right.

You may want to add some notation on the screen that the user should press the "A" (for left) and "D" (for Right) and (X) maybe to Exit- rather than presenting the user with a very blank screen to start.- But that's minor.

Sounding like you wish to Draw a Robot using "@" chars, you will want to have more control - starting with (a) retaining the "@" on the screen as you move to the Right, and (b) retaining AND deleting "@"'s under user control - more so than simply moving the cursor L & R.

Also, I see that entering the commands (A,D) in lower case is a requirement, you may want to check the values during entry to ensure that any upper case letters are converted to lower case before proceeding further into the program.- Although, again, that's minor since only the correct keys currently work.

Lastly, to draw a picture, you will have to move to additional lines.
This is fine if you only wish to move DOWN. I usually make mistakes, and so like to go back UP and fix any type-o's rather than having to start the entire program over again.

This, however, will entail a little more thought and planning - because you will likely need to place the entire picture of your robot - as you draw it - into a 2-d array. This really is not so difficult a task. You already have the "@" moving in a 1-d array- except they are being placed onto the screen rather than an array.

Define an array of CHARs - about 80 CHARs wide
a_robot_Line[79] = ".";

then as you print the "@"'s on the screen, also place them into your array

a_robot_Line[i_pos] = "@"; // Add a char
a_robot_Line[i_pos] = " "; // Erase a char

[i_pos] is just the counter of your current location within the row you are on.

-
Later you can add a 2nd dimension to your array, so that you can store,
not only all the 79 character positions of one line,
but "N" number of ROWS as well

a_robot_Line[25, 79] = ".";
or
a_robot_Line[ i-rows, i_wide] = ".";

I see, too, that you have a 2-d array defined, and a Load Grid and a Print Grid, you will now need to store your Row & Column data into that array with, maybe, a Save Grid subrt'n - because right now as the "@"'s are written to the screen, they are being overwritten and forgotten.


Lastly, always remember that spending 60% of your time to DESIGN your code means you'll only spend 15% of your time to FIX it !.




Last edited on
jimm78,
Also make sure that you also watch , and program, for your boundary positions.
meaning that as you move RIGHT (D)
RRRRRRRRRRRRR

and you decide to begin to move LEFT (A)
RRRRRRRRRLR

RRRRRRRRLLR

That the first time ( after moving RIGHT) you should not actually
move, but simply over wright the current location

RRRRRRRRRR
RRRRRRRRRL
RRRRRRRRLL

- and this is also true for the reverse.

As this is a special condition, you'll need a special check and a special subrt'n to control this condition.

Last edited on
// w32test01.cpp : Defines the entry point for the console application.
// // cout << "NOTE: MAKE SURE ALL ENTERED LETTERS ARE LOWER CASE!!!!!!!";

#include "stdafx.h"
#include <iostream>
#include<conio.h>
#include <windows.h>
using namespace std;

// char moveR;
// char moveL;
int mx=30;
int my=10;
int i, j;
char direction;
const char left_key='a', right_key='d', up_key='w', down_key='s';
char keypress;
char a[25][80];


void gotoxy(short x, short y)
{
HANDLE hConsoleOutput;
COORD Cursor = {x,y};
hConsoleOutput = GetStdHandle (STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hConsoleOutput, Cursor);
}

void loadgrid()
{
for (i=0; i<24; i++)
{
for (j=0; j<75; j++)
{
a[i][j]=' ';
}
}
}

void printgrid()
{
gotoxy(1,1); // re-sets the position to the Top Most Upper Left Corner position
cout<<"."; // Places a DOT here - later can be changed to a SPACE
for (i=0; i<24; i++)
{
for (j=0; j<75; j++)
{
cout<<a[i][j];
}
cout<<endl;
}
}

void main()
{
int ans = 0; // User Instructions
printf( " Press A-Left, D-Right, W-Up, S-Down \n\n" );
printf( " Enter a NUMBER to begin ...\n\n" );
scanf ("%d", &ans);

loadgrid();
printgrid();

while (mx>0 && my>0)
{
if (kbhit())
{
keypress=getch(); //keypress=(char)getchar()
if ((keypress == right_key) || (keypress == left_key) || (keypress == up_key) || (keypress == down_key) )
direction = keypress;

if (direction == 'a')
{
mx=mx-1;
a[my][mx]='L'; // row col
printgrid();
}


if (direction == 'd')
{
mx=mx+1;
a[my][mx]='R'; // row col
printgrid();
}
// ========================================= Code for UIp & DOWN

if (direction == 'w') // W= UP
{
my=my-1;
a[my][mx]='u'; // row col
printgrid();
}


if (direction == 's') // s = DOWN
{
my=my+1;
a[my][mx]='d'; // row col
printgrid();
}


direction = ' ';
}
}


} // EOF


i just can't make the characters of the robot to appear
having the same problem
how can i make the program from closing when the robot reaches the boundaries? my code now is,


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


int mx=30;
int my=10;
int i, j;
char direction;
const char left_key='a', right_key='d';
char keypress;
	
char grid[24][79];

	
void gotoxy(short x, short y)
{
     HANDLE hConsoleOutput;
     COORD Cursor = {x,y};
     hConsoleOutput = GetStdHandle (STD_OUTPUT_HANDLE);
     SetConsoleCursorPosition(hConsoleOutput, Cursor);
}
	

void printgrid()
{
     for (i=0; i<24; i++)
     {
		for (j=0; j<79; j++)
        {
			cout<<grid[i][j];
        }
        cout<<endl;
     }
}

#define VMAX 3

#define HMAX 3

 

void printRobot(char robot[][3],int x, int y);

void fillIn(int x,int y);

int main()
{
	int x,y;

//   clock_t pause = 50;

   char robot[VMAX][HMAX]={

      {'.','o','.'},

      {'-','¦','-'},

      {'/',' ','\\'}

      };

	
		
	HANDLE hOut;

	hOut = GetStdHandle(STD_OUTPUT_HANDLE);

	//SetConsoleTextAttribute(hOut, BACKGROUND_BLUE|
//BACKGROUND_INTENSITY);
	SetConsoleTextAttribute(hOut, BACKGROUND_GREEN|
    BACKGROUND_INTENSITY);
	

	//loadgrid();
	printgrid();
	gotoxy(mx,my);
    printRobot(robot,x,y);

	while (mx<70 && my<20 && my>0 && mx>0)
	{
      if (kbhit())
      {
            keypress=getch(); //keypress=(char)getchar()
            
			if ((keypress == right_key) || (keypress == left_key))
                 direction = keypress;
			
			
			if (direction == 'a')
                 {
                  gotoxy(mx,my);
                  cout<<" "<<flush;
                  
				  mx=mx-1;
                  gotoxy(mx,my);
                  
				  printRobot(robot,x,y);
				  fillIn(x,y);
                  gotoxy(mx,my);
                  }
			
			
			if (direction == 'd')
                  {
                  gotoxy(mx,my);
                  cout<<" "<<flush;
                  
				  mx=mx+1;
                  gotoxy(mx,my);
                  printRobot(robot,x,y);
                  fillIn(x,y);
				  gotoxy(mx,my);
                  }
			
                  
			direction = ' ';
      }
	}
	
				


	//	cout << "NOTE: MAKE SURE ALL ENTERED LETTERS ARE LOWER CASE!!!!!!!";
		
		
return 0;
}



		
		
void printRobot(char robot[][3],int x, int y) {

   int r,c;

    

   for(c=0,r=2;c<HMAX;c++)

      cout<<robot[r][c]<<flush;

   gotoxy(x,y-1);

   for(c=0,r=1;c<HMAX;c++)  

      cout<<robot[r][c]<<flush;

   gotoxy(x,y-2);

   for(c=0,r=0;c<HMAX;c++)

      cout<<robot[r][c]<<flush;

}

void fillIn(int x,int y) {

   int i;

	 for(i=VMAX;i>-1;i--) {

      gotoxy(x,y-i);
      cout<<"   "<<flush;

   }

}

		
		
		
		

	

	
@jimm78

how can i make the program from closing when the robot reaches the boundaries?


The best way would be to check first if you're still in boundaries, BEFORE you move the robot.
example..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
if (direction == 'a')
{
     if(mx-1 >=0)
{
        gotoxy(mx,my);
          cout<<" "<<flush;
	  mx=mx-1;
          gotoxy(mx,my);
     
	  printRobot(robot,x,y);
	  fillIn(x,y);
         gotoxy(mx,my);
}
}
Topic archived. No new replies allowed.