Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SFML/Graphics.hpp>
- #include <iostream>
- #include <random>
- #include <vector>
- #define WIDTH 800
- #define HEIGHT 600
- sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "Snake");
- void SetRandPos(sf::RectangleShape &shape)
- {
- int x = rand()%WIDTH;
- int y = rand()%HEIGHT;
- shape.setPosition({x, y});
- }
- class Snake
- {
- public:
- sf::RectangleShape head;
- std::vector<sf::RectangleShape> tail;
- int eatenCoins = 0;
- float speed;
- sf::Vector2f defaultSize;
- sf::Vector2f dir = {0, -1}; // default in sus
- /*
- 0, -1 -> sus
- 0, 1 -> jos
- 1, 0 -> dreapta
- -1, 0 -> stanga
- */
- void ChangeDir()
- {
- if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) dir = {0, -1};
- if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) dir = {0, 1};
- if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) dir = {-1, 0};
- if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) dir = {1, 0};
- }
- void Move()
- {
- head.move(dir * speed);
- for(int i = 0; i<tail.size(); ++i){
- }
- }
- void AddNewTailPart()
- {
- }
- void CheckForCoin(sf::RectangleShape &coin)
- {
- if(head.getGlobalBounds().contains(coin.getPosition())){
- ++eatenCoins;
- std::cout << eatenCoins << '\n';
- SetRandPos(coin);
- AddNewTailPart();
- }
- }
- void Draw()
- {
- window.draw(head);
- for(auto &i:tail) window.draw(i);
- }
- Snake(sf::Vector2f StartPos, sf::Vector2f Size, float Speed)
- {
- defaultSize = Size;
- speed = Speed;
- head.setSize(Size);
- head.setFillColor(sf::Color(255, 255, 255));
- head.setPosition(StartPos);
- head.setOrigin(Size.x/2, Size.y/2);
- }
- };
- int main()
- {
- srand((time(0)));
- window.setFramerateLimit(60);
- Snake snake({WIDTH/2, HEIGHT/2}, {20, 20}, 4);
- sf::RectangleShape coin;
- coin.setFillColor(sf::Color::Yellow);
- coin.setSize({20, 20});
- coin.setOrigin(20/2, 20/2);
- SetRandPos(coin);
- while(window.isOpen())
- {
- sf::Event e;
- while(window.pollEvent(e)){
- if(e.type == sf::Event::Closed) window.close();
- }
- snake.Move();
- snake.ChangeDir();
- snake.CheckForCoin(coin);
- window.clear(sf::Color(0, 0, 0));
- window.draw(coin);
- snake.Draw();
- window.display();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement