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
- Install a C compiler (like GCC or Turbo C) on your system.
- Create a new file and copy-paste the code into it, e.g.,
snake_game.c. - Compile the program using a C compiler. For example, run the following command in the terminal:
gcc snake_game.c -o snake_game
- Execute the compiled program using the command:
./snake_game
- Use the W, A, S, and D keys to control the snake’s movement. Press X to exit the game.


This paragraph is reaally a good one it helps new web users, who
are wishing for blogging. http://boyarka-inform.com/
This paragraph is really a good one it helps nnew web users, who are wising
for blogging. http://boyarka-inform.com/
https://steroidwiki.com/forum/topic/2679-car-rental-protugal-airport.html
https://www.zazzle.co.uk/mbr/238433441106677515
You are mistaken. I suggest it to discuss.
https://www.facer.io/user/2nu8iGFxJN
элитные проститутки
Nassau Airport Shuttle Transfer is your trusted partner for group airport shuttle Nassau Bahamas. Enjoy prompt Nassau airport shuttle service and reliable private Nassau airport transportation with an efficient shuttle transfer from Nassau airport.
I apologise, but, in my opinion, you are not right. I am assured. Let’s discuss it.
——
buy thailand virtual phone number online https://virtual-local-numbers.com/countries/33-thailand.html for calls, sms, registration (otp)
Анонимная архитектура кракен даркнет онион базируется на луковой маршрутизации где каждое соединение проходит три узла от пользователя до сервера и три обратно.
Uwielbiasz hazard? nv casino no deposit bonus: rzetelne oceny kasyn, weryfikacja licencji oraz wybor bonusow i promocji dla nowych i powracajacych graczy. Szczegolowe recenzje, porownanie warunkow i rekomendacje dotyczace odpowiedzialnej gry.
Envie de parier telecharger 1xbet est une plateforme de paris sportifs en ligne pour la Republique democratique du Congo. Football et autres sports, paris en direct et d’avant-match, cotes, resultats et statistiques. Presentation des fonctionnalites du service.
Le site web 1xbet cd apk propose des informations sur les paris sportifs, les cotes et les evenements en direct. Football, tournois populaires, cotes et statistiques y sont presentes. Ce site est ideal pour se familiariser avec les fonctionnalites de la plateforme.
Online 1xbet rdc telecharger est une plateforme de paris sportifs en ligne. Championnats de football, cotes en direct et resultats sont disponibles. Page d’information sur le service et ses fonctionnalites pour les utilisateurs de la region.
студия косметологии косметология москва
Do you love gambling? verified crypto deposit casinos allow you to play online using Bitcoin and altcoins. Enjoy fast deposits, instant payouts, privacy, slots, and live dealer games on reliable, crypto-friendly platforms.
Gioca a Crazy Time con croupier dal vivo su una piattaforma legale in Italia con bonus esclusivi e pagamenti veloci.
Registrati ora e prova subito il demo ogni giorno!
vincita piu alta crazy time [url=http://www.clearcreekgamefowl.com]https://clearcreekgamefowl.com/[/url]
تتضمن 888starz مصر مجموعة واسعة من الألعاب الرياضية والأحداث التي يمكن للمستخدمين المشاركة فيها
مراهنات 888 [url=http://www.888starz.onl/eg]https://888starz.onl/eg/[/url]
888starz Egypt تتميز بتوفر العديد من طرق الدفع الآمنة
888starz تعتمد على تقنيات حديثة لتوفير تجربة لعب آمنة ومثيرة
تنزيل تطبيق 888 [url=https://888starz.onl/eg/apk/]https://888starz.onl/eg/apk/[/url]
888starz مصر تتميز بسهولة استخدام موقعها الإلكتروني وتطبيقاتها
888starz مصر تعمل على توفير تجربة مميزة وممتعة للمراهنين
كازينو 888 تسجيل الدخول [url=http://www.888starz.onl/eg]https://888starz.onl/eg/[/url]
888starz Egypt تُقدم عروض وتخفيضات đặc biệt للمستخدمين الجدد
تعتبر 888starz من الشركات المرموقة فى مجال المراهنات الرياضية فى مصر
ستار 888 للمراهنات [url=http://www.888starz.onl/eg]https://888starz.onl/eg/[/url]
توفر 888starz مصر إمكانية المراهنة على مختلف الرياضات وأحداثها
888starz مصر تعمل على توفير تجربة مميزة وممتعة للمراهنين
تنزيل 888 [url=https://888starz.onl/eg/apk/]تنزيل 888[/url]
توفر 888starz مصر إمكانية المراهنة على مختلف الرياضات وأحداثها