I am currently making a snake game in sfml, however, whenever i try to change the position of the snake, the snake just stops moving, what is a good fix to this problem?
main.cpp
#include <SFML/Graphics.hpp>
#include <iostream>
#include "write.h"
#include <SFML/Graphics/Font.hpp>
#include "menu.h"
#include "snake.h"
#include "wait.h"
int main()
{
sf::RenderWindow windows(sf::VideoMode::getDesktopMode(), "SFML works!",sf::Style::None);
sf::Font fonts;
sf::Clock gameClock;
windows.setKeyRepeatEnabled(false);
if(!fonts.loadFromFile("assets/bit.ttf"))
{
std::cerr << "Error loading font" << std::endl;
}
std::string gameScreen = "Main Menu";
Snake snake1(10,100,500,0);
snake1.drawSnake(windows);
while(windows.isOpen())
{
sf::Event event;
while (windows.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
windows.close();
}
if(event.type == sf::Event::KeyPressed)
{
if(event.key.code == sf::Keyboard::Left)
{
if(gameScreen == "Play Game" )
{
snake1.left();
}
}
}
if(event.key.code == sf::Keyboard::Escape)
{
windows.close();
}
}
if(gameScreen == "Main Menu")
{
gameScreen = buildMenu(fonts,windows);
}
if(gameScreen == "Play Game")
{
snake1.moveForward(windows);
wait(10,gameClock);
}
}
return 0;
}
snake.cpp
#include <SFML/Graphics.hpp>
#include <iostream>
#include <SFML/Graphics/Font.hpp>
#include "snake.h"
#include "wait.h"
#include "math.h"
Snake::Snake( int s, int gx, int gy, int num) //size,color,x,y)
{
size = s;
x = gx;
y=gy;
facing = num;
}
void Snake::drawSnake(sf::RenderWindow& window)
{
sf::RectangleShape rectangle2;
rectangle2.setSize(sf::Vector2f(size*10, 20));
rectangle2.setOutlineColor(sf::Color::Transparent);
rectangle2.setOutlineThickness(10);
rectangle2.setPosition(x,y);
rectangle2.setFillColor(sf::Color::White);
window.clear();
window.draw(rectangle2);
window.display();
}
void Snake::moveForward(sf::RenderWindow& window)
{
Snake::drawSnake(window);
if(cos(facing) == 1)
{
x=x+1;
}
else if(sin(facing) == 1){
y=y+1;
}
else if(cos(facing) == -1)
{
x=x-1;
std::cout << "hola";
}
else if(sin(facing) == -1)
{
y = y-1;
}
}
void Snake::left()
{
facing = facing + 90;
std::cout<<facing;
}
void Snake::right()
{
facing = facing -90;
}