Hello. I'm trying to make a snake in C++ with SFML.
The code is fairly small, what I did atm is that when we press one key (left/right/up/down) the direction change, and while the window is open there are 4 while loops: while(direction = right/left/down/up) (one loop for each direction) and in that loop I put sprite.move(x,y).
I really can't find the error. It's maybe a C++ error but I really can't find it.
Here is the code :
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <vector>
sf::Event event;
enum Direction { Up, Down, Left, Right};
int dir = Up;
class SnakeBlock
{
public:
SnakeBlock * next;
sf::Texture texture;
sf::Sprite snakeblock;
};
int main()
{
sf::Sprite background;
sf::Texture backgroundtex;
backgroundtex.loadFromFile("background.png", sf::IntRect(0, 0, 1987, 1315));
background.setTexture(backgroundtex);
SnakeBlock snakeHead;
snakeHead.texture.loadFromFile("spritesheetsnake.png", sf::IntRect(0,0,52,44));
snakeHead.snakeblock.setTexture(snakeHead.texture);
std::vector<SnakeBlock> Snake;
Snake.push_back(snakeHead);
Snake[0].snakeblock.setPosition(100,100);
sf::RenderWindow window(sf::VideoMode(800,600), "SFML Snake");
window.setFramerateLimit(30);
while(window.isOpen())
{
while(window.pollEvent(event))
{
switch(event.type)
{
case sf::Event::Closed:
window.close();
break;
default:
break;
}
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
dir = Left;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
dir = Right;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
dir = Down;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
dir = Up;
}
while(dir == Up)
{
Snake[0].snakeblock.move(0,-5);
}
while(dir == Down)
{
Snake[0].snakeblock.move(0,5);
}
while(dir == Left)
{
Snake[0].snakeblock.move(-5,0);
}
while(dir == Right)
{
Snake[0].snakeblock.move(5,0);
}
window.clear(sf::Color::Green);
window.draw(background);
window.draw(Snake[0].snakeblock);
window.display();
}
return 0;
}
By the way, if that code works, after that, I plan to make the snake bigger when he collide with something, delete the thing he went into, and add one snakeblock to the vector of snakeblock called Snake, then I will get (the last element minus one) of Snake and initialize the *next variable pointer to the last element, and in the main isOpen loop, I will make a for loop where I draw the last block of the snake, and then draw each *next of the snakeblock, but I wonder how I could make the snake not look like a line of blocks but such as that :
_______
|.............|___O
|
where the line is the body of the snake and the "O" is the head of the snake.
If you don't understand what I said about making the snake game just try to find the error in my code, I know what I said is not very clear.
Thanks you a lot in advance.