Snake Game in C - GeeksforGeeks (2024)

Table of Contents
C C Please Login to comment... FAQs

Last Updated : 10 Feb, 2021

Summarize

Comments

Improve

In this article, the task is to implement a basic Snake Game. Below given some functionalities of this game:

  • The snake is represented with a 0(zero) symbol.
  • The fruit is represented with an *(asterisk) symbol.
  • The snake can move in any direction according to the user with the help of the keyboard (W, A, S, D keys).
  • When the snake eats a fruit the score will increase by 10 points.
  • The fruit will generate automatically within the boundaries.
  • Whenever the snake will touch the boundary the game is over.

Steps to create this game:

  • There will be four user-defined functions.
  • Build a boundary within which the game will be played.
  • The fruits are generated randomly.
  • Then increase the score whenever the snake eats a fruit.

The user-defined functions created in this program are given below:

  • Draw(): This function creates the boundary in which the game will be played.
  • Setup(): This function will set the position of the fruit within the boundary.
  • Input(): This function will take the input from the keyboard.
  • Logic(): This function will set the movement of the snake.

Built-in functions used:

  • kbhit(): This function in C is used to determine if a key has been pressed or not. To use this function in a program include the header file conio.h. If a key has been pressed, then it returns a non-zero value otherwise it returns zero.
  • rand(): The rand() function is declared in stdlib.h. It returns a random integer value every time it is called.

Header files and variables:

  • The header files and variables used in this program are:

  • Here include the <unistd.h> header file for the sleep() function.

Draw(): This function is responsible to build the boundary within which the game will be played.

Below is the C program to build the outline boundary using draw():

C

// C program to build the outline

// boundary using draw()

#include <stdio.h>

#include <stdlib.h>

int i, j, height = 30;

int width = 30, gameover, score;

// Function to draw a boundary

void draw()

{

// system("cls");

for (i = 0; i < height; i++) {

for (j = 0; j < width; j++) {

if (i == 0 || i == width - 1 || j == 0

|| j == height - 1) {

printf("#");

}

else {

printf(" ");

}

}

printf("\n");

}

}

// Driver Code

int main()

{

// Function Call

draw();

return 0;

}

Output:

############################### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###############################

setup():nThisbfunction is used to write the code to generate the fruit within the boundary using rand() function.

  • Using rand()%20 because the size of the boundary is length = 20 and width = 20 so the fruit will generate within the boundary.

Input(): In this function, the programmer writes the code to take the input from the keyboard (W, A, S, D, X keys).

logic(): Here, write all the logic for this program like for the movement of the snake, for increasing the score, when the snake will touch the boundary the game will be over, to exit the game and the random generation of the fruit once the snake will eat the fruit.

sleep(): This function in C is a function that delays the program execution for the given number of seconds. In this code sleep() is used to slow down the movement of the snake so it will be easy for the user to play.

main(): From the main() function the execution of the program starts. It calls all the functions.

Below is the C program to build the complete snake game:

C

// C program to build the complete

// snake game

#include <conio.h>

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

int i, j, height = 20, width = 20;

int gameover, score;

int x, y, fruitx, fruity, flag;

// Function to generate the fruit

// within the boundary

void setup()

{

gameover = 0;

// Stores height and width

x = height / 2;

y = width / 2;

label1:

fruitx = rand() % 20;

if (fruitx == 0)

goto label1;

label2:

fruity = rand() % 20;

if (fruity == 0)

goto label2;

score = 0;

}

// Function to draw the boundaries

void draw()

{

system("cls");

for (i = 0; i < height; i++) {

for (j = 0; j < width; j++) {

if (i == 0 || i == width - 1

|| j == 0

|| j == height - 1) {

printf("#");

}

else {

if (i == x && j == y)

printf("0");

else if (i == fruitx

&& j == fruity)

printf("*");

else

printf(" ");

}

}

printf("\n");

}

// Print the score after the

// game ends

printf("score = %d", score);

printf("\n");

printf("press X to quit the game");

}

// Function to take the input

void input()

{

if (kbhit()) {

switch (getch()) {

case 'a':

flag = 1;

break;

case 's':

flag = 2;

break;

case 'd':

flag = 3;

break;

case 'w':

flag = 4;

break;

case 'x':

gameover = 1;

break;

}

}

}

