0% found this document useful (0 votes)
4 views

Senha c Programming

The document describes the implementation of the classic Snake Game in C programming, where players control a snake to eat fruit and grow longer while avoiding collisions. Key features include a game loop, basic controls, a score system, collision detection, and random fruit generation displayed in a console interface. The project serves as an educational tool for beginners to learn fundamental programming concepts such as arrays and user input handling.

Uploaded by

avhadsss249
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Senha c Programming

The document describes the implementation of the classic Snake Game in C programming, where players control a snake to eat fruit and grow longer while avoiding collisions. Key features include a game loop, basic controls, a score system, collision detection, and random fruit generation displayed in a console interface. The project serves as an educational tool for beginners to learn fundamental programming concepts such as arrays and user input handling.

Uploaded by

avhadsss249
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Introduction

______________________________________________

The Snake Game is a classic video game that has been widely popular since the
1970s. It involves a snake that moves around the screen, eating food (usually
represented by a fruit), and growing longer with each food item it eats.

The goal is to keep the snake alive and avoid colliding with the walls or itself. The
game continues until the snake hits a boundary or itself, at which point the game
ends.

In this version, the game is implemented in the C programming language, where


you control the snake using the keyboard.

This version of Snake runs on a console screen (CLI), and the game is developed
in a simple yet effective way using the standard libraries and basic programming
concepts.

1
Abstract

______________________________________________

The Snake game is developed in C, where the snake is represented by a series of


characters. The snake moves on a grid where the player can control the direction of
the snake using the arrow keys or predefined keys (w, a, s, d).

The objective is to guide the snake to eat the fruit (represented by *), which causes
the snake to grow longer and increase the player's score. The game ends when the
snake hits the wall or itself.

The snake is drawn on the console using ASCII characters, and the program keeps
track of its position, length, and score.

A random position for the fruit is generated, and the snake's movement is updated
continuously in a loop until the game is over.

2
Features
______________________________________________

Game Loop:

 The game runs in an infinite loop that continuously updates the game state
(snake's position, fruit location, and score).
 The game ends if the snake collides with the boundary or itself.

Basic Controls:

 The snake can be controlled using the arrow keys or w, a, s, d for up, left,
down, and right movements, respectively.
 The snake can also be exited by pressing the x key.

Score System:

 Each time the snake eats a fruit, the score increases.


 The length of the snake increases as well, which makes the game
progressively harder.

Collision Detection:

 The game detects collisions with the walls of the screen or the snake’s own
body, which results in the game ending.

3
Dynamic Snake Growth:

 The snake grows longer as it eats fruit, which increases the difficulty of
maneuvering the snake.

Console-based Display:

 The game is displayed in a text-based interface, where the snake, fruit, and
boundaries are represented using ASCII characters.

Random Fruit Generation:

 Fruit appears at random positions on the screen after each one is eaten by
the snake.

Simple Graphics:

 Uses basic ASCII characters (#, O, *, o) for drawing the boundaries, snake,
and fruit.

4
Key Components
______________________________________________

1. Snake Body and Movement:

 The snake's body is made up of multiple segments. Each segment (or


part of the snake) is represented as o, and the head of the snake is
represented as O.
 The snake moves in the four cardinal directions: left, right, up, or
down. Each time the snake moves, its previous position is saved, and
it follows the last position to create a continuous movement effect.

2. Game Board:

 The game board consists of boundaries that represent the edges of the
screen. The snake cannot go beyond these boundaries. The snake is
confined within the grid, and if it hits the walls or itself, the game
ends.

3. Fruit (Food) Generation:

 A fruit (represented by *) is randomly placed on the grid. When the


snake eats the fruit, its length increases by one segment, and the score
increases by 10 points. A new fruit is placed at a random position on
the grid.

4. Score Counter:

 The score is displayed at the top of the screen. It increases every time
the snake eats the fruit.

5
5. Input Handling:

 The game allows the user to control the snake using the keyboard. The
conio.h library (on Windows) or alternative libraries (for other
operating systems) is used to capture key presses. Depending on the
user's input, the snake’s direction is changed.

6. Game Over Condition:

o The game ends if the snake collides with the boundary or itself. Once
the game ends, the program displays a message and terminates.

7. Game Timer and Speed Control:

o A Sleep function is used to control the speed of the game. The game
runs at a reasonable speed, and the snake's movement is updated after
a short delay to ensure smooth gameplay.

6
Source Code
______________________________________________

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 30
#define HEIGHT 20
int gameover, score;
int x, y, fruitX, fruitY, flag;
int tailX[100], tailY[100]; // snake tail coordinates
int length; // initial length of snake
void draw()
{
system("cls"); // clear 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("#"); // left boundary
if (i == y && j == x)
printf("O"); // snake head

7
else if (i == fruitY && j == fruitX)
printf("*"); // fruit
else {
int isprint = 0;
for (int k = 0; k < length; k++) {
if (tailX[k] == j && tailY[k] == i) {
printf("o"); // snake tail
isprint = 1;
}
}
if (!isprint)
printf(" ");
}
if (j == WIDTH - 1)
printf("#"); // right boundary
}
printf("\n");
}
for (int i = 0; i < WIDTH+2; i++)
printf("#");
printf("\n");
printf("Score: %d", score);
}
void input()
{
if (_kbhit()) {
switch (_getch()) {

8
case 'a': flag = 1; break;
case 'd': flag = 2; break;
case 'w': flag = 3; break;
case 's': flag = 4; break;
case 'x': gameover = 1; break;
}
}
}
void logic()
{
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < length; i++) {
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (flag) {
case 1: x--; break;
case 2: x++; break;
case 3: y--; break;

9
case 4: y++; break;
default: break;
}
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT)
gameover = 1;
for (int i = 0; i < length; i++) {
if (tailX[i] == x && tailY[i] == y)
gameover = 1;
}
if (x == fruitX && y == fruitY) {
score += 10;
length++;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
}
}
void setup()
{
gameover = 0;
flag = 0;
x = WIDTH / 2;
y = HEIGHT / 2;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
score = 0;
length = 1;
}

