How to Create Snake Game in C Programming - Step-by-Step Guide

Faraz

By Faraz -

Learn how to create a classic Snake Game in C programming. Follow this simple step-by-step guide to build and run your own game. Perfect for beginners!


create-snake-game-in-c-programming.webp

Introduction

The Snake Game is one of the most popular classic games ever created. It’s simple yet addictive, making it a great project for beginners learning C programming. In this blog, you’ll learn how to create your own version of the Snake Game using C. This guide will take you step-by-step through writing the code, compiling it, and running the game. By the end, you’ll have a fully functional Snake Game that you can customize or share with others.

Step-by-Step Guide to Creating Snake Game in C

1. Setting Up Your Development Environment

Before starting, ensure you have a C compiler installed. You can use GCC (GNU Compiler Collection) on Windows, Linux, or macOS. If you’re on Windows, you might prefer using an IDE like Code::Blocks or Dev-C++ that comes with an integrated compiler.

2. Understanding the Game Logic

The Snake Game is about controlling a snake that moves around the screen, eating food to grow longer. The snake loses the game if it runs into the wall or itself. The game logic involves:

  • Moving the snake in a specified direction.
  • Checking for collision with the walls or the snake’s own body.
  • Randomly generating food on the screen.
  • Keeping track of the score based on how long the snake grows.

3. Creating the Game Board

Start by defining the game board. You can use a simple 2D array to represent the grid where the snake will move. For example, a 20x20 grid might be suitable for this purpose. Each cell in the array can store a value indicating whether it’s empty, part of the snake, or contains food.

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

#define WIDTH 20
#define HEIGHT 20
  • stdio.h: For standard input/output functions.
  • stdlib.h: For dynamic memory allocation and random number generation.
  • conio.h: For console input/output functions (e.g., _kbhit() and _getch()).
  • WIDTH and HEIGHT: Dimensions of the game board.

4. Initializing the Snake

The snake can be represented as an array of coordinates, where each element stores the position of a segment of the snake’s body. Start with the snake at the center of the board.

char board[HEIGHT][WIDTH];
int snakeX[100], snakeY[100];
int snakeLength = 3;
int gameOver = 0;
int dx = 0, dy = -1; 
int foodX, foodY;

void initializeGame() {
    for (int i = 0; i < HEIGHT; i++) {
        for (int j = 0; j < WIDTH; j++) {
            board[i][j] = ' ';
        }
    }

    for (int i = 0; i < snakeLength; i++) {
        snakeX[i] = WIDTH / 2;
        snakeY[i] = HEIGHT / 2 + i;
        board[snakeY[i]][snakeX[i]] = 'S';
    }

    generateFood();
}
  • board: 2D array to represent the game board.
  • snakeX and snakeY: Arrays to store the snake's position.
  • snakeLength: Initial length of the snake.
  • gameOver: Flag to indicate if the game is over.
  • dx and dy: Direction of movement for the snake.
  • foodX and foodY: Position of the food.

5. Generating Food

The food can appear randomly on the board. Make sure the food doesn’t spawn where the snake is currently located.

void generateFood() {
    do {
        foodX = rand() % (WIDTH - 2) + 1;  
        foodY = rand() % (HEIGHT - 2) + 1; 
    } while (board[foodY][foodX] != ' ');
}

6. Moving the Snake

The snake moves by updating its head position based on user input (up, down, left, right) and shifting the body to follow the head.

void moveSnake() {
    int newX = snakeX[0] + dx;
    int newY = snakeY[0] + dy;

    for (int i = snakeLength - 1; i > 0; i--) {
        snakeX[i] = snakeX[i - 1];
        snakeY[i] = snakeY[i - 1];
    }

    snakeX[0] = newX;
    snakeY[0] = newY;
}

7. Detecting Collisions

Check for collisions with the walls or the snake’s body. If a collision is detected, the game ends.

int checkCollision() {
    if (snakeX[0] < 1 || snakeX[0] >= WIDTH - 1 || snakeY[0] < 1 || snakeY[0] >= HEIGHT - 1) {
        return 1; // Collision with wall
    }
    for (int i = 1; i < snakeLength; i++) {
        if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
            return 1; // Collision with self
        }
    }
    return 0;
}

8. Eating the Food

If the snake’s head reaches the food, the snake grows longer, and new food is generated.

void eatFood() {
    if (snakeX[0] == foodX && snakeY[0] == foodY) {
        snakeLength++;
        generateFood();
    }
}

9. Updating the Board

After each move, update the board to reflect the snake’s new position and the food location. Then, print the board to the console.

void updateBoard() {
    for (int i = 0; i < HEIGHT; i++) {
        for (int j = 0; j < WIDTH; j++) {
            board[i][j] = ' ';
        }
    }

    for (int i = 0; i < snakeLength; i++) {
        board[snakeY[i]][snakeX[i]] = 'S';
    }

    board[foodY][foodX] = 'F'; // Place food on the board
}

10. Draw the Board

Display the game board and score:

void drawBoard() {
    system("cls");
    for (int i = 0; i < WIDTH + 2; i++) printf("#");
    printf("\n");

    for (int i = 0; i < HEIGHT; i++) {
        printf("#");
        for (int j = 0; j < WIDTH; j++) {
            printf("%c", board[i][j]);
        }
        printf("#\n");
    }

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

    // Display score at the bottom
    printf("Score: %d\n", snakeLength - 3);
}

11. Implement the changeDirection Function:

Change the snake's direction based on user input:

void changeDirection(char key) {
    switch (key) {
        case 'w': dx = 0; dy = -1; break;
        case 's': dx = 0; dy = 1; break;
        case 'a': dx = -1; dy = 0; break;
        case 'd': dx = 1; dy = 0; break;
    }
}

12. Run the game

Run the game loop, handle user input, update the game state, and draw the board:

int main() {
    initializeGame();

    while (!gameOver) {
        if (_kbhit()) {
            char key = _getch();
            changeDirection(key);
        }

        moveSnake();
        gameOver = checkCollision();
        eatFood();
        updateBoard();
        drawBoard();

        _sleep(200); // Control the game speed
    }

    printf("Game Over! Your final score is: %d\n", snakeLength - 3);
    return 0;
}

Compiling and Running the Program

To compile and run your Snake Game program, follow these steps:

  1. Compile the Program
    • If you're using GCC, open the terminal and navigate to the directory containing your source code file (e.g., snake_game.c). Then, run the following command:
      gcc -o snake_game snake_game.c
  2. Run the Program
    • After compiling, run the executable:
      ./snake_game

Conclusion

Creating a Snake Game in C programming is a great way to practice your coding skills and understand basic game development concepts. By following this step-by-step guide, you’ve learned how to set up the game board, initialize the snake, move it around, detect collisions, and handle user input. Now, you can customize your Snake Game by adding new features or improving the gameplay.

This guide was designed to be simple and straightforward, making it easier for beginners to understand. Keep practicing, and soon you'll be able to create even more complex games and applications using C.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