refactor: merge final cleanups before working on AI #6

Merged
Trianta merged 12 commits from refactor into master 2024-08-10 15:05:56 -05:00
13 changed files with 719 additions and 640 deletions

1
.gitignore vendored
View File

@ -49,3 +49,4 @@ build
# Extras # Extras
.vs* .vs*
.cache

View File

@ -4,7 +4,7 @@ project(
snakeplusplus snakeplusplus
LANGUAGES CXX) LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11 CACHE STRING "The C++ standard to use") set(CMAKE_CXX_STANDARD 23 CACHE STRING "The C++ standard to use")
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_EXTENSIONS OFF)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin) set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)

View File

@ -1,5 +1,6 @@
#include "botinterface.hpp" #include "botinterface.hpp"
#include "common.hpp" #include "common.hpp"
#include "gamestate.hpp"
#include <array> #include <array>
#include <cstdlib> #include <cstdlib>
#include <iostream> #include <iostream>
@ -7,8 +8,6 @@
#include <stdexcept> #include <stdexcept>
#include <SFML/System/Vector2.hpp> #include <SFML/System/Vector2.hpp>
namespace snakeplusplus
{
PlayerDirection lastKnownDirection = kNone; PlayerDirection lastKnownDirection = kNone;
AISnake::AISnake() { AISnake::AISnake() {
@ -18,8 +17,10 @@ namespace snakeplusplus
PlayerDirection AISnake::GetInput(const sf::Vector2f* source) PlayerDirection AISnake::GetInput(const sf::Vector2f* source)
{ {
sf::Vector2f directionDelta; sf::Vector2f directionDelta;
if (*source == path.top()) { path.pop(); } if (!source)
if (path.empty()) { return kUp; } // Snake is trapped return kUp;
while (*source == path.top() && !path.empty()) { path.pop(); }
if (path.empty()) { path.push(GetAnyOpenPath(*source)); }
directionDelta = *source - path.top(); directionDelta = *source - path.top();
path.pop(); path.pop();
if ((directionDelta.y == 1) if ((directionDelta.y == 1)
@ -48,53 +49,55 @@ namespace snakeplusplus
probabilityBFS += amount; probabilityBFS += amount;
if (probabilityBFS > 1.0) { probabilityBFS = 1.0; } if (probabilityBFS > 1.0) { probabilityBFS = 1.0; }
if (probabilityBFS < 0.0) { probabilityBFS = 0.0; } if (probabilityBFS < 0.0) { probabilityBFS = 0.0; }
std::cout << "[Info - AISnake] New BFS probability: " << probabilityBFS << std::endl;
return; return;
} }
void AISnake::AddIteration(const int size)
{
if (size > 40)
{
UpdateAverage(size);
double adjustmentAmount = 0.002;
if (average > size) { AdjustProbability(adjustmentAmount); }
else { AdjustProbability(-adjustmentAmount); }
}
std::cout << "[LOG - AI] Current average: " << average << std::endl;
std::cout << "[LOG - AI] Previous iteration size: " << size << std::endl;
}
void AISnake::ResetPath(void) {
while (!path.empty()) { path.pop(); }
}
// Gets a new path for the bot to follow // Gets a new path for the bot to follow
// Uses DFS algorithm // Uses DFS algorithm
void AISnake::GetNewPath(const std::vector< std::vector<char> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries, const int snakeSize) void AISnake::GetNewPath(const sf::Vector2f& source)
{ {
// Search for food // Search for food
/*
BFS(gameBoard, source, boundaries);
if (gameBoard[botPathUnsanitized.top().y][botPathUnsanitized.top().x] != 'X') {
while (!botPathUnsanitized.empty()) { botPathUnsanitized.pop(); }
DFS(gameBoard, source, boundaries);
while (botPathUnsanitized.size() > 15) { botPathUnsanitized.pop(); }
}
*/
// Probability-based approach for fun // Probability-based approach for fun
double roll = ((double) GenerateRandomNumber(RAND_MAX)) / ((double) RAND_MAX); double roll = ((double) GenerateRandomNumber(RAND_MAX)) / ((double) RAND_MAX);
if (roll <= probabilityBFS) { BFS(gameBoard, source, boundaries); } if (roll <= probabilityBFS) { BFS(source); }
else { DFS(gameBoard, source, boundaries); } else { DFS(source); }
// Create path for food UnvisitBoard();
path.push(botPathUnsanitized.top()); if (pathFailed) {
botPathUnsanitized.pop(); pathFailed = false;
while (!botPathUnsanitized.empty()) { EmptyPath();
sf::Vector2f deltaVector = botPathUnsanitized.top() - path.top(); path.push(GetAnyOpenPath(source));
int delta = abs(deltaVector.x) + abs(deltaVector.y); } else {
if (delta == 1) { TrimPath();
path.push(botPathUnsanitized.top()); if (path.empty())
} path.push(GetAnyOpenPath(source));
botPathUnsanitized.pop();
} }
} }
void AISnake::BFS(const std::vector< std::vector<char> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries) { void AISnake::BFS(const sf::Vector2f& source) {
std::queue<sf::Vector2f> search; std::queue<sf::Vector2f> search;
std::vector<std::vector<bool>> visited(boundaries.y, std::vector<bool> (boundaries.x, false));
bool foodFound = false;
search.push(source); search.push(source);
while (!search.empty()) { while (!search.empty()) {
sf::Vector2f currentLocation = search.front(); sf::Vector2f currentLocation = search.front();
search.pop(); search.pop();
if (foodFound) { break; } if (g_pEngine->gameBoard.at(currentLocation.y).at(currentLocation.x).m_bVisited)
if (visited.at(currentLocation.y).at(currentLocation.x)) { continue; } continue;
if (gameBoard.at(currentLocation.y).at(currentLocation.x) == 'X') {
foodFound = true;
}
botPathUnsanitized.push(currentLocation); botPathUnsanitized.push(currentLocation);
std::array<sf::Vector2f, 4> localLocations; std::array<sf::Vector2f, 4> localLocations;
localLocations.fill(currentLocation); localLocations.fill(currentLocation);
@ -102,77 +105,120 @@ namespace snakeplusplus
localLocations[1].x += 1; localLocations[1].x += 1;
localLocations[2].y -= 1; localLocations[2].y -= 1;
localLocations[3].x -= 1; localLocations[3].x -= 1;
for (auto i : localLocations) { for (sf::Vector2f nearby : localLocations) {
try { try {
if (gameBoard.at(i.y).at(i.x) == 'X') { GameSpace* space = &g_pEngine->gameBoard.at(nearby.y).at(nearby.x);
botPathUnsanitized.push(i); if (space->m_bFood) {
foodFound = true; botPathUnsanitized.push(nearby);
return;
} }
if (nearby.x < 1 || nearby.y < 1)
continue;
if (space->m_bVisited)
continue;
if (space->m_bSnake)
continue;
search.push(nearby);
} catch (const std::out_of_range& error) { } catch (const std::out_of_range& error) {
continue; // Out of bounds continue; // Out of bounds
} }
} }
for (sf::Vector2f newLocation : localLocations) { g_pEngine->gameBoard.at(currentLocation.y).at(currentLocation.x).m_bVisited = true;
try {
if ((!visited.at(newLocation.y).at(newLocation.x))
&& (gameBoard.at(newLocation.y).at(newLocation.x) == ' ')) {
search.push(newLocation);
}
} catch (const std::out_of_range& error) {
continue; // Out of bounds
}
}
visited.at(currentLocation.y).at(currentLocation.x) = true;
} }
pathFailed = true;
} }
void AISnake::DFS(const std::vector< std::vector<char> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries) { void AISnake::DFS(const sf::Vector2f& source) {
std::stack<sf::Vector2f> search; std::stack<sf::Vector2f> search;
std::vector<std::vector<bool>> visited(boundaries.y, std::vector<bool> (boundaries.x, false));
bool foodFound = false;
search.push(source); search.push(source);
while (!search.empty()) { while (!search.empty()) {
sf::Vector2f currentLocation = search.top(); sf::Vector2f currentLocation = search.top();
search.pop(); search.pop();
if (foodFound) { break; } if (g_pEngine->gameBoard.at(currentLocation.y).at(currentLocation.x).m_bVisited)
if (visited.at(currentLocation.y).at(currentLocation.x)) { continue; } continue;
if (gameBoard.at(currentLocation.y).at(currentLocation.x) == 'X') {
foodFound = true;
}
botPathUnsanitized.push(currentLocation); botPathUnsanitized.push(currentLocation);
std::array<sf::Vector2f, 4> localLocations; std::array<sf::Vector2f, 4> localLocations;
localLocations.fill(currentLocation); localLocations.fill(currentLocation);
localLocations[0].y += 1; localLocations.at(0).y += 1;
localLocations[1].x += 1; localLocations.at(1).x += 1;
localLocations[2].y -= 1; localLocations.at(2).y -= 1;
localLocations[3].x -= 1; localLocations.at(3).x -= 1;
for (auto i : localLocations) { for (sf::Vector2f nearby : localLocations) {
try { try {
if (gameBoard.at(i.y).at(i.x) == 'X') { GameSpace* space = &g_pEngine->gameBoard.at(nearby.y).at(nearby.x);
botPathUnsanitized.push(i); if (space->m_bFood) {
foodFound = true; botPathUnsanitized.push(nearby);
return;
} }
} catch (const std::out_of_range& error) { if (nearby.x < 1 || nearby.x > g_pEngine->GetGameBoundaries().x - 2)
continue; // Out of bounds
}
}
for (sf::Vector2f newLocation : localLocations) {
try {
if (newLocation.x < 1 || newLocation.y < 1
|| newLocation.x > boundaries.x - 2
|| newLocation.y > boundaries.y - 2) {
continue; continue;
if (space->m_bVisited)
} continue;
if ((!visited.at(newLocation.y).at(newLocation.x)) if (space->m_bSnake)
&& (gameBoard.at(newLocation.y).at(newLocation.x) == ' ')) { continue;
search.push(newLocation); search.push(nearby);
}
} catch (const std::out_of_range& error) { } catch (const std::out_of_range& error) {
continue; // Out of bounds continue; // Out of bounds
} }
} }
visited.at(currentLocation.y).at(currentLocation.x) = true; g_pEngine->gameBoard.at(currentLocation.y).at(currentLocation.x).m_bVisited = true;
}
pathFailed = true;
}
sf::Vector2f AISnake::GetAnyOpenPath(const sf::Vector2f& source) {
sf::Vector2f bail;
std::array<sf::Vector2f, 4> paths;
paths.fill(source);
paths[0].x -= 1;
paths[1].x += 1;
paths[2].y -= 1;
paths[3].y += 1;
for (auto path : paths) {
try {
bail = path;
if (g_pEngine->gameBoard.at(path.y).at(path.x).m_bSnake)
continue;
return path;
} catch (const std::out_of_range& error) {
continue; // Out of bounds
} }
} }
return bail; // Snake is trapped, give up and die
}
void AISnake::UnvisitBoard(void) {
for (std::vector<GameSpace>& i : g_pEngine->gameBoard)
for (GameSpace& j : i)
j.m_bVisited = false;
}
void AISnake::UpdateAverage(const int size) {
totalLength += size;
amountPlayed += 1;
average = (double)totalLength / amountPlayed;
}
void AISnake::TrimPath(void) {
bool reachedSnake = false;
path.push(botPathUnsanitized.top()); // Push food location
while (!botPathUnsanitized.empty()) {
if (!reachedSnake) {
sf::Vector2f location = botPathUnsanitized.top();
if (g_pEngine->gameBoard[location.y][location.x].m_bSnake)
reachedSnake = true;
sf::Vector2f deltaVector = location - path.top();
int delta = abs(deltaVector.x) + abs(deltaVector.y);
if (delta == 1)
path.push(location);
}
botPathUnsanitized.pop();
}
}
void AISnake::EmptyPath(void) {
while (!botPathUnsanitized.empty())
botPathUnsanitized.pop();
} }

View File

@ -3,25 +3,32 @@
#include "common.hpp" #include "common.hpp"
#include <stack> #include <stack>
#include <vector>
#include <SFML/System/Vector2.hpp> #include <SFML/System/Vector2.hpp>
namespace snakeplusplus
{
class AISnake { class AISnake {
public: public:
std::stack<sf::Vector2f> path; std::stack<sf::Vector2f> path;
AISnake(); AISnake();
void GetNewPath(const std::vector< std::vector<char> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries, const int snakeSize); void GetNewPath(const sf::Vector2f& source);
PlayerDirection GetInput(const sf::Vector2f* source); PlayerDirection GetInput(const sf::Vector2f* source);
void UpdateProbability(int snakeSize); void UpdateProbability(int snakeSize);
void AdjustProbability(double amount); void AdjustProbability(double amount);
void AddIteration(const int size);
void ResetPath(void);
int amountPlayed = 0;
private: private:
double probabilityBFS = 0.500; int totalLength = 0;
double average = 0;
double probabilityBFS = 0.800;
bool pathFailed = false;
std::stack<sf::Vector2f> botPathUnsanitized; std::stack<sf::Vector2f> botPathUnsanitized;
void BFS(const std::vector< std::vector<char> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries); void BFS(const sf::Vector2f& source);
void DFS(const std::vector< std::vector<char> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries); void DFS(const sf::Vector2f& source);
sf::Vector2f GetAnyOpenPath(const sf::Vector2f& source);
void UnvisitBoard(void);
void UpdateAverage(const int size);
void TrimPath(void);
void EmptyPath(void);
}; };
}
#endif #endif

View File

@ -2,8 +2,6 @@
#include <random> #include <random>
#include "common.hpp" #include "common.hpp"
namespace snakeplusplus
{
std::default_random_engine generator; std::default_random_engine generator;
void InitializeGenerator(void) void InitializeGenerator(void)
{ {
@ -15,7 +13,16 @@ namespace snakeplusplus
{ {
int generatedNumber; int generatedNumber;
std::uniform_int_distribution<> distribution(0, generationLimit - 1); std::uniform_int_distribution<> distribution(0, generationLimit - 1);
generatedNumber = distribution(snakeplusplus::generator); generatedNumber = distribution(generator);
return generatedNumber; return generatedNumber;
} }
GameSpace::GameSpace(void) {
Reset();
}
void GameSpace::Reset(void) {
m_bFood = 0;
m_bSnake = 0;
m_bVisited = 0;
} }

View File

@ -1,8 +1,6 @@
#ifndef COMMON_HPP #ifndef COMMON_HPP
#define COMMON_HPP #define COMMON_HPP
namespace snakeplusplus
{
void InitializeGenerator(void); void InitializeGenerator(void);
int GenerateRandomNumber(int generationLimit); int GenerateRandomNumber(int generationLimit);
@ -15,6 +13,17 @@ namespace snakeplusplus
kRight = 4 kRight = 4
}; };
} struct GameSpace {
GameSpace();
unsigned char m_bFood : 1 = 0;
unsigned char m_bSnake : 1 = 0;
unsigned char m_bVisited : 1 = 0; // Used for BFS/DFS
unsigned char _3 : 1 = 0;
unsigned char _4 : 1 = 0;
unsigned char _5 : 1 = 0;
unsigned char _6 : 1 = 0;
unsigned char _7 : 1 = 0;
void Reset(void);
};
#endif #endif

View File

@ -1,5 +1,4 @@
// GameState.cpp // GameState.cpp
#include <iostream>
#include <stdexcept> #include <stdexcept>
#include <SFML/Graphics.hpp> #include <SFML/Graphics.hpp>
#include "botinterface.hpp" #include "botinterface.hpp"
@ -7,8 +6,6 @@
#include "playerinterface.hpp" #include "playerinterface.hpp"
#include "gamestate.hpp" #include "gamestate.hpp"
namespace snakeplusplus
{
GameEngine::GameEngine() GameEngine::GameEngine()
{ {
InitializeGenerator(); InitializeGenerator();
@ -18,6 +15,7 @@ namespace snakeplusplus
void GameEngine::Start() void GameEngine::Start()
{ {
PrepareGameBoard(); PrepareGameBoard();
if (!state.m_bNoDisplay)
graphics.StartGameWindow(); graphics.StartGameWindow();
Loop(); Loop();
return; return;
@ -25,41 +23,33 @@ namespace snakeplusplus
void GameEngine::Reset() void GameEngine::Reset()
{ {
AddIteration(); if (!state.m_bIsBotControlled)
graphics.CheckContinue();
else
bot.AddIteration(player.body.size());
player.Reset(); player.Reset();
if (isBotControlled) { while (!bot.path.empty()) { bot.path.pop(); } }
PrepareGameBoard(); PrepareGameBoard();
isGameOver = false; state.m_bIsGameOver = false;
graphics.SetShowGame((amountPlayed + 1) % 50 == 0); if (state.m_bIsBotControlled) {
return; while (!bot.path.empty())
bot.path.pop();
if (state.m_bNoDisplay)
graphics.SetShowGame(false);
graphics.SetShowGame((bot.amountPlayed + 1) % 50 == 0);
} }
void GameEngine::AddIteration(void)
{
graphics.CheckContinue(isBotControlled);
if (player.body.size() > 40)
{
UpdateAverage();
double adjustmentAmount = 0.002;
if (average > player.body.size()) { bot.AdjustProbability(adjustmentAmount); }
else { bot.AdjustProbability(-adjustmentAmount); }
}
std::cout << "[Info - GameEngine] Current average: " << average << std::endl;
std::cout << "[Info - GameEngine] Previous iteration size: " << player.body.size() << std::endl;
} }
void GameEngine::Loop(void) void GameEngine::Loop(void)
{ {
int currentScore = 0; int currentScore = 0;
while (graphics.IsOpen()) while (graphics.IsOpen() || state.m_bNoDisplay)
{ {
if (isGameOver) { Reset(); } if (state.m_bIsGameOver) { Reset(); }
UpdatePlayerSpeed(); UpdatePlayerSpeed();
PlaceNewSnakePart(MovePlayer()); PlaceNewSnakePart(MovePlayer());
RegenerateFood(); RegenerateFood();
currentScore = player.body.size() * 100; currentScore = player.body.size() * 100;
//bot.UpdateProbability(player.body.size()); if (!state.m_bNoDisplay)
graphics.DisplayGameState(gameBoard, currentScore); graphics.DisplayGameState(gameBoard, currentScore);
} }
return; return;
@ -79,17 +69,22 @@ namespace snakeplusplus
void GameEngine::PlaceNewSnakePart(sf::Vector2f location) { void GameEngine::PlaceNewSnakePart(sf::Vector2f location) {
if (!player.speed.x && !player.speed.y) { return; } if (!player.speed.x && !player.speed.y) { return; }
try { try {
char* locationState = &gameBoard.at(location.y).at(location.x); GameSpace* locationState = &gameBoard.at(location.y).at(location.x);
if (*locationState == 'O' && (player.body.size() > 1)) { if (locationState->m_bSnake && (player.body.size() > 1)) {
isGameOver = true; // Game should end (Snake touching snake) state.m_bIsGameOver = true; // Game should end (Snake touching snake)
} }
*locationState = 'O'; locationState->m_bSnake = true;
player.body.push(locationState); player.body.push(locationState);
player.headLocation = location; player.headLocation = location;
if (playerFood.location != location) if (playerFood.location != location)
player.Pop(); player.Pop();
else {
locationState->m_bFood = false;
if (state.m_bIsBotControlled)
bot.ResetPath();
}
} catch (const std::out_of_range& error) { } catch (const std::out_of_range& error) {
isGameOver = true; // Snake ran into edge state.m_bIsGameOver = true; // Snake ran into edge
} }
return; return;
} }
@ -99,12 +94,12 @@ namespace snakeplusplus
void GameEngine::RegenerateFood() void GameEngine::RegenerateFood()
{ {
// Generate a new food location if the current one is occupied // Generate a new food location if the current one is occupied
while (gameBoard.at(playerFood.location.y).at(playerFood.location.x) == 'O') { while (gameBoard.at(playerFood.location.y).at(playerFood.location.x).m_bSnake) {
playerFood.GenerateNewFood(GetGameBoundaries()); playerFood.GenerateNewFood(GetGameBoundaries());
} }
// Update the game board with the new food location // Update the game board with the new food location
gameBoard.at(playerFood.location.y).at(playerFood.location.x) = 'X'; gameBoard.at(playerFood.location.y).at(playerFood.location.x).m_bFood = 1;
} }
@ -112,27 +107,27 @@ namespace snakeplusplus
{ {
gameBoard.clear(); gameBoard.clear();
sf::Vector2f boardDimensions = GetGameBoundaries(); sf::Vector2f boardDimensions = GetGameBoundaries();
gameBoard.resize(boardDimensions.y, std::vector<char> (boardDimensions.x, ' ')); gameBoard.resize(boardDimensions.y, std::vector<GameSpace>(boardDimensions.x));
// Snake setup // Snake setup
player.headLocation.x = GenerateRandomNumber(boardDimensions.x); player.headLocation.x = GenerateRandomNumber(boardDimensions.x);
player.headLocation.y = GenerateRandomNumber(boardDimensions.y); player.headLocation.y = GenerateRandomNumber(boardDimensions.y);
{ {
char* locationState = &gameBoard.at(player.headLocation.y).at(player.headLocation.x); GameSpace* locationState = &gameBoard.at(player.headLocation.y).at(player.headLocation.x);
player.body.push(locationState); player.body.push(locationState);
*locationState = 'O'; locationState->m_bSnake = true;
} }
// Food setup // Food setup
playerFood.GenerateNewFood(boardDimensions); playerFood.GenerateNewFood(boardDimensions);
gameBoard.at(playerFood.location.y).at(playerFood.location.x) = 'X'; gameBoard.at(playerFood.location.y).at(playerFood.location.x).m_bFood = true;
return; return;
} }
void GameEngine::UpdatePlayerSpeed(void) void GameEngine::UpdatePlayerSpeed(void)
{ {
PlayerDirection controller; PlayerDirection controller;
if (isBotControlled) { if (state.m_bIsBotControlled) {
if (bot.path.empty()) { if (bot.path.empty()) {
bot.GetNewPath(gameBoard, player.headLocation, GetGameBoundaries(), player.body.size()); bot.GetNewPath(player.headLocation);
} }
controller = bot.GetInput(&player.headLocation); controller = bot.GetInput(&player.headLocation);
} }
@ -163,9 +158,3 @@ namespace snakeplusplus
} }
return; return;
} }
void GameEngine::UpdateAverage() {
totalLength += player.body.size();
amountPlayed += 1;
average = (double)totalLength / amountPlayed;
}
}

View File

@ -3,12 +3,11 @@
#define GAMESTATE_HPP #define GAMESTATE_HPP
#include <SFML/Graphics.hpp> #include <SFML/Graphics.hpp>
#include <memory>
#include "botinterface.hpp" #include "botinterface.hpp"
#include "snake.hpp" #include "snake.hpp"
#include "playerinterface.hpp" #include "playerinterface.hpp"
namespace snakeplusplus
{
const int kUnitSpeed = 1; const int kUnitSpeed = 1;
class GameEngine class GameEngine
@ -17,28 +16,31 @@ namespace snakeplusplus
GameEngine(); GameEngine();
void Start(void); void Start(void);
void Reset(void); void Reset(void);
void AddIteration(void);
sf::Vector2f GetGameBoundaries(void); sf::Vector2f GetGameBoundaries(void);
struct GameState {
unsigned char m_bIsGameOver : 1 = 0;
unsigned char m_bIsBotControlled : 1 = 0;
unsigned char m_bNoDisplay : 1 = 0;
unsigned char _3 : 1 = 0;
unsigned char _4 : 1 = 0;
unsigned char _5 : 1 = 0;
unsigned char _6 : 1 = 0;
unsigned char _7 : 1 = 0;
} state;
std::vector< std::vector<GameSpace> > gameBoard;
private: private:
std::vector< std::vector<char> > gameBoard;
PlayerOutput graphics; PlayerOutput graphics;
Snake player; Snake player;
Food playerFood; Food playerFood;
AISnake bot; AISnake bot;
bool isGameOver = 0;
bool isBotControlled = 1;
void DisplayEndScreen(void);
void Loop(void); void Loop(void);
sf::Vector2f MovePlayer(void); sf::Vector2f MovePlayer(void);
void PlaceNewSnakePart(sf::Vector2f location); void PlaceNewSnakePart(sf::Vector2f location);
void RegenerateFood(void); void RegenerateFood(void);
void PrepareGameBoard(void); void PrepareGameBoard(void);
void UpdatePlayerSpeed(); void UpdatePlayerSpeed();
void UpdateAverage();
int totalLength = 0;
int amountPlayed = 0;
double average = 0;
}; };
}
inline std::unique_ptr<GameEngine> g_pEngine;
#endif #endif

View File

@ -1,8 +1,42 @@
#include "gamestate.hpp" #include "gamestate.hpp"
#include <memory>
#include <string>
#include <vector>
#include <iostream>
int main(void) void Help(void) {
{ std::cout << "Usage: snakeplusplus [OPTIONS]" << std::endl;
snakeplusplus::GameEngine game; std::cout << "Options:" << std::endl;
game.Start(); std::cout << "\t--server\tRun snake in server mode (also sets --bot)" << std::endl;
std::cout << "\t--auto\t\tControl snake using a bot or AI" << std::endl;
std::cout << "\t-h, --help\tPrint this help message and exit" << std::endl;
std::cout << std::endl;
std::cout << "Autoplay options (requires --auto):" << std::endl;
std::cout << "\t--dumb\t\tPlays using basic search algorithms BFS and DFS" << std::endl;
std::cout << "\t--smart\t\tTrains an algorithm using unsupervised learning" << std::endl;
std::cout << std::endl;
}
int main(int argc, char* argv[]) {
std::vector<std::string> args(argv, argv + argc);
g_pEngine = std::make_unique<GameEngine>();
for (int i = 1; i < args.size(); ++i) {
if (args[i].compare("--server") == 0) {
g_pEngine->state.m_bNoDisplay = true;
g_pEngine->state.m_bIsBotControlled = true;
std::cout << "[LOG - Main] Disabling display" << std::endl;
} else if (args[i].compare("--auto") == 0) {
g_pEngine->state.m_bIsBotControlled = true;
std::cout << "[LOG - Main] Bot control enabled" << std::endl;
} else if (args[i].compare("-h") == 0 || args[i].compare("--help") == 0) {
Help();
return 0;
} else {
std::cout << "[LOG - Main] Argument `" << args[i] << "` unrecognized, printing help and exiting..."<< std::endl;
Help();
return 1;
}
}
g_pEngine->Start();
return 0; return 0;
} }

View File

@ -1,9 +1,8 @@
#include "playerinterface.hpp" #include "playerinterface.hpp"
#include <SFML/System/Vector2.hpp> #include <SFML/System/Vector2.hpp>
#include <SFML/Window/Keyboard.hpp> #include <SFML/Window/Keyboard.hpp>
#include <iostream>
namespace snakeplusplus
{
PlayerDirection GetPlayerInput(void) PlayerDirection GetPlayerInput(void)
{ {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)
@ -23,7 +22,7 @@ namespace snakeplusplus
bool PlayerOutput::IsOpen(void) bool PlayerOutput::IsOpen(void)
{ {
return gameWindow.isOpen(); return isWindowAlive;
} }
PlayerOutput::PlayerOutput(void) PlayerOutput::PlayerOutput(void)
@ -38,9 +37,8 @@ namespace snakeplusplus
return; return;
} }
void PlayerOutput::CheckContinue(bool isBotControlled) void PlayerOutput::CheckContinue()
{ {
if (isBotControlled) { return; }
DisplayEndScreen(); DisplayEndScreen();
while (true) while (true)
{ {
@ -49,6 +47,7 @@ namespace snakeplusplus
|| (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))) || (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)))
{ {
gameWindow.close(); gameWindow.close();
isWindowAlive = false;
return; return;
} }
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Enter)) { return; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Enter)) { return; }
@ -84,7 +83,7 @@ namespace snakeplusplus
} }
void PlayerOutput::DisplayGameState(std::vector< std::vector<char> >& gameBoard, int score) void PlayerOutput::DisplayGameState(std::vector< std::vector<GameSpace> >& gameBoard, int score)
{ {
CheckWindowEvents(); CheckWindowEvents();
if (delay == sf::milliseconds(0)) { return; } if (delay == sf::milliseconds(0)) { return; }
@ -93,19 +92,12 @@ namespace snakeplusplus
{ {
for (float x = 0; x < gameBoundaries.x; x++) for (float x = 0; x < gameBoundaries.x; x++)
{ {
letterOnBoard = &gameBoard.at(y).at(x); if (gameBoard.at(y).at(x).m_bSnake)
switch (*letterOnBoard)
{
case 'O':
DrawSnake(sf::Vector2f(x, y)); DrawSnake(sf::Vector2f(x, y));
break; else if (gameBoard.at(y).at(x).m_bFood)
case 'X':
DrawFood(sf::Vector2f(x,y)); DrawFood(sf::Vector2f(x,y));
break; else
default:
DrawEmpty(sf::Vector2f(x,y)); DrawEmpty(sf::Vector2f(x,y));
break;
}
} }
} }
DisplayScore(score); DisplayScore(score);
@ -122,7 +114,7 @@ namespace snakeplusplus
} }
void PlayerOutput::SetShowGame(bool isShowing) { void PlayerOutput::SetShowGame(bool isShowing) {
if (isShowing) { delay = sf::milliseconds(2); } if (isShowing) { delay = sf::milliseconds(5); }
else { delay = sf::milliseconds(0); } else { delay = sf::milliseconds(0); }
return; return;
} }
@ -132,8 +124,10 @@ namespace snakeplusplus
while (gameWindow.pollEvent(event)) while (gameWindow.pollEvent(event))
{ {
if ((event.type == sf::Event::Closed) if ((event.type == sf::Event::Closed)
|| (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))) || (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))) {
gameWindow.close(); gameWindow.close();
isWindowAlive = false;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Equal)) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Equal)) {
if (delay > sf::milliseconds(16)) { continue; } if (delay > sf::milliseconds(16)) { continue; }
delay += sf::milliseconds(1); delay += sf::milliseconds(1);
@ -171,4 +165,3 @@ namespace snakeplusplus
gameWindow.draw(drawObject); gameWindow.draw(drawObject);
return; return;
} }
}

