Create a Snake Game in C Language with Free Codes

Snake Game in C Thumbnail

Table of Contents

Introduction – Snake Game

Game development is the most popular and famous field of all time with Amazing Salary packages. Most of the game developers used C Language to develop the many things in Game. So today we are going to create a Snake Game in C Language which is the Advance topic of College Level projects. Here we explain each code group which is used for create a Console Based Snake Game by the Use of C Language.

Overview of the Game

This Snake Game involves controlling a snake moving around a bounded area, consuming food items to grow in length. The primary challenges is to avoid colliding with the boundaries of the game area or with snake’s own body. The game will difficult with increase of the snake’s lenght.

C Language Question – Answers

Code Structure

Here is the explanation of Snake Game Code Structure,

Part : 1 – Initialization (setup() function)

void setup() {
    // Initialize game variables
    snake_length = 1;
    snakeX[0] = WIDTH / 2;
    snakeY[0] = HEIGHT / 2;
    fruitX = rand() % WIDTH;
    fruitY = rand() % HEIGHT;
    game_over = 0;
    score = 0;
}
  • Here the ‘setup()’ function initializes the game state, setting the initial position of the snake (‘snakeX[0]’) and (‘snakeY[0]’) at the center of the game area (‘WIDTH’ and “HEIGHT”).
  • A random position is chosen for the first fruit (‘fruitX’ and ‘fruitY’).
  • ‘game_over’ and ‘score’ variables are initialized.

Part : 2 – Drwaing the Game (‘draw()’ function)

void draw() {
    system("cls"); // Clear the console screen
    // Draw upper wall
    for (int i = 0; i < WIDTH + 2; i++)
        printf("#");
    printf("\n");

    // Draw game area and entities
    for (int i = 0; i < HEIGHT; i++) {
        for (int j = 0; j < WIDTH; j++) {
            // Draw walls, snake, fruit, and empty spaces
            // ...
        }
        printf("\n");
    }

    // Draw lower wall
    for (int i = 0; i < WIDTH + 2; i++)
        printf("#");
    printf("\n");

    printf("Score: %d\n", score); // Display the player's score
}
  • The ‘draw()’ functon is responsible for rendering the game state onto the console screen.
  • Walls, snake segments, and the fruit are represented using ASCII characters (‘#’, ‘O’, ‘F’, etc.).
  • The function clears the screen (‘system(“cls”)’) and then iteratively prints the game board.

Part : 3 – Handling User Input (‘input()’ function)

void input() {
    if (_kbhit()) { // Check if a key is pressed
        switch (_getch()) {
            case UP:
                snakeY[0]--;
                break;
            case DOWN:
                snakeY[0]++;
                break;
            case LEFT:
                snakeX[0]--;
                break;
            case RIGHT:
                snakeX[0]++;
                break;
            default:
                break;
        }
    }
}
  • The ‘_kbhit()’ function from ‘<conio.h>’ checks if a key has been pressed.
  • ‘_getch()’ retrieves the pressed key.
  • The arrow keys (UP, DOWN, LEFT, RIGHT) control the movement of the snake’s head.

Part : 4 – Game Logic (‘logic()’ function)

void logic() {
    // Move the snake
    // ...

    // Check collision with walls and itself
    // ...

    // Check if snake eats fruit
    // ...
}
  • Here the logic()function which is used for handles the core game logic like:
    • Moving the snake by updating the positions of its segments.
    • Checking for collisions with walls or the snake’s own body.
    • Detecting if the snake has consumed a fruit, updating the score and growing the snake.

Part – 5 Main Game and Loop Flow

int main() {
    setup();

    while (!game_over) {
        draw();
        input();
        logic();
        Sleep(100); // Control snake's speed
    }

    printf("Game Over!\n");
    printf("Your Score: %d\n", score);

    return 0;
}
  • Themain()function initializes the game (‘setup()‘) and enters a continuous loop until the game ends (game_overbecomes true).
  • Within the loop, the game state is updated (‘draw()‘, ‘input()‘, ‘logic()‘) and the screen is refreshed.
  • After the game loop, the final score is displayed along with a game-over message.

Complete Project Codes – Snake Game

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

#define WIDTH 20
#define HEIGHT 20
#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77

int snakeX[50], snakeY[50];
int fruitX, fruitY;
int snake_length;
int game_over;
int score;

void setup() {
    snake_length = 1;
    snakeX[0] = WIDTH / 2;
    snakeY[0] = HEIGHT / 2;
    fruitX = rand() % WIDTH;
    fruitY = rand() % HEIGHT;
    game_over = 0;
    score = 0;
}

void draw() {
    system("cls");
    int i, j;
    // Draw upper wall
    for (i = 0; i < WIDTH + 2; i++)
        printf("#");
    printf("\n");

    for (i = 0; i < HEIGHT; i++) {
        for (j = 0; j < WIDTH; j++) {
            if (j == 0)
                printf("#"); // Draw left wall
            if (i == snakeY[0] && j == snakeX[0])
                printf("O"); // Draw snake's head
            else if (i == fruitY && j == fruitX)
                printf("F"); // Draw fruit
            else {
                int isBodyPart = 0;
                for (int k = 1; k < snake_length; k++) {
                    if (i == snakeY[k] && j == snakeX[k]) {
                        printf("o"); // Draw snake's body
                        isBodyPart = 1;
                        break;
                    }
                }
                if (!isBodyPart)
                    printf(" ");
            }
            if (j == WIDTH - 1)
                printf("#"); // Draw right wall
        }
        printf("\n");
    }

    // Draw lower wall
    for (i = 0; i < WIDTH + 2; i++)
        printf("#");
    printf("\n");

    printf("Score: %d\n", score);
}

void input() {
    if (_kbhit()) {
        switch (_getch()) {
            case UP:
                snakeY[0]--;
                break;
            case DOWN:
                snakeY[0]++;
                break;
            case LEFT:
                snakeX[0]--;
                break;
            case RIGHT:
                snakeX[0]++;
                break;
            default:
                break;
        }
    }
}

void logic() {
    // Move the snake
    for (int i = snake_length - 1; i > 0; i--) {
        snakeX[i] = snakeX[i - 1];
        snakeY[i] = snakeY[i - 1];
    }

    // Check collision with wall
    if (snakeX[0] < 0 || snakeX[0] >= WIDTH || snakeY[0] < 0 || snakeY[0] >= HEIGHT)
        game_over = 1;

    // Check collision with itself
    for (int i = 1; i < snake_length; i++) {
        if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i])
            game_over = 1;
    }

    // Check if snake eats fruit
    if (snakeX[0] == fruitX && snakeY[0] == fruitY) {
        score += 10;
        snake_length++;
        fruitX = rand() % WIDTH;
        fruitY = rand() % HEIGHT;
    }
}

int main() {
    setup();

    while (!game_over) {
        draw();
        input();
        logic();
        Sleep(100); // Control snake's speed
    }

    printf("Game Over!\n");
    printf("Your Score: %d\n", score);

    return 0;
}

Conclusion

Here we create a Snake Game in C Language which is the most Advance Level Project for College Students if they want to become a game Developer. This is the boost for game skill, because of it’s complicated structure understanding.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top