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

DOC-20241024-WA0002.

This document outlines an assignment for developing a Snake Game in C as part of a Bachelor of Engineering course. It includes detailed explanations of the game's components, functionalities, and the main gameplay loop, along with the code structure and controls. The game involves a snake that collects food while avoiding collisions, and it provides a simple interactive experience in a console environment.

Uploaded by

040506het
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

DOC-20241024-WA0002.

This document outlines an assignment for developing a Snake Game in C as part of a Bachelor of Engineering course. It includes detailed explanations of the game's components, functionalities, and the main gameplay loop, along with the code structure and controls. The game involves a snake that collects food while avoiding collisions, and it provides a simple interactive experience in a console environment.

Uploaded by

040506het
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

ASSIGNMENT

Programming For Problem Solving


Bachelor of Engineering
Semester – 1

Submitted by
Het Kalpeshkumar Gandhi

Roll No:2024BECE49
Course Coordinator
Dr. Seems B. Joshi

GUJARAT TECHNOLOGY UNIVERSITY


SCHOOL OF ENGINEERING AND TECHNOLOGY

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

// Point structure to represent coordinates


typedef struct {
int x;
int y;
} Point;

// Snake structure to represent the snake and its


attributes
typedef struct {
Point body[100]; // Fixed size for simplicity

2
int length; // Current length of the snake
} Snake;

// Game structure to hold the game state


typedef struct {
Snake snake; // The snake
Point food; // The food's position
int score; // Player's score
int game_over; // Game over flag
} Game;

// Initialize the game state


void initialize_game(Game *game) {
game->snake.length = INITIAL_SNAKE_LENGTH;

// Initialize snake's starting position


for (int i = 0; i < game->snake.length; i++) {
game->snake.body[i].x = WIDTH / 2;
game->snake.body[i].y = HEIGHT / 2 + i;
}

game->score = 0;

3
game->game_over = 0;

// Place food at a random location within the


boundaries
game->food.x = rand() % WIDTH;
game->food.y = rand() % HEIGHT;
}

// 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");

// Displaying the player's score


mvprintw(0, 0, "Score: %d", game->score);

4
refresh();
}

// Update the snake's position based on the input


direction
void update_snake(Game *game, int dx, int dy) {
Point new_head = {game->snake.body[0].x + dx, game-
>snake.body[0].y + dy};

// Check for collisions with walls


if (new_head.x < 0 || new_head.x >= WIDTH ||
new_head.y < 0 || new_head.y >= HEIGHT) {
game->game_over = 1; // Snake hit the walls
}

// Check for collisions with itself


for (int i = 0; i < game->snake.length; i++) {
if (game->snake.body[i].x == new_head.x && game-
>snake.body[ i ].y == new_head.y) {
game->game_over = 1; // Snake hit itself
}
}

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

// Check if the snake eats the food


if (new_head.x == game->food.x && new_head.y ==
game->food.y) {
game->score++; // Increase score
game->snake.length++; // Increase snake length
game->food.x = rand() % WIDTH; // Reposition food
game->food.y = rand() % HEIGHT; // Reposition food
}
}

// Main function to run the game


int main() {
srand(time(0)); // Seed the random number generator
Game game;
initialize_game(&game);

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

int dx = 0, dy = -1; // Initial direction (upwards)

// Main game loop


while (!game.game_over) {
draw_game(&game);
int ch = getch(); // Get player input
switch (ch) {
case KEY_UP: if (dy != 1) { dx = 0; dy = -1; } break;
case KEY_DOWN: if (dy != -1) { dx = 0; dy = 1; }
break;
case KEY_LEFT: if (dx != 1) { dx = -1; dy = 0; } break;
case KEY_RIGHT: if (dx != -1) { dx = 1; dy = 0; }
break;
}
update_snake(&game, dx, dy); // Update snake
position
}
7
// Game Over display
mvprintw(HEIGHT / 2, WIDTH / 2 - 5, "Game Over!");
mvprintw(HEIGHT / 2 + 1, WIDTH / 2 - 5, "Final Score:
%d", game.score);
refresh();
getch(); // Wait for user input before exiting
endwin(); // End ncurses mode
return 0;
}
OUTPUT:

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

1. Headers and Macros:

o #include <stdio.h>: Standard input/output


functions, like printing to the console.

o #include <stdlib.h>: Standard library for functions


like rand().

o `#include <unistd.h>:` Includes the POSIX


standard header that provides access to system calls
and low-level I/O functions in Unix-like operating
systems. It allows use of functions like `read()`,
`write()`, and `fork()`.

o `#include <time.h>` :Includes the header file that


provides functions and types for manipulating time
and date in C. It allows access to features like

10
getting the current time, formatting dates, and
measuring time intervals.

o `#include <ncurses.h>`: Includes the ncurses


library, which is used for creating text-based user
interfaces in terminal applications. It provides
functions for handling windowing, keyboard input,
and screen manipulation in a terminal environment.

o #define HEIGHT 20 and #define WIDTH 20:


Defines the dimensions of the game area.

2. Variables:

o Arrays snakeBodyX[100] and snakeBodyY[100] sto


re the coordinates of the snake's body segments.

o snakebodyen keeps track of the length of the snake.

o gameover, key, and score are flags and counters for


the game's state.

o (x, y) represents the snake's head coordinates,


while (fruitx, fruity) represent the fruit's
coordinates.

3. Functions:

11
o setup(): Initializes the game state, including the
position of the snake and fruit, and sets the score to
zero.

o draw(): Renders the game board, including walls,


the snake's head, body, fruit, and the current score
and instructions.

o input(): Captures user input for snake movement


and quitting the game. It uses kbhit() to check if a
key is pressed and uses getch() to capture the key.

o logic(): Contains game logic for snake movement


and collision detection:

▪ Updates the snake's position based on the


current direction (key).

▪ Checks for boundary collisions and self-


collisions.

▪ Updates the score and increases the snake’s


length when it eats fruit.

4. Main Function:

o main(): Starts the game by calling setup() and


enters a game loop that continues until gameover is

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

• The gameplay loop consists of three main operations:

i. Draw the current state of the game.

ii. Read player input to update movement direction.

iii. Apply game logic to update the snake's position,


check for collisions, and handle fruit collection.

Key Controls

• The player moves the snake using:

o Up

o Down

o Left

o Right

o ENTER Quit game

Conclusion

This code represents a basic snake game structure, involving


setting up the game environment, handling player input,
13
managing game state, and rendering the output to provide
feedback to the player. The game continues until the player
either chooses to quit or the snake collides with itself or the
walls.

This explanation simplifies the understanding of the snake


game's operational mechanics and structure, making it easier
to comprehend the coding process behind it.

14

You might also like