View File

@ -6,8 +6,6 @@
const int kGridSize = 25; const int kGridSize = 25;
namespace snakeplusplus
{
PlayerDirection GetPlayerInput(void); PlayerDirection GetPlayerInput(void);
class PlayerOutput class PlayerOutput
@ -16,8 +14,8 @@ namespace snakeplusplus
sf::Vector2f gameBoundaries; sf::Vector2f gameBoundaries;
PlayerOutput(void); PlayerOutput(void);
bool IsOpen(void); bool IsOpen(void);
void CheckContinue(bool isBotControlled); void CheckContinue();
void DisplayGameState(std::vector< std::vector<char> >& gameBoard, int score); void DisplayGameState(std::vector< std::vector<GameSpace> >& gameBoard, int score);
void DisplayScore(int score); void DisplayScore(int score);
void StartGameWindow(void); void StartGameWindow(void);
void SetShowGame(bool isShowing); void SetShowGame(bool isShowing);
@ -31,9 +29,8 @@ namespace snakeplusplus
sf::VideoMode gameVideoSettings; sf::VideoMode gameVideoSettings;
sf::RectangleShape drawObject; sf::RectangleShape drawObject;
sf::Event event; sf::Event event;
bool isWindowAlive; bool isWindowAlive = false;
sf::Time delay = sf::milliseconds(1); sf::Time delay = sf::milliseconds(12);
}; };
}
#endif #endif