10
int main()
{
setup();
while (!gameover) {
draw();
input();
logic();
Sleep(10); // slow down the game
}
return 0;
}
******************************************************************************

11
Output
___________________________________________________

12
Algorithm
______________________________________________

1. Initialization:

 Function: setup()

o Initialize Variables:
 Set gameover flag to 0 (game is not over).
 Set flag to 0 (initial direction is undefined).
 Set the initial position of the snake's head (x and y) to the center
of the grid (WIDTH/2 and HEIGHT/2).
 Randomly generate the position of the fruit (fruitX and fruitY).
 Set the initial score to 0.
 Set the initial length of the snake to 1 (only the head is visible).

2. Game Loop (Running the Game):

The core of the game is contained within the game loop. The loop continues as
long as gameover is 0, and executes the following functions in each iteration.

 Function: draw()

o Clear Screen: system("cls") is used to clear the console, giving the


illusion of the snake moving.

o Draw Game Border: The game’s boundaries are drawn using #


characters. The boundaries are fixed at the edges of the grid
(WIDTH and HEIGHT).

13
o Draw Snake Head: The snake’s head is drawn as O at the current
position (x, y).

o Draw Snake Tail: For each segment of the snake’s tail (from tailX
and tailY arrays), the character o is used to represent the body of
the snake.

o Draw Fruit: The fruit is drawn as * at its current position (fruitX,


fruitY).
o Display Score: The current score is displayed at the bottom.

 Function: logic()

o Snake Movement Logic:

 Save the position of the head and each part of the tail in
temporary variables.
 Shift the positions of the snake’s tail segments to "follow" the
previous segment.
 Update the head’s position according to the flag:
 If flag = 1: Move left (decrement x).
 If flag = 2: Move right (increment x).
 If flag = 3: Move up (decrement y).
 If flag = 4: Move down (increment y)

14
Flowchart
______________________________________________

Setup Game

Game Loop

Draw Board Input Logic snake

Game Over?

Display Final Score

Exit the Game

15
Conclusion
___________________________________________________

The Snake game in C is an excellent project to understand basic concepts like


arrays, control flow, and user input handling.
It demonstrates how to create an interactive game with basic features and
mechanics.

You can further enhance the game by adding more features such as levels,
increasing speed, or improving the user interface.

The simplicity of this project makes it ideal for beginners learning C programming.

The Snake Game implemented in C programming is a classic and simple example


of how fundamental concepts like loops, conditionals, and user input handling can
be combined to create an interactive game.

16
Reference
____________________________________

https://chatgpt.com/
https://en.wikipedia.org/wiki/Snake_(video_game_genre)#:~:text=Vi
ewed%20from%20a%20top%2Ddown,the%20body%20of%20eith
er%20snake.
https://www.geeksforgeeks.org/design-snake-game/

17

You might also like