Added bot controls, bot still has poor pathing

This commit is contained in:
Trimutex 2023-08-19 12:56:40 -05:00
parent 197311831f
commit d2e1424e7d
6 changed files with 47 additions and 3 deletions

View File

@ -6,6 +6,7 @@ add_executable(snakeplusplus
./snake.cpp
./playerinterface.cpp
./common.cpp
./botinterface.cpp
)
target_include_directories(snakeplusplus PUBLIC ${CMAKE_CURRENT_LIST_DIR})

26
src/botinterface.cpp Normal file
View File

@ -0,0 +1,26 @@
#include "botinterface.hpp"
#include "common.hpp"
#include <SFML/System/Vector2.hpp>
namespace snakeplusplus
{
PlayerDirection lastKnownDirection = kNone;
PlayerDirection GetBotInput(sf::Vector2f snakeHeadLocation, sf::Vector2f foodLocation)
{
sf::Vector2f directionDelta;
directionDelta = snakeHeadLocation - foodLocation;
if ((directionDelta.y > 0)
&& (lastKnownDirection != kDown))
{ lastKnownDirection = kUp; }
else if ((directionDelta.y < 0)
&& (lastKnownDirection != kUp))
{ lastKnownDirection = kDown; }
else if ((directionDelta.x > 0)
&& (lastKnownDirection != kRight))
{ lastKnownDirection = kLeft; }
else if ((directionDelta.x < 0)
&& (lastKnownDirection != kLeft))
{ lastKnownDirection = kRight; }
return lastKnownDirection;
}
}

12
src/botinterface.hpp Normal file
View File

@ -0,0 +1,12 @@
#ifndef BOTINTERFACE_HPP
#define BOTINTERFACE_HPP
#include "common.hpp"
#include <SFML/System/Vector2.hpp>
namespace snakeplusplus
{
PlayerDirection GetBotInput(sf::Vector2f snakeHeadLocation, sf::Vector2f foodLocation);
}
#endif

View File

@ -1,6 +1,7 @@
// GameState.cpp
#include <stdexcept>
#include <SFML/Graphics.hpp>
#include "botinterface.hpp"
#include "common.hpp"
#include "playerinterface.hpp"
#include "gamestate.hpp"
@ -34,7 +35,7 @@ namespace snakeplusplus
{
while (graphics.IsOpen())
{
if (isGameOver) {Reset();}
if (isGameOver) { Reset(); }
UpdatePlayerSpeed();
PlaceNewSnakePart(MovePlayer());
RegenerateFood();
@ -113,7 +114,10 @@ namespace snakeplusplus
void GameEngine::UpdatePlayerSpeed(void)
{
switch (GetPlayerInput()) {
PlayerDirection controller;
if (isBotControlled) { controller = GetBotInput(player.headLocation, playerFood.location); }
else { controller = GetPlayerInput(); }
switch (controller) {
case kUp:
if (player.speed.y == 1) { break; }
player.speed.x = 0;

View File

@ -21,6 +21,7 @@ namespace snakeplusplus
Snake player;
Food playerFood;
bool isGameOver = 0;
bool isBotControlled = 1;
void DisplayEndScreen(void);
void Loop(void);
sf::Vector2f MovePlayer(void);

View File

@ -29,7 +29,7 @@ namespace snakeplusplus
sf::VideoMode gameVideoSettings;
sf::RectangleShape drawObject;
bool isWindowAlive;
sf::Time delay = sf::milliseconds(60);
sf::Time delay = sf::milliseconds(20);
};
}