View File

@ -4,11 +4,9 @@
#include "common.hpp" #include "common.hpp"
#include "snake.hpp" #include "snake.hpp"
namespace snakeplusplus
{
void Snake::Pop(void) void Snake::Pop(void)
{ {
*(body.front()) = ' '; body.front()->m_bSnake = false;
body.pop(); body.pop();
return; return;
} }
@ -28,4 +26,3 @@ namespace snakeplusplus
location.y = GenerateRandomNumber(boundaries.y); location.y = GenerateRandomNumber(boundaries.y);
return; return;
} }
}

View File

@ -4,15 +4,14 @@
#include <SFML/System/Vector2.hpp> #include <SFML/System/Vector2.hpp>
#include <queue> #include <queue>
#include "common.hpp"
namespace snakeplusplus
{
struct Snake struct Snake
{ {
public: public:
sf::Vector2f headLocation; sf::Vector2f headLocation;
sf::Vector2f speed; sf::Vector2f speed;
std::queue<char*> body; std::queue<GameSpace*> body;
void Pop(void); void Pop(void);
void Reset(void); void Reset(void);
}; };
@ -21,9 +20,7 @@ namespace snakeplusplus
{ {
public: public:
sf::Vector2f location; sf::Vector2f location;
char* food;
void GenerateNewFood(sf::Vector2f boundaries); void GenerateNewFood(sf::Vector2f boundaries);
}; };
}
#endif #endif