I am trying to create a snake game in SFML, and I can't figure out what is happening because the window is not updating with the new position of the snake. Here is my code.
main.cpp
#include <SFML/Graphics.hpp>
#include <iostream>
#include "write.h"
#include <SFML/Graphics/Font.hpp>
#include "menu.h"
#include "snake.h"
int main()
{
sf::RenderWindow windows(sf::VideoMode::getDesktopMode(), "SFML works!",sf::Style::None);
sf::Font fonts;
if(!fonts.loadFromFile("assets/bit.ttf"))
{
std::cerr << "Error loading font" << std::endl;
}
std::string gameScreen = "Main Menu";
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::Escape)
{
windows.close();
}
if(event.type == sf::Event::MouseMoved)
{
}
}
if(gameScreen == "Main Menu")
{
gameScreen = buildMenu(fonts,windows);
}
if(gameScreen == "Play Game")
{
Snake snake1(10,100,500);
snake1.drawSnake(windows);
snake1.moveForward(windows);
}
}
return 0;
}
Snake.cpp
#include <SFML/Graphics.hpp>
#include <iostream>
#include <SFML/Graphics/Font.hpp>
#include "snake.h"
Snake::Snake( int s, int gx, int gy) //size,color,x,y)
{
size = s;
x = gx;
y=gy;
}
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);
x = x+1;
}
snake.h
#ifndef SNAKE_H
#define SNAKE_H
class Snake
{
int size;
int x;
int y;
public:
Snake(int s, int gx,int gy);
void moveForward(sf::RenderWindow& window);
//left();
//right();
void drawSnake(sf::RenderWindow& window);
};
#endif