// Function for the logic behind

// each movement

void logic()

{

sleep(0.01);

switch (flag) {

case 1:

y--;

break;

case 2:

x++;

break;

case 3:

y++;

break;

case 4:

x--;

break;

default:

break;

}

// If the game is over

if (x < 0 || x > height

|| y < 0 || y > width)

gameover = 1;

// If snake reaches the fruit

// then update the score

if (x == fruitx && y == fruity) {

label3:

fruitx = rand() % 20;

if (fruitx == 0)

goto label3;

// After eating the above fruit

// generate new fruit

label4:

fruity = rand() % 20;

if (fruity == 0)

goto label4;

score += 10;

}

}

// Driver Code

void main()

{

int m, n;

// Generate boundary

setup();

// Until the game is over

while (!gameover) {

// Function Call

draw();

input();

logic();

}

}

Output:

Demonstration:



S

souravwork14

Snake Game in C - GeeksforGeeks (7)

Improve

Previous Article

Telecom Billing System in C

Next Article

C program to display month by month calendar for a given year

Please Login to comment...

Snake Game in C - GeeksforGeeks (2024)

FAQs

Is Snake game easy to code? ›

Snake is a fun game to make as it doesn't require a lot of code (less than 100 lines with all comments removed). This is a basic implementation of the snake game, but it's missing a few things intentionally and they're left as further exploration for the reader.

What is the objective of the Snake game in C? ›

- Move the snake in any direction as per the user by using the keys – W, A, S, D. - Increase the score by 10 points, when the snake eats a fruit. - You will see that the fruit is generated automatically within the boundaries. - As soon as the snake touches the boundary, the game gets over.

Can you code a game in C? ›

It can still do it; it's just generally easier with more modern languages. There are many ways to achieve this. First decide the game, is it going to be 2D or 3D. If it is going to be 3D, then use OpenGL.

Which programming language is used in Snake game? ›

Java, with its robust object-oriented programming capabilities, has been a popular choice for game development.

Is Python the hardest code? ›

Which is harder, C++ or Python? C++ is considered a more difficult language to learn than Python, as it has a complex syntax and a steep learning curve. It has many features, such as templates, namespaces, and multiple inheritances, making the code difficult to understand and debug.

Can we make Snake game in C++? ›

Snake Code in C++ Snake is a classic game that includes a growing line represented as a snake that can consume items, change direction, and grow in length. As the snake grows larger in length, the difficulty of the game grows. In this article, we will create a snake game using a C++ program.

Can I make a Snake game in C? ›

This Snake Game Mini Project in C is a basic console program with no graphics. You may play the famous "Snake Game" in this project exactly as you would anywhere else. To move the snake, use the up, down, right, and left arrows.

How to make a Snake game in C sharp? ›

Written Tutorial –
  1. Click OK for the project to be created in Visual Studio.
  2. Right click on the SnakeGame inside the Solutions Explorer, hover over Add, click on Class. ...
  3. In the name box type Circle (Capital C) and Click add. ...
  4. The circle class has been added to the program. ...
  5. Now we have all our classes added to the project.

What is the algorithm used in the Snake game? ›

This Greedy Best-First Search algorithm has a one-move horizon and only considers moving the snake to the position on the board that appears to be closest to the goal, i.e. apple. We use Manhattan distance to define how close the snake head is to the apple.

Does anyone still code in C? ›

Despite the prevalence of higher-level languages, the C programming language continues to empower the world. There are plenty of reasons to believe that C programming will remain active for a long time. Here are some reasons that C is unbeatable, and almost mandatory, for certain applications.

Do I need to learn C before C++? ›

C ++ can be learnt directly without the knowledge of C. C is a basic programming language where as C++ is pure object oriented language. An added advantage of learning the basics of C first is that every part of what you are probably going to learn in C++ would already be covered by you while learning C.

Is C good for game programming? ›

Both C and C++ are commonly used for game development, but C++ is generally considered to be the better choice.

Is coding a Snake game hard? ›

In this blog, I'm going to go through the step-by-step process of coding the game Snake, as it is commonly prescribed to beginner programmers as the game to code. However, I wouldn't personally recommend this game to beginner programmers as Snake certainly has some tough quirks you have to figure out.

