c-plus-plus
  1. c-plus-plus-snake-code-in-c

Snake Code in C++

The Snake game is a classic game that has been popular for years. It is a simple game where the player controls a snake that moves around on a board and eats food. As the snake eats more food, it grows longer, making it more difficult to control without colliding with walls or its own body.

Syntax

The Snake game code in C++ uses a variety of functions and data types, including arrays, loops, and classes. Below is a simplified version with the basic syntax:

// function to move the snake
void move_snake();

// function to check for collisions
bool check_collisions();

// function to update the screen
void update_screen();

// main function
int main() {
    // code to initialize the game
    initialize_game();

    // game loop
    while(1) {
        // move the snake
        move_snake();

        // check for collisions
        if(check_collisions()) {
            // end the game
            game_over();
            break;
        }

        // update the screen
        update_screen();

        // delay
        usleep(speed);
    }

    return 0;
}

Example

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <windows.h>

using namespace std;

// game variables
const int width = 20;
const int height = 20;
int x, y, fruitX, fruitY, score;
bool gameOver;
int tailX[100], tailY[100], nTail;
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir;

// function to set up the game
void Setup() {
    gameOver = false;
    dir = STOP;
    x = width / 2;
    y = height / 2;
    fruitX = rand() % width;
    fruitY = rand() % height;
    score = 0;
}

// function to draw the game board
void Draw() {
    system("cls");
    for (int i = 0; i < width+2; i++)
        cout << "#";
    cout << endl;

    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            if (j == 0)
                cout << "#";
            if (i == y && j == x)
                cout << "O";
            else if (i == fruitY && j == fruitX)
                cout << "F";
            else {
                bool print = false;
                for (int k = 0; k < nTail; k++) {
                    if (tailX[k] == j && tailY[k] == i) {
                        cout << "o";
                        print = true;
                    }
                }
                if (!print)
                    cout << " ";
            }
            if (j == width - 1)
                cout << "#";
        }
        cout << endl;
    }

    for (int i = 0; i < width+2; i++)
        cout << "#";
    cout << endl;

    cout << "Score:" << score << endl;
}

// function to take user input
void Input() {
    if (_kbhit()) {
        switch (_getch()) {
        case 'a':
            dir = LEFT;
            break;
        case 'd':
            dir = RIGHT;
            break;
        case 'w':
            dir = UP;
            break;
        case 's':
            dir = DOWN;
            break;
        case 'x':
            gameOver = true;
            break;
        }
    }
}

// function to update the game
void Logic() {
    int prevX = tailX[0];
    int prevY = tailY[0];
    int prev2X, prev2Y;
    tailX[0] = x;
    tailY[0] = y;
    for (int i = 1; i < nTail; i++) {
        prev2X = tailX[i];
        prev2Y = tailY[i];
        tailX[i] = prevX;
        tailY[i] = prevY;
        prevX = prev2X;
        prevY = prev2Y;
    }

    switch (dir) {
    case LEFT:
        x--;
        break;
    case RIGHT:
        x++;
        break;
    case UP:
        y--;
        break;
    case DOWN:
        y++;
        break;
    default:
        break;
    }

    if (x >= width) x = 0; else if (x < 0) x = width - 1;
    if (y >= height) y = 0; else if (y < 0) y = height - 1;

    for (int i = 0; i < nTail; i++)
        if (tailX[i] == x && tailY[i] == y)
            gameOver = true;

    if (x == fruitX && y == fruitY) {
        score += 10;
        fruitX = rand() % width;
        fruitY = rand() % height;
        nTail++;
    }
}

int main() {
    Setup();
    while (!gameOver) {
        Draw();
        Input();
        Logic();
        Sleep(50);
    }
    return 0;
}

Output

The output of the game is a playing board with the snake as well as the fruit that the snake must eat to gain points. The score is displayed on the screen and updates as the snake eats food.

Explanation

The Snake game code uses a variety of functions to create and run the game. The Setup function initializes the game variables, the Draw function creates the game board and displays it on-screen, the Input function waits for user input, and the Logic function updates the game based on the user's input.

To control the snake, the user presses the arrow keys to move up, down, left, or right. The snake grows longer as it eats food, and the game ends when the snake collides with a wall or its own body.

The game uses a series of arrays to keep track of the snake's tail, the position of the fruit, and the player's score. It also uses a Sleep function to slow down the game so that it is playable.

Use

The Snake game code in C++ can be used as a template for creating similar games or as a starting point for learning C++ programming. It uses a variety of useful programming concepts, such as loops, functions, and arrays, and can be customized to create games with different features.

Important Points

  • The Snake game code in C++ uses a variety of functions and data types, including arrays, loops, and classes.
  • The game is controlled by the user's input, and the snake grows longer as it eats food.
  • The game ends when the snake collides with a wall or its own body.
  • The game can be customized to include different features or styles.

Summary

The Snake game code in C++ is a classic example of a game created using programming concepts such as loops, functions, and data types. It is a good starting point for learning C++ programming and can be used as a template for creating similar games. The game is controlled by the user's input, and the snake grows longer as it eats food, with the game ending when the snake collides with a wall or its own body.

Published on: