Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: [Beginner] Snake game, please help.  (Read 5549 times)

0 Members and 1 Guest are viewing this topic.

Serilda

  • Guest
[Beginner] Snake game, please help.
« on: March 19, 2016, 01:24:43 pm »
How can I make snake length increase after eating the fruit? also how can I make the fruit change position? Please help me.Thanks!

#include "stdafx.h"
#include <SFML\Graphics.hpp>


#include "Win32Project1.h"
#include <iostream>
#include <time.h>
bool intersects(const sf::RectangleShape & snake, const sf::RectangleShape & fruit)
{
        sf::FloatRect s = snake.getGlobalBounds();
        sf::FloatRect f = fruit.getGlobalBounds();
        return s.intersects(f);

}
int main(){
        srand(time(NULL));

        int width = 400;
        int height = 400;
        sf::VideoMode videomode(width, height);
        sf::RenderWindow window(videomode, "Snake");
        sf::RectangleShape snake;
        sf::RectangleShape borderleft;
        sf::RectangleShape borderright;
        sf::RectangleShape bordertop;
        sf::RectangleShape borderbot;
        sf::RectangleShape fruit;
        sf::RectangleShape addsnake;


        borderleft.setFillColor(sf::Color::Black);
        borderleft.setSize(sf::Vector2f(20, 400));
        borderleft.setPosition(0, 0);


        borderright.setFillColor(sf::Color::Black);
        borderright.setSize(sf::Vector2f(20, 400));
        borderright.setPosition(380, 0);


        bordertop.setFillColor(sf::Color::Black);
        bordertop.setSize(sf::Vector2f(20, 400));
        bordertop.setPosition(400,0);
        bordertop.rotate(90);


        borderbot.setFillColor(sf::Color::Black);
        borderbot.setSize(sf::Vector2f(20, 400));
        borderbot.setPosition(400, 380);
        borderbot.rotate(90);


        snake.setFillColor(sf::Color::Red);
        snake.setOutlineColor(sf::Color::Blue);
        snake.setPosition(width - 200, height - 200);
        snake.setSize(sf::Vector2f(20, 20));

       
        addsnake.setFillColor(sf::Color::Red);
        addsnake.setOutlineColor(sf::Color::Blue);
        addsnake.setPosition(snake.getPosition() - 20); //problem

        fruit.setFillColor(sf::Color::Yellow);
        int fruitx = rand() % 400;
        int fruity = rand() % 400;
        fruit.setPosition(fruitx, fruity); //Use later in while loop.
        fruit.setSize(sf::Vector2f(20, 20));
       
       


        while (window.isOpen()){
                window.clear(sf::Color::Cyan);
                window.draw(snake);
                window.draw(borderleft);
                window.draw(borderright);
                window.draw(bordertop);
                window.draw(borderbot);
                window.draw(fruit);
                window.display();
               


                sf::Event event;
                while (window.pollEvent(event)){

                        if ((event.type == sf::Event::Closed) || ((event.type == sf::Event::KeyPressed) && (sf::Keyboard::Up)))
                                window.close();
                }
                if (intersects(snake, fruit)){
//do something
                       

        }
}
 
Please help , I am new to SFML and I know only basic C++

(I don't know how to format to code,sorry)
« Last Edit: March 19, 2016, 02:12:32 pm by eXpl0it3r »

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11034
    • View Profile
    • development blog
    • Email
Re: [Beginner] Snake game, please help.
« Reply #1 on: March 19, 2016, 02:34:32 pm »
Use a std::vector and add new RectangleShapes into for more body parts.

(I don't know how to format to code,sorry)
I added the formatting for you, you just need to use [code=cpp][/code]. ;)
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

bitano

  • Jr. Member
  • **
  • Posts: 89
    • View Profile
Re: [Beginner] Snake game, please help.
« Reply #2 on: March 19, 2016, 02:42:08 pm »
Lol To be fair, you're pretty much asking others to make the whole game for you :D

It's not just about the snake growing or the fruit changing position, but also:

1. the keypresses aren't properly read
2. there's nothing in place to make the snake move
3. there's this addsnake class / struct in your code but it doesn't exist.

Not flaming you at all, but it seems you're trying to fly when you have to learn to walk first.
Here are some tips based on how i would make a first snake game:

1. Don't use 4 black sf::rectangleShapes to make a border. just clear the window using black color and then use a single sf::rectangleShape to draw the cyan playField.

2. Since the snake and the fruit are 20x20 squares, don't think of the playfield as a 400x400 square, but instead as a grid of 20x20 positions.

3. Use a separate function createFruit() which randomly determines a new location for the fruit to be created. Pass the snake vector array to this function so that the function can check whether the new fruit is sharing a spot with a snake tailpiece - if so, find a new spot. The function then returns the randomly generated grid position x and y of the fruit which you keep in a variable.

4. Use a vector array to keep track of each bodypart of the snake. Whenever the snake moves, loop through the vector to determine the new position of each tailpiece based on the previous tailpiece.

5. Add an sf::clock to the game and check for the elapsed time. Use a speed variable and determine at which elapsed time amount you want to update the snake's position (thus determining the game speed)

6. When the snake moves, make several checks on the first vector array record (the head).
    - if its grid position equals that of the fruit, call the createFruit() function (and increase a score variable by 1)
    - if its grid position equals that of a tailpiece, it's game over
    - if its grid position is lower or higher than the amount of available grid positions, it's game over

Don't try to build Snake in 1 go. Read some SFML documentation on events, sf::Clock, vectors, etc. Just focus on parts of the game and get those to work first (keyboard input, snake head movement). Then when you figured each part out, combine them and you build your very own game.

Good luck!

Serilda

  • Guest
Re: [Beginner] Snake game, please help.
« Reply #3 on: March 19, 2016, 02:58:37 pm »
I'm still making the game bitano, still didn't add the motion stuff, anyway thanks for the tips!

bitano

  • Jr. Member
  • **
  • Posts: 89
    • View Profile
Re: [Beginner] Snake game, please help.
« Reply #4 on: March 19, 2016, 03:20:37 pm »
I'm still making the game bitano, still didn't add the motion stuff, anyway thanks for the tips!
I realize that. But the way i see it, you don't have to worry yet about the snake growing or the fruit changing position before you get the input handling and snake movement right.

But maybe that's just me. Again, good luck!  ;D

Here's a small improvement on your event loop (you could ofc use enums for the direction instead of short values to make it more readable):

        // INPUT
        sf::Event event;
        while (window.pollEvent(event)) {
            switch(event.type) {
                case sf::Event::Closed:
                    window.close();
                    break;
                case sf::Event::KeyPressed:
                    switch (event.key.code) {
                        case sf::Keyboard::Escape: window.close();   break;
                        case sf::Keyboard::Up:     snakeDir = 0;     break;
                        case sf::Keyboard::Down:   snakeDir = 1;     break;
                        case sf::Keyboard::Left:   snakeDir = 2;     break;
                        case sf::Keyboard::Right:  snakeDir = 3;     break;
                        default: break;
                    }
                    break;
                default: break;
            }
        }
 

Serilda

  • Guest
Re: [Beginner] Snake game, please help.
« Reply #5 on: March 19, 2016, 03:36:46 pm »
Oh,thanks so much! :D

Serilda

  • Guest
Re: [Beginner] Snake game, please help.
« Reply #6 on: March 19, 2016, 03:41:55 pm »
Do you think there's something else better for a beginner bitano? I've been searching for suggestions but couldn't find except this and pong.Thank you !

bitano

  • Jr. Member
  • **
  • Posts: 89
    • View Profile
Re: [Beginner] Snake game, please help.
« Reply #7 on: March 19, 2016, 03:47:19 pm »
Do you think there's something else better for a beginner bitano? I've been searching for suggestions but couldn't find except this and pong.Thank you !
Oh no i think Snake is fine! Just don't try to complete the game as fast as possible, but handle 1 challenge at a time :D and try to understand what's going on before moving to the next part :D

For instance, i think the next step might be for you to try and move the snake square around like in the snake game. Don't worry about anything else until that's working

Serilda

  • Guest
Re: [Beginner] Snake game, please help.
« Reply #8 on: March 19, 2016, 03:51:41 pm »
Thank you so much! =)

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: [Beginner] Snake game, please help.
« Reply #9 on: March 21, 2016, 01:18:44 pm »
Instead of moving each body part each time the snake moves, it can be simpler to just add a new piece where it moves to and remove one piece from the end. To make it grow, simply don't remove the piece at the end.

It may be better to use a std::deque instead of a std::vector for this but the vector can still handle this particular situation, although the deque does have pop_back and push_front!
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

bitano

  • Jr. Member
  • **
  • Posts: 89
    • View Profile
Re: [Beginner] Snake game, please help.
« Reply #10 on: March 21, 2016, 02:04:06 pm »
It may be better to use a std::deque instead of a std::vector for this
Oh hey... There's something new i've learned about then. Convenient! :D

 

anything