Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a class object based on two variables C++

Tags:

c++

class

I need help with a problem pertaining to classes. I know how to solve it but I am wondering if there is a better solution than my current idea.

Each Class Tile Object and Class Player Object has an x and y position. I would like to know if there is a way to expedite things. My current idea is if-else statements like this:

if(x==1) {
    if(y==1) {

       return tileone1;

    } else if(y==2) {  

       return tileone2;

    } else if(y==3) {  

       return tileone3;

    } else if(y==4) {  

       return tileone4;

    } else if(y==5) {  

       return tileone5;

    } //......

} else if(x==2) { 
      if(y==1) {

       return tiletwo1;

    } else if(y==2) {  

       return tiletwo2;

    } else if(y==3) {  

       return tiletwo3;

    } else if(y==4) {  

       return tiletwo4;

    } else if(y==5) {  

       return tiletwo5;

    } //......
} //......

The problem is it would take way too long to write this for every tile.

I need a function that will return a Tile object based on the x and y input of the Object Player. Any other solution would be great as well.

Tile getTileBasedOnCoords(int x, int y){

}
like image 891
Macta Man Avatar asked Jul 21 '26 02:07

Macta Man


1 Answers

There are multiple ways to achieve this. The easiest seems to be (given the question) is by putting all Tile objects into the array, and returning the one with corresponding index.

like image 85
SergeyA Avatar answered Jul 22 '26 14:07

SergeyA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!