DOC-20241024-WA0002.
DOC-20241024-WA0002.
Submitted by
Het Kalpeshkumar Gandhi
Roll No:2024BECE49
Course Coordinator
Dr. Seems B. Joshi
1
Objective: Develop a Snake Game in C. Explain each
functionality with its objective.
INPUT:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <ncurses.h>
#define WIDTH 20
#define HEIGHT 20
#define INITIAL_SNAKE_LENGTH 3
2
int length; // Current length of the snake
} Snake;
game->score = 0;
3
game->game_over = 0;
// Draw the game state including the snake and the food
void draw_game(Game *game) {
clear();
// Draw snake
for (int i = 0; i < game->snake.length; i++) {
mvprintw(game->snake.body[i].y, game-
>snake.body[i].x, "O");
}
// Draw food
mvprintw(game->food.y, game->food.x, "X");
4
refresh();
}
5
// Move the snake by updating the body positions
for (int i = game->snake.length; i > 0; i--) {
game->snake.body[i] = game->snake.body[i - 1];
}
game->snake.body[0] = new_head; // Setting the new
head
6
initscr(); // Initialize ncurses mode
noecho(); // Don't echo pressed keys
curs_set(0); // Hide cursor
keypad(stdscr, TRUE); // Enable arrow keys input
timeout(100); // Set a timeout for input to be non-
blocking
8
This C program implements a simple interactive snake game
in a console environment. Below is a clear and concise
explanation of the various components and functionalities of
the code:
Overview
9
The game consists of a snake that moves on the console
screen, trying to collect fruits while avoiding collisions with
walls and its own body. The player controls the snake using
the keys 'W', 'A', 'S', and 'D' for movement, and 'X' to exit the
game.
Components
10
getting the current time, formatting dates, and
measuring time intervals.
2. Variables:
3. Functions:
11
o setup(): Initializes the game state, including the
position of the snake and fruit, and sets the score to
zero.
4. Main Function:
12
set to 1. In each iteration, it calls the draw(), input(),
and logic() functions, with a brief sleep to manage
game speed.
Gameplay Loop
Key Controls
o Up
o Down
o Left
o Right
Conclusion
14