# C++ easy understand solution with comments

• ``````class SnakeGame {
public:
/** Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */
SnakeGame(int width, int height, vector<pair<int, int>> food) {
body.push_back(make_pair(0,0));
_food=food;
_width=width;
_height=height;

// food index
foodindx=0;
}

/** Moves the snake.
@param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
@return The game's score after the move. Return -1 if game over.
Game over when snake crosses the screen boundary or bites its body. */
int move(string direction) {
// food coordinates initilization
int food_x=-1;
int food_y=-1;
// if food exist,record current food coordinates
if(_food.size()!=0){
food_x= _food[foodindx].first;
food_y=_food[foodindx].second;
}

if(direction=="U")
else if(direction=="L")
else if(direction=="R")
else if(direction=="D")

// check head if out boundary
return -1;
// check if snake can eat food
foodindx++;
}
// no food, just update snake body
else{
body.pop_back();
return -1;
}
}
return body.size()-1;
}
// helper function: check head if is out boundary
bool outBoundary(int x,int y){
if(x>=0&&x<_height&&y>=0&&y<_width)
return false;
return true;
}
//helper function: check snake if bite itself.
bool biteItself(int x,int y){
auto iter=find(body.begin(),body.end(),make_pair(x,y));
if(iter!=body.end())
return true;
return false;
}
private:
vector<pair<int,int>>body;
int _width;
int _height;