c++ - I would like to ignore a user's input if they go out-of-bounds -
i tried looking answer question couldn't find quite right.
my problem deals having array set , moving little cursor around field of dots. need able ignore user's input if hit arrow key in direction take them out of bounds of grid. i'm not sure best this.
this class cannot modify. can inherit this.
//you can add or delete includes #include <iostream> #include <stdlib.h> //for system() #include <conio.h> //for getche() #include <time.h> using namespace std; const int max_height = 20; //the height of grid const int max_width = 40; //the width of grid class pickupgame { protected: char screen[max_height][max_width]; //the grid print screen int xpos, ypos; //the current x , y position of users cursor on grid public: //constructor intialize screen , x , y positions pickupgame() : xpos(0), ypos(max_width - 1) { setupscreen(); //initalize grid } //initialize screen '.' characters , set intial user cursor position on grid void setupscreen() { for(int height = 0; height < max_height; height++) { for(int width = 0; width < max_width; width++) { screen[height][width] = '.'; //initialize each grid position } } screen[xpos][ypos] = '<'; //set users initial cursor position } //print grid screen void print() { for(int height = 0; height < max_height; height++) { for(int width = 0; width < max_width; width++) { cout << screen[height][width]; //print character @ location in grid } cout << endl; //after each row printed, print newline character } } //take in user input move around grid void move(char direction) { switch(static_cast<int>(direction)) //don't know ascii characters arrow keys use ascii numbers { case 72: //up arrow screen[xpos][ypos] = ' '; //wipe out users current cursor xpos--; //move users x position on grid screen[xpos][ypos] = '^'; //move users cursor break; case 80: //down arrow screen[xpos][ypos] = ' '; xpos++; screen[xpos][ypos] = 'v'; break; case 75: //left arrow screen[xpos][ypos] = ' '; ypos--; screen[xpos][ypos] = '<'; break; case 77: //right arrow screen[xpos][ypos] = ' '; ypos++; screen[xpos][ypos] = '>'; break; } } };
you need check whether movement take them outside bounds , ignore if so. example, moving right:
if (right_key_pressed() && x_position < max_x_value) { x_position++; } that is, move right if press → key , not yet @ maximum x position value. can apply similar logic other directions.
edit after addition of pickupgame class question
since movement logic in pickupgame , you're not allowed modify it, makes little bit annoying. ideally if statements inside move check bounds. instead, you're going have check outside call move:
if ((direction == 72 && xpos > 0) || /* same right, down, , left */) { move(direction); } so want check if direction , there room move up, or if right , there room move right, or... , on. , pass direction along move.
Comments
Post a Comment