Ticker

6/recent/ticker-posts

Snake Game in C++

 Snake Game in C++

Welcome to Programming Chaska! In this post, I will share the program in C++ to make Snake Game. Make sure to Subscribe to Programming Chaska to get the latest updates and Don't forget to share it with friends.


Note- You must have the SFML library installed and included its path to your Programming IDE.

Game Preview:

Snake Game


Game over


Game Controls:

Left arrow Key - To move the snake Left 
Right arrow Key - To move the snake Right
Up arrow Key - To move the snake Up
Down arrow Key - To move the snake Down

Steps to make Game:

  1. Make a new folder (say, Snake).
  2. In the Arkanoid folder make your .cpp file (say main.cpp) and a folder whose name must be "images".
  3. Download All the images given below and keep them in the "images" folder with their specific name as given below each image.
  4. Copy and Compile the code given below to generate its executable (.exe) file.
  5. At last, Run that .exe file to play the game.

Images Used:

over.png

red.png

green.png

white.png

Note:- I have used sans font to display the score. You have to download any font and name it as "font" and it must be kept in the "images" folder.


Game Code:

#include <SFML/Graphics.hpp>
#include <time.h>
#include <sstream>

using namespace sf;

int N = 30M = 20;
int size = 16;
int w = size * N;
int h = size * M;
int speed = 20;
int dirnum = 4;
int fscore=0;
bool gameIsAlive = true;

struct Snake
{
    int xy;
s[100];

struct Fruit
{
    int xy;
f;

void Tick()
{
    for (int i = numi > 0; --i)
    {
        s[i].x = s[i - 1].x;
        s[i].y = s[i - 1].y;
    }

    if (dir == 0)
        s[0].y += 1;
    if (dir == 1)
        s[0].x -= 1;
    if (dir == 2)
        s[0].x += 1;
    if (dir == 3)
        s[0].y -= 1;

    if ((s[0].x == f.x) && (s[0].y == f.y))
    {
        fscore++;
        num++;
        if (speed < 60)
            speed++;
        f.x = rand() % N;
        f.y = rand() % M;
    }

    if (s[0].x > N)
        s[0].x = 0;
    if (s[0].x < 0)
        s[0].x = N;
    if (s[0].y > M)
        s[0].y = 0;
    if (s[0].y < 0)
        s[0].y = M;

    //Checking for Snake Collision
    for (int i = 1i < numi++)
        if (s[0].x == s[i].x && s[0].y == s[i].y)
        {
            num = i;
            gameIsAlive = false;
        }
}

int main()
{
    srand(time(0));

    RenderWindow window(VideoMode(wh), "Snake Game!");

    sf::Font myFont;
    if (!myFont.loadFromFile("images/font.ttf"))
    {
    }
    Texture t1t2t3t4;
    t1.loadFromFile("images/white.png");
    t2.loadFromFile("images/red.png");
    t3.loadFromFile("images/green.png");
    t4.loadFromFile("images/over.png");
    Sprite sprite1(t1);
    Sprite sprite2(t2);
    Sprite sprite3(t3);
    Sprite sover(t4);

    Clock clock;
    float timer = 0delay = 0.1;

    f.x = 10;
    f.y = 10;

    sf::Text score;
    score.setFont(myFont);
    score.setFillColor(sf::Color::Blue);
    score.setStyle(sf::Text::Regular);
    score.setString("Score");
    score.setCharacterSize(25);
    score.setPosition(25130); //25,130

    sf::Text scoreCurrent;
    scoreCurrent.setFont(myFont);
    scoreCurrent.setFillColor(sf::Color::Green);
    scoreCurrent.setStyle(sf::Text::Regular);
    scoreCurrent.setCharacterSize(25);
    scoreCurrent.setPosition(45175);

    sf::RectangleShape scoreRectangle;
    scoreRectangle.setSize(sf::Vector2f(10050));
    scoreRectangle.setOutlineThickness(1);
    scoreRectangle.setOutlineColor(sf::Color::White);
    scoreRectangle.setFillColor(sf::Color::Black);
    scoreRectangle.setPosition(25165);

    while (window.isOpen())
    {

        window.setFramerateLimit(speed);
        float time = clock.getElapsedTime().asSeconds();
        clock.restart();
        timer += time;

        Event e;
        while (window.pollEvent(e))
        {
            if (e.type == Event::Closed)
                window.close();
        }
        if (gameIsAlive)
        {
            if (Keyboard::isKeyPressed(Keyboard::Left) && dir != 2)
                dir = 1;
            if (Keyboard::isKeyPressed(Keyboard::Right) && dir != 1)
                dir = 2;
            if (Keyboard::isKeyPressed(Keyboard::Up) && dir != 0)
                dir = 3;
            if (Keyboard::isKeyPressed(Keyboard::Down) && dir != 3)
                dir = 0;

            if (timer > delay)
            {
                timer = 0;
                Tick();
            }

            ////// draw  ///////

            window.clear();

            for (int i = 0i < Ni++)
                for (int j = 0j < Mj++)
                {
                    sprite1.setPosition(i * sizej * size);
                    window.draw(sprite1);
                }

            for (int i = 0i < numi++)
            {
                sprite2.setPosition(s[i].x * sizes[i].y * size);
                window.draw(sprite2);
            }

            sprite3.setPosition(f.x * sizef.y * size);
            window.draw(sprite3);

            window.display();
        }
        else
        {
            ////// draw  ///////

            window.clear();
            std::stringstream s;
            s << fscore;
            scoreCurrent.setString(s.str());

            window.draw(sover);
            window.draw(score);
            window.draw(scoreRectangle);
            window.draw(scoreCurrent);
            window.display();
        }
    }

    return 0;
}


If you have any doubts/questions related to Program, or if you want to give any suggestionsfeel free to comment below. Subscribe to Programming Chaska for the latest programming updates and Don't forget to share it with friends. 

Post a Comment

0 Comments