snakeplusplus/src/snake.cpp

57 lines
1.2 KiB
C++
Raw Normal View History

// Snake.cpp
#include <queue>
#include <SFML/Graphics.hpp>
#include "common.h"
#include "snake.h"
2023-03-12 08:50:50 -05:00
// General constructor for snake class
Snake::Snake(void)
2023-03-12 08:50:50 -05:00
{
2023-03-17 20:13:50 -05:00
CreateNewHead(sf::Vector2f(4,5));
2023-03-12 08:50:50 -05:00
return;
}
2023-03-17 20:13:50 -05:00
// Move snake based on direction and check for collision
sf::Vector2f Snake::MoveSnake(void)
{
2023-03-17 20:13:50 -05:00
sf::Vector2f newHeadPosition;
newHeadPosition = CalculateNewHead();
CreateNewHead(newHeadPosition);
return newHeadPosition;
}
2023-03-17 20:13:50 -05:00
// Removes tail of snake
// Returns the location of the tail
sf::Vector2f Snake::Pop(void)
{
2023-03-17 20:13:50 -05:00
sf::Vector2f tailLocation = snakeBody.front();
snakeBody.pop();
return tailLocation;
}
void Snake::UpdateDirection(int newDirection)
{
snakeDirection = newDirection;
return;
}
// Get a new coordinate position based on snake direction
2023-03-17 20:13:50 -05:00
sf::Vector2f Snake::CalculateNewHead(void)
{
2023-03-17 20:13:50 -05:00
sf::Vector2f position = snakeBody.back();
if (snakeDirection == kLeft)
2023-03-17 20:13:50 -05:00
position.x -= 1;
if (snakeDirection == kUp)
2023-03-17 20:13:50 -05:00
position.y -= 1;
if (snakeDirection == kDown)
2023-03-17 20:13:50 -05:00
position.y += 1;
if (snakeDirection == kRight)
2023-03-17 20:13:50 -05:00
position.x += 1;
}
2023-03-17 20:13:50 -05:00
void Snake::CreateNewHead(sf::Vector2f headLocation)
{
2023-03-17 20:13:50 -05:00
snakeBody.push(headLocation);
return;
}