Introduction

The Snake game is a classic and popular arcade game where the player controls a snake to eat food that appears on the screen. Each time the snake eats, it grows longer, and the game becomes more difficult. The goal is to avoid hitting the walls and the snake’s own body. In this tutorial, we will learn how to create the Snake game using the C programming language.

Objective

Our objective is to build the classic Snake game in C, where the snake moves around the screen, eats food, and grows longer. The game should end when the snake collides with the walls or itself.

Code

#include 
#include 
#include 
#include 
#include 

// Define the size of the game board
#define WIDTH 30
#define HEIGHT 20

// Declare the snake structure
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int nTail;
int gameOver;
int dir;

// Function to set up the game
void setup()
{
    gameOver = 0;
    dir = 0; // Initial direction (right)
    x = WIDTH / 2;
    y = HEIGHT / 2;
    fruitX = rand() % WIDTH;
    fruitY = rand() % HEIGHT;
    score = 0;
    nTail = 0;
}

// Function to draw the game screen
void draw()
{
    system("cls"); // Clear the screen

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

    for (int i = 0; i < HEIGHT; i++)
    {
        for (int j = 0; j < WIDTH; j++)
        {
            if (j == 0)
                printf("#"); // Draw left wall
            if (i == y && j == x)
                printf("O"); // Draw the head of the snake
            else if (i == fruitY && j == fruitX)
                printf("F"); // Draw the fruit
            else
            {
                int isPrintTail = 0;
                for (int k = 0; k < nTail; k++)
                {
                    if (tailX[k] == j && tailY[k] == i)
                    {
                        printf("o"); // Draw the snake's tail
                        isPrintTail = 1;
                    }
                }
                if (!isPrintTail)
                    printf(" "); // Empty space
            }
            if (j == WIDTH - 1)
                printf("#"); // Draw right wall
        }
        printf("\n");
    }

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

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

// Function to input the direction of the snake
void input()
{
    if (_kbhit())
    {
        switch (_getch())
        {
        case 'a':
            dir = 3; // Left
            break;
        case 'd':
            dir = 1; // Right
            break;
        case 'w':
            dir = 0; // Up
            break;
        case 's':
            dir = 2; // Down
            break;
        case 'x':
            gameOver = 1; // Exit the game
            break;
        }
    }
}

// Function to move the snake based on direction
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 0: y--; break; case 1: x++; break; case 2: y++; break; case 3: x--; 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 = 1; // Snake collides with itself
    }

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

// Function to run the game
void run()
{
    setup();
    while (!gameOver)
    {
        draw();
        input();
        logic();
        Sleep(100); // Slow down the game
    }
}

int main()
{
    run();
    return 0;
}

Explanation of the Program

This Snake game in C consists of several functions:

  • setup: Initializes the game variables like the snake’s initial position, the fruit’s position, and the score.
  • draw: Draws the game screen, including the snake, fruit, and game boundaries.
  • input: Reads user input to change the snake’s direction. The game stops if the player presses ‘x’.
  • logic: Controls the snake’s movement based on the current direction. It also checks for collisions with walls and self-collision. If the snake eats the fruit, it grows longer, and the score increases.
  • run: Starts and runs the game until the player loses.

How to Run the Program

  1. Install a C compiler (like GCC or Turbo C) on your system.
  2. Create a new file and copy-paste the code into it, e.g., snake_game.c.
  3. Compile the program using a C compiler. For example, run the following command in the terminal:
    gcc snake_game.c -o snake_game
  4. Execute the compiled program using the command:
    ./snake_game
  5. Use the W, A, S, and D keys to control the snake’s movement. Press X to exit the game.
© 2025 Learn Programming. All Rights Reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

2 thoughts on “Create the Classic Snake Game in C”

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)