snakeplusplus/src/GameState.cpp

91 lines
2.3 KiB
C++
Raw Normal View History

// GameState.cpp
#include <SFML\Graphics.hpp>
#include <SFML\System.hpp>
#include "Common.h"
#include "Snake.h"
#include "GameState.h"
GameState::GameState()
{
delay = sf::milliseconds(75);
gameVideoSettings = sf::VideoMode(1025, 725);
2023-03-12 08:50:50 -05:00
gameWindow.create(gameVideoSettings, "SnakePlusPlus");
return;
}
2023-03-12 08:50:50 -05:00
GameState::GameState(int maxHorizontal, int maxVertical)
{
delay = sf::milliseconds(75);
2023-03-12 08:50:50 -05:00
gameVideoSettings = sf::VideoMode(maxHorizontal, maxVertical);
gameWindow.create(gameVideoSettings, "SnakePlusPlus");
return;
}
2023-03-12 08:50:50 -05:00
void GameState::StartGame()
{
2023-03-12 08:50:50 -05:00
gameWindow.create(gameVideoSettings, "SnakePlusPlus");
Snake player(sf::Vector2f(kGridSize,kGridSize));
SnakeFood playerFood(sf::Vector2f(kGridSize,kGridSize));
RunGameLoop();
return;
2023-03-12 08:50:50 -05:00
}
sf::Vector2f GameState::GetGameBoundaries(void)
{
sf::Vector2f boundaries;
boundaries.x = gameVideoSettings.width;
boundaries.y = gameVideoSettings.height;
return boundaries;
}
void GameState::GetKeyboardInput(void)
{
sf::Event event;
while (gameWindow.pollEvent(event))
{
if ((event.type == sf::Event::Closed) ||
(sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)))
gameWindow.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
player.UpdateDirection(kLeft);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
player.UpdateDirection(kUp);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
player.UpdateDirection(kDown);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
player.UpdateDirection(kRight);
return;
}
2023-03-12 08:50:50 -05:00
// Generates new food until not colliding with player
void GameState::RegenerateFood(void)
{
// Keep making new food until generating a valid spot
while (player.IsTouchingObject(playerFood.GetFoodObject()))
playerFood.GenerateNewFood(GetGameBoundaries());
return;
}
2023-03-12 08:50:50 -05:00
void GameState::RunGameLoop(void)
{
while (gameWindow.isOpen())
{
GetKeyboardInput();
player.MoveSnake(&playerFood);
2023-03-12 08:50:50 -05:00
RegenerateFood();
RenderWindow();
sf::sleep(delay);
}
return;
}
2023-03-12 08:50:50 -05:00
void GameState::RenderWindow(void)
{
gameWindow.clear();
player.DisplaySnake(gameWindow);
gameWindow.draw(playerFood.GetFoodObject());
gameWindow.display();
return;
2023-03-12 08:50:50 -05:00
}