What is the logic behind the Snake game? ›

The game scores a point when the snake eats a piece of food, which involves moving to the same coordinate location as the next item in the food array. Food items appear sequentially, with the next item making its appearance only after the current one has been eaten.

What technology is used in the Snake game? ›

Snake Game Using Deep Reinforcement Learning

In this research, the researchers develop a refined Deep Reinforcement Learning model to enable the autonomous agent to play the classical SnakeGame, whose constraint gets stricter as the game progresses.

Is snake a programming language? ›

Python is called a snake language because the language was named after the Monty Python comedy group, and not after the snake. The creator of Python, Guido van Rossum, named the language after the comedy group because he was a big fan of their work.

Can you code snake in Python? ›

well, Building the Snake game in Python lets us be creative and improve our computer skills simultaneously. Python is the best language for this project because it is easy to learn and can be used in many ways. Don't worry if you've never used Python before.

What algorithm is used in the Snake game? ›

This Greedy Best-First Search algorithm has a one-move horizon and only considers moving the snake to the position on the board that appears to be closest to the goal, i.e. apple. We use Manhattan distance to define how close the snake head is to the apple.

Is it easy to code a game? ›

And the good news is that it's not as difficult as you might think. Plenty of resources are available to help you get started, and with patience and perseverance, you'll be coding your games in no time. One of the best things about coding games is that there are no rules.

Top Articles
SOUTHEAST GEORGIA HEALTH SYSTEM- BRUNSWICK CAMPUS
Craigslist Leads to Fully Booked Rentals in a Week – Leasey.AI
Sugar And Spice 1976 Pdf
Att Login Prepaid
Gateway Login Georgia Client Id
Busted Newspaper Longview Texas
Selinas Gold Full Movie Netflix
Paul Mccombs Nashville Tn
Ubreakifix Laptop Repair
Hannaford Weekly Flyer Manchester Nh
Bbaexclusive
Olde Kegg Bar & Grill Portage Menu
Texas Motors Specialty Photos
High school football: Photos from the top Week 3 games Friday
636-730-9503
Python Regex Space
Caldwell Idaho Craigslist
Ap Computer Science Principles Grade Calculator
Arkansas Craigslist Cars For Sale By Owner
Madison Legistar
Sona Twu
Ayala Rv Storage
Account Now Login In
Dayinew
Student Exploration Gravity Pitch
120 temas Enem 2024 - Cálculo
Mark Rosen announces his departure from WCCO-TV after 50-year career
Showcameips
King of Battle and Blood
Koinonikos Tourismos
Kagtwt
South Louisiana Community College Bookstore
About Us - Carrols Corporation
Does Walmart have Affirm program? - Cooking Brush
Krunker.io . Online Games . BrightestGames.com
631 West Skyline Parkway, Duluth, MN 55806 | Compass
Rage Room Longmont
Ebk Jaaybo Net Worth
Bfri Forum
Mudae Disable Tags
Pressconnects Obituaries Recent
Ihop Ralph Ave
Pre-Order Apple Watch Series 10 – Best Prices in Dubai, UAE
Showbiz Waxahachie Bowling Hours
Hyb Urban Dictionary
Plusword 358
'We weren't done': Spacebar Arcade closes its doors for good
Ultimate Guide to Los Alamos, CA: A Small Town Big On Flavor
Ebony Ts Facials
Salmon Fest 2023 Lineup
Conan Exiles Rhino Guide - Conan Fanatics
South Florida residents must earn more than $100,000 to avoid being 'rent burdened'
Latest Posts
Article information

Author: Jeremiah Abshire

Last Updated:

Views: 5707

Rating: 4.3 / 5 (74 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Jeremiah Abshire

Birthday: 1993-09-14

Address: Apt. 425 92748 Jannie Centers, Port Nikitaville, VT 82110

Phone: +8096210939894

Job: Lead Healthcare Manager

Hobby: Watching movies, Watching movies, Knapping, LARPing, Coffee roasting, Lacemaking, Gaming

Introduction: My name is Jeremiah Abshire, I am a outstanding, kind, clever, hilarious, curious, hilarious, outstanding person who loves writing and wants to share my knowledge and understanding with you.