Code: Select all
Snake::Snake(const Location& loc)
{
constexpr int nBodyColors = 4;
constexpr Color SnakeColor[nBodyColors] =
{
{10, 100, 32},
{10, 130, 48},
{18, 160, 48},
{10, 130, 48}
};
for (int i = 0; i < nSegmentsMax; i++)
{
segements[i].InitBody(SnakeColor[i % nBodyColors]);
}
segements[0].InitHead(loc);
}
void Snake::MoveBy(const Location& delta_loc)
{
for (int i = nSegments - 1; i > 0; --i)
{
segements[i].Follow(segements[i - 1]);
}
segements[0].MoveBy(delta_loc);
}
void Snake::Grow()
{
if (nSegments < nSegmentsMax)
{
nSegments++;
}
}
void Snake::Draw(Board& board) const
{
for (int i = 0; i < nSegments; ++i)
{
segements[i].Draw(board);
}
}
bool Snake::SnakeInTile(const Location& target)const
{
for (int i = 0; i < nSegments - 1; ++i)
{
if (segements[i].GetLocation() == target)
{
return true;
}
}
return false;
}
bool Snake::SnakeIsColliding(const Location& target)const
{
for (int i = 0; i < nSegments - 1; ++i)
{
if (segements[i].GetLocation() == target)
{
return true;
}
}
return false;
}
Location& Snake::GetHead(const Location& delta_loc) const
{
Location l(segements[0].GetLocation());
l.Add(delta_loc);
return l;
}
void Snake::Segement::InitHead(const Location& in_loc)
{
loc = in_loc;
c = Snake::HeadColor;
}
void Snake::Segement::InitBody(Color c_in)
{
c = c_in;
}
void Snake::Segement::Follow(const Segement& next)
{
loc = next.loc;
}
void Snake::Segement::MoveBy(const Location& delta_loc)
{
assert(abs(delta_loc.x) + abs(delta_loc.y) == 1);
loc.Add(delta_loc);
}
void Snake::Segement::Draw(Board& board) const
{
board.DrawCell(loc, c);
}
const Location& Snake::Segement::GetLocation()const
{
return loc;
}