C++ Game Map wall crashes .. Help pls | SoloLearn: Learn to code for FREE!


C++ Game Map wall crashes .. Help pls

I'm currently building a mars rover game collecting gold for my uni assignment, but sadly I'm facing a problem, when the rover hit the down wall, the game crashes I mean the game ends .. can somebody check my code and give me ideas ? thank you https://code.sololearn.com/cA19A13a3a9a

3/3/2021 11:32:47 AM

Sky Yogash Shri

3 Answers

New Answer


I haven't read all of your code but your Mars::isGold, isTrap, isInsideMap, isEmpty, setObject and getObject don't seem to be implemented correctly. In most of these functions if y == 0 then dimY will be equal to dimY and accessing an array of size n like arr[n] is outside of its boundaries. getObject doesn't even use the y parameter. Are you sure don't just want to do something like map[y][x]? If your y coordinate is flipped then you should use map[dimY-y-1][x] instead. To check if a coordinate is inside a 2d array you should check if x/y >= 0 and < size but inside isInsideMap you're checking for x/y > 0 and <= size which would think that the most top and left side is outside the map and that 1 outside the bottom and right side is inside the map ( which would be out of bounds ). You can replace the subscript operators with the .at function instead and you'll see that it throws an out of bounds exception when you try to go outside the bottom of the map. Also if your y coordinate isn't flipped then your '^' and 'v' movement is going the wrong way. It should be y-1 for '^' and y+1 for 'v'. y == 0 is up, y == size - 1 is down. Hope it helps. :)


Yea, that function is correct. But you can shorten it to return x >= 0 && x < dimX && y >= 0 && y < dimY; Whenever you have a structure like: if( expr ) return true; else return false; You can just replace it with return expr; You most likely had/have an out of bounds on the right side as well, it's just that going outside the boundary of the x coordinate is less likely to crash because you often allocate more memory than you ask for so you're less likely to hit memory regions that isn't allocated.


Hi Mr .dennis, thanks for the answer, appreciate it so much. my rover's heading isn't upside down plus I don't really get your explanation about how to bound inside the boundary. could you please check this? sorry, i just started c++ 2 months ago, pls guide me. bool Map::isInsideMap(int x, int y) { bool inside = true ; if((x>=0 && x < dimX) && (y >=0 && y < dimY )) return true ; //inside else return false ; //outsid }