2022-08-15 23:51:18 -05:00
|
|
|
// Snake.cpp
|
2022-08-21 02:51:33 -05:00
|
|
|
#include <queue>
|
2023-03-17 17:27:02 -05:00
|
|
|
#include <SFML/Graphics.hpp>
|
2023-03-13 21:10:52 -05:00
|
|
|
#include "common.h"
|
|
|
|
#include "snake.h"
|
2022-07-25 15:40:45 -05:00
|
|
|
|
2023-03-12 08:50:50 -05:00
|
|
|
// General constructor for snake class
|
2023-03-12 21:57:46 -05:00
|
|
|
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)
|
2022-07-25 15:40:45 -05:00
|
|
|
{
|
2023-03-17 20:13:50 -05:00
|
|
|
sf::Vector2f newHeadPosition;
|
|
|
|
newHeadPosition = CalculateNewHead();
|
|
|
|
CreateNewHead(newHeadPosition);
|
|
|
|
return newHeadPosition;
|
2022-07-26 19:47:08 -05:00
|
|
|
}
|
|
|
|
|
2023-03-17 20:13:50 -05:00
|
|
|
// Removes tail of snake
|
|
|
|
// Returns the location of the tail
|
|
|
|
sf::Vector2f Snake::Pop(void)
|
2022-07-26 19:47:08 -05:00
|
|
|
{
|
2023-03-17 20:13:50 -05:00
|
|
|
sf::Vector2f tailLocation = snakeBody.front();
|
|
|
|
snakeBody.pop();
|
|
|
|
return tailLocation;
|
2022-07-25 16:12:11 -05:00
|
|
|
}
|
|
|
|
|
2023-03-12 21:57:46 -05:00
|
|
|
void Snake::UpdateDirection(int newDirection)
|
2022-07-26 16:56:26 -05:00
|
|
|
{
|
2023-03-12 21:57:46 -05:00
|
|
|
snakeDirection = newDirection;
|
|
|
|
return;
|
2022-07-26 16:56:26 -05:00
|
|
|
}
|
|
|
|
|
2023-03-12 21:57:46 -05:00
|
|
|
// Get a new coordinate position based on snake direction
|
2023-03-17 20:13:50 -05:00
|
|
|
sf::Vector2f Snake::CalculateNewHead(void)
|
2022-07-26 19:03:55 -05:00
|
|
|
{
|
2023-03-17 20:13:50 -05:00
|
|
|
sf::Vector2f position = snakeBody.back();
|
2023-03-12 21:57:46 -05:00
|
|
|
if (snakeDirection == kLeft)
|
2023-03-17 20:13:50 -05:00
|
|
|
position.x -= 1;
|
2023-03-12 21:57:46 -05:00
|
|
|
if (snakeDirection == kUp)
|
2023-03-17 20:13:50 -05:00
|
|
|
position.y -= 1;
|
2023-03-12 21:57:46 -05:00
|
|
|
if (snakeDirection == kDown)
|
2023-03-17 20:13:50 -05:00
|
|
|
position.y += 1;
|
2023-03-12 21:57:46 -05:00
|
|
|
if (snakeDirection == kRight)
|
2023-03-17 20:13:50 -05:00
|
|
|
position.x += 1;
|
2023-03-13 08:24:56 -05:00
|
|
|
}
|
|
|
|
|
2023-03-17 20:13:50 -05:00
|
|
|
void Snake::CreateNewHead(sf::Vector2f headLocation)
|
2022-08-15 23:51:18 -05:00
|
|
|
{
|
2023-03-17 20:13:50 -05:00
|
|
|
snakeBody.push(headLocation);
|
|
|
|
return;
|
2022-07-26 16:56:26 -05:00
|
|
|
}
|