Hello,
I've been trying to make a snake game, and I had lots of problems and debugging errors related to the vector, which I though I eventually solved, but now I discovered that the snake isn't moving at all when I use the keyboard keys , let alone increasing in length upon eating a fruit. Could you please check my code and help me by telling me what's wrong/what can I do to solve the problem/ways to improve my code? Thank you!
I'm a beginner, so please excuse me if the question is stupid/the solution is obvious. (I've done my research, believe me.).
#include <vector>
#include <limits>
#include <algorithm>
#include <SFML/Graphics.hpp>
#include <iostream>
int t = 0;
sf::RectangleShape addsnake();
sf::RectangleShape first;
sf::RectangleShape second;
sf::RectangleShape third;
sf::RectangleShape fourth;
std::vector<sf::RectangleShape>snake{first,second,third,fourth };
sf::RectangleShape addsnake(){
snake[0].setFillColor(sf::Color::Red);
snake[0].setPosition(100, 100);
snake[0].setSize(sf::Vector2f(20, 20));
return snake[t];
}
bool intersects(const sf::RectangleShape & r1, const sf::RectangleShape & r2){
sf::FloatRect snake = r1.getGlobalBounds();
sf::FloatRect spawnedFruit = r2.getGlobalBounds();
return snake.intersects(spawnedFruit);
}
sf::RectangleShape generateFruit() {
sf::RectangleShape fruit;
fruit.setFillColor(sf::Color::Yellow);
int fruitx = rand() % 400;
int fruity = rand() % 400;
fruit.setPosition(fruitx, fruity);
fruit.setSize(sf::Vector2f(5, 5));
return fruit;
}
int main()
{
srand(time(NULL));
int width = 400;
int height = 400;
sf::VideoMode videomode(width, height);
sf::RenderWindow window(videomode, "Snake");
sf::Clock clock;
sf::Time t1 = sf::seconds(20);
sf::RectangleShape spawnedFruit;
while (window.isOpen()) {
window.clear();
window.draw(snake[0]);
sf::Time elapsed1 = clock.getElapsedTime();
if (elapsed1 >= t1) {
spawnedFruit = generateFruit();
clock.restart();
}
window.draw(spawnedFruit);
window.display();
sf::Event event;
while (window.pollEvent(event))
{
if ((event.type == sf::Event::Closed) ||
((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape)))
window.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
snake[0].move(0, -0.1);
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
snake[0].move(0, 0.1);
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
snake[0].move(-0.1, 0);
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
snake[0].move(0.1, 0);
if (intersects(snake[0], spawnedFruit))
t++;
snake.push_back(addsnake()); //tried snake[t]
}
}