#include <SFML/Graphics.hpp>
#include <vector>

class Entity {
public:
    sf::RectangleShape body;

    Entity(sf::Vector2f size, sf::Color color) {
        body.setSize(size);
        body.setFillColor(color);
    }
};

class Snake : public Entity {
public:
    std::vector<sf::Vector2f> positions;

    Snake() : Entity(sf::Vector2f(10.f, 10.f), sf::Color::Green) {
        positions.push_back(body.getPosition());
    }

    void grow() {
        positions.push_back(body.getPosition());
    }

    void move(sf::Vector2f direction) {
        positions.insert(positions.begin(), positions[0] + direction * body.getSize().x);
        positions.pop_back();
    }

    bool checkCollision() {
        for (std::size_t i = 1; i < positions.size(); ++i) {
            if (positions[0] == positions[i]) return true;
        }
        return false;
    }
};

class Food : public Entity {
public:
    Food() : Entity(sf::Vector2f(10.f, 10.f), sf::Color::Red) {}

    void spawn(std::vector<sf::Vector2f> snakePositions) {
        while (true) {
            body.setPosition(rand() % 800, rand() % 600);
            bool onSnake = false;
            for (auto pos : snakePositions) {
                if (body.getPosition() == pos) onSnake = true;
            }
            if (!onSnake) break;
        }
    }
};

class Game {
public:
    sf::RenderWindow window;
    Snake snake;
    Food food;
    sf::Clock clock;
    sf::Time timer;
    sf::Vector2f direction;
    float speed;
    sf::Texture backgroundTexture;
    sf::Sprite backgroundSprite;

    Game() : window(sf::VideoMode(800, 600), "Snake Game") {}

    void setLevel(int level) {
        if (level == 1) { // Easy
            speed = 0.2f;
            backgroundTexture.loadFromFile("background1.png");
        } else if (level == 2) { // Medium
            speed = 0.1f;
            backgroundTexture.loadFromFile("background2.png");
        } else if (level == 3) { // Hard
            speed = 0.05f;
            backgroundTexture.loadFromFile("background3.png");
        }
        backgroundSprite.setTexture(backgroundTexture);
    }

    void run() {
        while (window.isOpen()) {
            sf::Event event;
            while (window.pollEvent(event)) {
                if (event.type == sf::Event::Closed)
                    window.close();
                else if (event.type == sf::Event::KeyPressed) {
                    if (event.key.code == sf::Keyboard::Up) direction = {0, -1};
                    else if (event.key.code == sf::Keyboard::Down) direction = {0, 1};
                    else if (event.key.code == sf::Keyboard::Left) direction = {-1, 0};
                    else if (event.key.code == sf::Keyboard::Right) direction = {1, 0};
                }
            }

            timer += clock.restart();
            if (timer > sf::seconds(speed)) {
                timer = sf::Time::Zero;
                snake.move(direction);
                if (snake.checkCollision()) window.close();
                if (snake.positions[0] == food.body.getPosition()) {
                    snake.grow();
                    food.spawn(snake.positions);
                }
            }

            window.clear();
            window.draw(backgroundSprite);
            for (auto pos : snake.positions) {
                snake.body.setPosition(pos);
                window.draw(snake.body);
            }
            window.draw(food.body);
            window.display();
        }
    }
};

int main() {
    srand(time(NULL));
    Game game;
    
    // Set the level here
    game.setLevel(1); // Easy level

    game.run();
}
 

C++ Online Compiler

Write, Run & Share C++ code online using OneCompiler's C++ online compiler for free. It's one of the robust, feature-rich online compilers for C++ language, running on the latest version 17. Getting started with the OneCompiler's C++ compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as C++ and start coding!

Read inputs from stdin

OneCompiler's C++ online compiler supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample program which takes name as input and print your name with hello.

#include <iostream>
#include <string>
using namespace std;

int main() 
{
    string name;
    cout << "Enter name:";
    getline (cin, name);
    cout << "Hello " << name;
    return 0;
}

About C++

C++ is a widely used middle-level programming language.

  • Supports different platforms like Windows, various Linux flavours, MacOS etc
  • C++ supports OOPS concepts like Inheritance, Polymorphism, Encapsulation and Abstraction.
  • Case-sensitive
  • C++ is a compiler based language
  • C++ supports structured programming language
  • C++ provides alot of inbuilt functions and also supports dynamic memory allocation.
  • Like C, C++ also allows you to play with memory using Pointers.

Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition If-Else is used.

if(conditional-expression) {
   //code
}
else {
   //code
}

You can also use if-else for nested Ifs and If-Else-If ladder when multiple conditions are to be performed on a single variable.

2. Switch:

Switch is an alternative to If-Else-If ladder.

switch(conditional-expression){    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
......    
    
default:     
 code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
  //code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
// code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
 // code 
} while (condition); 

Functions

Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity. Function gets run only when it is called.

How to declare a Function:

return_type function_name(parameters);

How to call a Function:

function_name (parameters)

How to define a Function:

return_type function_name(parameters) {  
 // code
}