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
11 changed files with 110 additions and 70 deletions
Showing only changes of commit ccf5843e61 - Show all commits

View File

@ -52,7 +52,7 @@ void AISnake::AdjustProbability(double amount)
// 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 std::vector< std::vector<GameSpace> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries, const int snakeSize)
{ {
// Search for food // Search for food
/* /*
@ -80,7 +80,7 @@ void AISnake::GetNewPath(const std::vector< std::vector<char> >& gameBoard, cons
} }
} }
void AISnake::BFS(const std::vector< std::vector<char> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries) { void AISnake::BFS(const std::vector< std::vector<GameSpace> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries) {
std::queue<sf::Vector2f> search; std::queue<sf::Vector2f> search;
std::vector<std::vector<bool>> visited(boundaries.y, std::vector<bool> (boundaries.x, false)); std::vector<std::vector<bool>> visited(boundaries.y, std::vector<bool> (boundaries.x, false));
bool foodFound = false; bool foodFound = false;
@ -90,7 +90,7 @@ void AISnake::BFS(const std::vector< std::vector<char> >& gameBoard, const sf::V
search.pop(); search.pop();
if (foodFound) { break; } if (foodFound) { break; }
if (visited.at(currentLocation.y).at(currentLocation.x)) { continue; } if (visited.at(currentLocation.y).at(currentLocation.x)) { continue; }
if (gameBoard.at(currentLocation.y).at(currentLocation.x) == 'X') { if (gameBoard.at(currentLocation.y).at(currentLocation.x).m_bFood) {
foodFound = true; foodFound = true;
} }
botPathUnsanitized.push(currentLocation); botPathUnsanitized.push(currentLocation);
@ -102,7 +102,7 @@ void AISnake::BFS(const std::vector< std::vector<char> >& gameBoard, const sf::V
localLocations[3].x -= 1; localLocations[3].x -= 1;
for (auto i : localLocations) { for (auto i : localLocations) {
try { try {
if (gameBoard.at(i.y).at(i.x) == 'X') { if (gameBoard.at(i.y).at(i.x).m_bFood) {
botPathUnsanitized.push(i); botPathUnsanitized.push(i);
foodFound = true; foodFound = true;
} }
@ -113,7 +113,8 @@ void AISnake::BFS(const std::vector< std::vector<char> >& gameBoard, const sf::V
for (sf::Vector2f newLocation : localLocations) { for (sf::Vector2f newLocation : localLocations) {
try { try {
if ((!visited.at(newLocation.y).at(newLocation.x)) if ((!visited.at(newLocation.y).at(newLocation.x))
&& (gameBoard.at(newLocation.y).at(newLocation.x) == ' ')) { && (gameBoard.at(newLocation.y).at(newLocation.x).m_bFood)
&& (gameBoard.at(newLocation.y).at(newLocation.x).m_bSnake)) {
search.push(newLocation); search.push(newLocation);
} }
} catch (const std::out_of_range& error) { } catch (const std::out_of_range& error) {
@ -124,7 +125,7 @@ void AISnake::BFS(const std::vector< std::vector<char> >& gameBoard, const sf::V
} }
} }
void AISnake::DFS(const std::vector< std::vector<char> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries) { void AISnake::DFS(const std::vector< std::vector<GameSpace> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries) {
std::stack<sf::Vector2f> search; std::stack<sf::Vector2f> search;
std::vector<std::vector<bool>> visited(boundaries.y, std::vector<bool> (boundaries.x, false)); std::vector<std::vector<bool>> visited(boundaries.y, std::vector<bool> (boundaries.x, false));
bool foodFound = false; bool foodFound = false;
@ -133,8 +134,8 @@ void AISnake::DFS(const std::vector< std::vector<char> >& gameBoard, const sf::V
sf::Vector2f currentLocation = search.top(); sf::Vector2f currentLocation = search.top();
search.pop(); search.pop();
if (foodFound) { break; } if (foodFound) { break; }
if (visited.at(currentLocation.y).at(currentLocation.x)) { continue; } if (visited[currentLocation.y][currentLocation.x]) { continue; }
if (gameBoard.at(currentLocation.y).at(currentLocation.x) == 'X') { if (gameBoard[currentLocation.y][currentLocation.x].m_bFood) {
foodFound = true; foodFound = true;
} }
botPathUnsanitized.push(currentLocation); botPathUnsanitized.push(currentLocation);
@ -146,7 +147,7 @@ void AISnake::DFS(const std::vector< std::vector<char> >& gameBoard, const sf::V
localLocations[3].x -= 1; localLocations[3].x -= 1;
for (auto i : localLocations) { for (auto i : localLocations) {
try { try {
if (gameBoard.at(i.y).at(i.x) == 'X') { if (gameBoard.at(i.y).at(i.x).m_bFood) {
botPathUnsanitized.push(i); botPathUnsanitized.push(i);
foodFound = true; foodFound = true;
} }
@ -163,7 +164,8 @@ void AISnake::DFS(const std::vector< std::vector<char> >& gameBoard, const sf::V
} }
if ((!visited.at(newLocation.y).at(newLocation.x)) if ((!visited.at(newLocation.y).at(newLocation.x))
&& (gameBoard.at(newLocation.y).at(newLocation.x) == ' ')) { && !(gameBoard.at(newLocation.y).at(newLocation.x).m_bFood)
&& !(gameBoard.at(newLocation.y).at(newLocation.x).m_bSnake)) {
search.push(newLocation); search.push(newLocation);
} }
} catch (const std::out_of_range& error) { } catch (const std::out_of_range& error) {

View File

@ -10,15 +10,15 @@ 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 std::vector< std::vector<GameSpace> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries, const int snakeSize);
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);
private: private:
double probabilityBFS = 0.500; double probabilityBFS = 0.500;
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 std::vector< std::vector<GameSpace> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries);
void DFS(const std::vector< std::vector<char> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries); void DFS(const std::vector< std::vector<GameSpace> >& gameBoard, const sf::Vector2f& source, const sf::Vector2f& boundaries);
}; };
#endif #endif

View File

@ -16,3 +16,8 @@ int GenerateRandomNumber(int generationLimit)
generatedNumber = distribution(generator); generatedNumber = distribution(generator);
return generatedNumber; return generatedNumber;
} }
GameSpace::GameSpace(void) {
m_bFood = 0;
m_bSnake = 0;
}

View File

@ -13,4 +13,16 @@ enum PlayerDirection
kRight = 4 kRight = 4
}; };
struct GameSpace {
GameSpace();
unsigned char m_bFood : 1 = 0;
unsigned char m_bSnake : 1 = 0;
unsigned char _2 : 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;
};
#endif #endif

View File

@ -16,6 +16,7 @@ GameEngine::GameEngine()
void GameEngine::Start() void GameEngine::Start()
{ {
PrepareGameBoard(); PrepareGameBoard();
if (!state.m_bNoDisplay)
graphics.StartGameWindow(); graphics.StartGameWindow();
Loop(); Loop();
return; return;
@ -25,16 +26,19 @@ void GameEngine::Reset()
{ {
AddIteration(); AddIteration();
player.Reset(); player.Reset();
if (isBotControlled) { while (!bot.path.empty()) { bot.path.pop(); } } if (state.m_bIsBotControlled) { while (!bot.path.empty()) { bot.path.pop(); } }
PrepareGameBoard(); PrepareGameBoard();
isGameOver = false; state.m_bIsGameOver = false;
if (state.m_bNoDisplay)
graphics.SetShowGame(false);
else
graphics.SetShowGame((amountPlayed + 1) % 50 == 0); graphics.SetShowGame((amountPlayed + 1) % 50 == 0);
return; return;
} }
void GameEngine::AddIteration(void) void GameEngine::AddIteration(void)
{ {
graphics.CheckContinue(isBotControlled); graphics.CheckContinue(state.m_bIsBotControlled);
if (player.body.size() > 40) if (player.body.size() > 40)
{ {
UpdateAverage(); UpdateAverage();
@ -50,14 +54,15 @@ void GameEngine::AddIteration(void)
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()); //bot.UpdateProbability(player.body.size());
if (!state.m_bNoDisplay)
graphics.DisplayGameState(gameBoard, currentScore); graphics.DisplayGameState(gameBoard, currentScore);
} }
return; return;
@ -77,17 +82,19 @@ sf::Vector2f GameEngine::GetGameBoundaries(void)
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;
} 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;
} }
@ -97,12 +104,12 @@ void GameEngine::PlaceNewSnakePart(sf::Vector2f location) {
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[playerFood.location.y][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[playerFood.location.y][playerFood.location.x].m_bFood = 1;
} }
@ -110,25 +117,25 @@ void GameEngine::PrepareGameBoard(void)
{ {
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[player.headLocation.y][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[playerFood.location.y][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(gameBoard, player.headLocation, GetGameBoundaries(), player.body.size());
} }

View File

@ -18,15 +18,22 @@ public:
void Reset(void); void Reset(void);
void AddIteration(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 = 1;
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;
private: private:
std::vector< std::vector<char> > gameBoard; std::vector< std::vector<GameSpace> > 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);

View File

@ -1,8 +1,20 @@
#include "gamestate.hpp" #include "gamestate.hpp"
#include <memory> #include <memory>
#include <string>
#include <vector>
#include <iostream>
int main(void) int main(int argc, char* argv[])
{ {
std::vector<std::string> args{argv + 1, argv + argc};
for (auto it = args.begin(); it != args.end(); it++) {
if (it->compare("--no-gui") == 0) {
g_pEngine->state.m_bNoDisplay = true;
} else {
std::cerr << "[ERROR] Argument option not found, exiting..." << std::endl;
return 1;
}
}
g_pEngine = std::make_unique<GameEngine>(); g_pEngine = std::make_unique<GameEngine>();
g_pEngine->Start(); g_pEngine->Start();
return 0; return 0;

View File

@ -21,7 +21,7 @@ PlayerDirection GetPlayerInput(void)
bool PlayerOutput::IsOpen(void) bool PlayerOutput::IsOpen(void)
{ {
return gameWindow.isOpen(); return isWindowAlive;
} }
PlayerOutput::PlayerOutput(void) PlayerOutput::PlayerOutput(void)
@ -47,6 +47,7 @@ void PlayerOutput::CheckContinue(bool isBotControlled)
|| (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; }
@ -82,7 +83,7 @@ void PlayerOutput::DisplayScore(int score) {
} }
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; }
@ -91,19 +92,12 @@ void PlayerOutput::DisplayGameState(std::vector< std::vector<char> >& gameBoard,
{ {
for (float x = 0; x < gameBoundaries.x; x++) for (float x = 0; x < gameBoundaries.x; x++)
{ {
letterOnBoard = &gameBoard.at(y).at(x); if (gameBoard[y][x].m_bSnake)
switch (*letterOnBoard)
{
case 'O':
DrawSnake(sf::Vector2f(x, y)); DrawSnake(sf::Vector2f(x, y));
break; else if (gameBoard[y][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);

View File

@ -15,7 +15,7 @@ public:
PlayerOutput(void); PlayerOutput(void);
bool IsOpen(void); bool IsOpen(void);
void CheckContinue(bool isBotControlled); void CheckContinue(bool isBotControlled);
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);
@ -29,7 +29,7 @@ private:
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(1);
}; };

View File

@ -6,7 +6,7 @@
void Snake::Pop(void) void Snake::Pop(void)
{ {
*(body.front()) = ' '; body.front()->m_bSnake = false;
body.pop(); body.pop();
return; return;
} }

View File

@ -4,13 +4,14 @@
#include <SFML/System/Vector2.hpp> #include <SFML/System/Vector2.hpp>
#include <queue> #include <queue>
#include "common.hpp"
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);
}; };