0% found this document useful (0 votes)
53 views18 pages

Report Project

This document describes a 2D cross-road game project built using OpenGL and GLUT. It includes an objective to create a basic 2D game and demonstrate graphics programming fundamentals. It lists required technologies and provides an introduction to computer graphics and the GLUT library. It then describes the application, including using it for education, programming practice, and understanding OpenGL, algorithms, and interactive programming. It provides details about rendering obstacles and characters through functions, drawing various elements like bodies and features using transformations and colors. It also mentions including multiple difficulty levels in the game.

Uploaded by

Shaiball Barua
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)
53 views18 pages

Report Project

This document describes a 2D cross-road game project built using OpenGL and GLUT. It includes an objective to create a basic 2D game and demonstrate graphics programming fundamentals. It lists required technologies and provides an introduction to computer graphics and the GLUT library. It then describes the application, including using it for education, programming practice, and understanding OpenGL, algorithms, and interactive programming. It provides details about rendering obstacles and characters through functions, drawing various elements like bodies and features using transformations and colors. It also mentions including multiple difficulty levels in the game.

Uploaded by

Shaiball Barua
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/ 18

Table of Contents

OBJECTIVE : ................................................................................................................................................... 2
REQUIRED TECHNOLOGY: ............................................................................................................................. 2
INTRODUCTION: ............................................................................................................................................ 2
APPLICATION: ................................................................................................................................................ 4
PROJECT DESCRIPTION:................................................................................................................................. 5
CODE SECTION: ........................................................................................................................................... 10
DISCUSSION:................................................................................................................................................ 18

1
OBJECTIVE :
 To build a basic 2D cross-road game using OpenGL and GLUT.
 To demonstrates graphics programming and game development fundamentals.
 Rendering 2D shapes like rectangles, lines, circles.
 TO Apply the transformations to position objects.
 TO Implementscharacter movement and obstacle scrolling.
 Offering multiple difficulty levels.
 Providing enjoyable gameplay and challenges.

REQUIRED TECHNOLOGY:
 OpenGL
 GLUT(OpenGL Utility Toolkit)
 C++ Compiler
 Development Environment
 Operating System

INTRODUCTION:
The study and practice of creating, modifying, and displaying visual content on screens using
computers is known as computer graphics. For creating images, animations, and visual
representations on digital devices like computer monitors, cellphones, and other display devices,
it includes a broad range of techniques, technologies, and algorithms. Computer graphics can be
broadly categorized into two main areas:

Creating and modifying images in two-dimensional space is the task of 2D graphics. It involves
activities like creating text, photos, lines, and shapes as well as altering these items through
transformations like scaling, rotation, and translation.The display and manipulation of three-
dimensional objects in a virtual environment is the subject of 3D graphics. Video games,
computer-aided design (CAD), architectural visualization, and simulations are just a few fields

2
that heavily utilize 3D graphics. To generate realistic or stylized representations of objects, it
uses methods like shading, rendering, and 3D modeling.

A library called GLUT (OpenGL Utility Toolkit) is used in OpenGL applications for window
creation and management, input processing, and rendering graphics. It offers a collection of tools
that abstract low-level platform-specific information, making the creation of cross-platform
visual applications simpler. GLUT makes activity such as creating windows, managing keyboard
and mouse input, and generating 2D/3D graphics easier.

Here are some of the main characteristics and functions of GLUT:

Window Management :GLUT offers tools for creating windows, controlling their dimensions
and titles, and responding to closing and resizing events.

Handling Input :GLUT provides a straightforward user interface to manage keyboard and mouse
input. You can define actions to take in response to mouse and key events as well as key presses
and releases.

OpenGL Context Creation: By abstracting away platform-specific information, GLUT creates an


OpenGL context for rendering. You will always have access to an OpenGL rendering
environment for your graphics operations. The main loop of GLUT handles events like user
input and display updates. The application can react to events by periodically calling user-
defined routines.

Cross-Platform Support: GLUT was made to be independent of platforms. There are GLUT
derivatives and replacements (such as FreeGLUT, OpenGLUT, and others) that offer enhanced
capability and compatibility with contemporary platforms, despite the fact that the original
GLUT library is fairly outdated and has restrictions.Primitives for Simple Drawing: GLUT
provides straightforward drawing routines for rendering simple shapes like points, lines, and
polygons.Example Code: GLUT includes a collection of programs that serve as examples of how
to use it for various graphics and interaction tasks.Rapid Prototyping: Due to its streamlined
interface, GLUT is frequently used for rapid prototyping and learning OpenGL fundamentals.

It's essential to remember that GLUT is not the most feature-rich or effective library for
complicated applications, particularly in the production of contemporary video games.

3
Developers frequently use more extensive frameworks like GLFW, SDL, or bespoke windowing
systems for performance and capabilities that are more complex.

APPLICATION:
The project is a simple cross-road game built using C++ and the GLUT library. While this game
is relatively basic, it serves as a learning exercise and demonstrates the concepts of computer
graphics and interactive programming. It's not a full-fledged game meant for commercial use, but
it can be a great starting point for beginners to understand game development and graphics
programming. Here are a few potential applications and benefits of this project:

1. Education and Learning: This project can be used as an educational tool to teach students the
fundamentals of computer graphics, interactive programming, and game development. It covers
topics like rendering, animation, collision detection, and user input handling.

2. Programming Practice: Building this project helps beginners practice coding in C++ and
working with a graphics library. It introduces them to concepts like functions, loops, conditional
statements, and object transformations.

3.OpenGL Understanding:By working with GLUT, developers can gain a better understanding
of OpenGL concepts, including rendering shapes, creating a rendering context, and managing
events.

4. Algorithm Understanding: Implementing collision detection and handling helps developers


understand basic algorithms related to hit detection, which is a fundamental concept in game
development.

5. Interactive Programming: The project introduces interactive programming concepts, such as


responding to user input (keyboard controls) and providing visual feedback.

6. Basic Game Development: While simple, the project outlines the structure of a game loop,
updating game state, and rendering game objects. This can serve as a stepping stone to more
complex game development.

4
PROJECT DESCRIPTION:
The `drawObstacle()` function is responsible for rendering an obstacle, which in this case
appears as a car-like shape.The function starts by positioning the obstacle at the specified `(x, y)`
coordinates using `glTranslatef()`.The car body is drawn using a reddish color with a series of
vertices to define a quadrilateral shape.The car roof is drawn next with a bluish color.
Adjustments have been made to the y-coordinates of the vertices to modify the roof's shape.The
car windows are created using light gray color, forming a rectangular shape.The front glass is
drawn with white color, forming a triangular shape at the front of the car.A dark gray driver seat
is drawn using a quadrilateral shape.A white light is added near the bottom of the car's front
using a small quadrilateral shape.Two wheels are drawn, the front and the rear, using a series of
points to form a circular shape. These circles simulate wheels.The transformations applied within
`glTranslatef()` ensure the correct positioning of the wheels and the entire car body.The function
ends by restoring the previous transformation using `glPopMatrix()`.In summary, the
`drawObstacle()` function creates the visual representation of an obstacle in the game, which
resembles a car. It includes elements such as the car body, roof, windows, front glass, driver seat,
light, and wheels, all positioned appropriately through transformations and drawn using various
colors and shapes.\

The `drawCharacter()` function renders a simplified human-like character:The function begins


by positioning the character at the specified `(characterX, characterY)` coordinates using
`glTranslatef()`.A scale transformation is applied to the character, making it half the size.The
character's body is drawn with a quadrilateral shape using a skin color.The character's head is
drawn using a circular shape (polygon) with a skin color.Two black points represent the
character's eyes.A dark red line simulates the character's mouth.The character's shirt is drawn
using a blue quadrilateral shape.Lines represent the character's arms using skin color, and
another pair of lines simulate wrists at the end of each arm.Lines representing legs and pants are
drawn using a dark gray color.Feet are represented as a continuation of the leg lines.A small
belly area is drawn using a polygon shape with a skin color.Various transformations are applied
to position the arms, hands, and other body parts.The function ends by restoring the previous
transformation using `glPopMatrix()`.

5
Easy level Medium level Hard level

The update() function manages the game's state and dynamics, executing at regular intervals:If
the game is ongoing and not over, the speed of obstacles is determined based on the chosen
difficulty level.A loop updates the position of each obstacle, moving them vertically downward.
If an obstacle goes below the screen, it is repositioned at the top and a point is added to the
score.Collision detection is performed between the character and each obstacle. If a collision
occurs, the game is marked as over and a collision message is displayed.If the current score
crosses a level threshold, the game's level is incremented. The difficulty is adjusted based on the
new level and a level up message is shown.The function schedules a redisplay using
glutPostRedisplay() to update the graphics.glutTimerFunc() is used to call the update() function
repeatedly at a set interval (approximately 32 milliseconds, which corresponds to a frame rate of
around 30 frames per second).

For left Press ‘A’

For Right Press ‘D’

The `handleKeypress()` function is responsible for responding to keyboard inputs during the
game:If the game has not started and the 's' key is pressed, the `gameStarted` flag is set to true,
initiating the game.If the game is over and the 'r' key is pressed, the `resetGame()` function is
called to reset the game state.If the game has started, the function handles character movement
based on the 'a' and 'd' keys.The `drawBackground()` function sets the background color of the
OpenGL window to yellow (RGB: 1.0, 1.0, 0.0), creating a yellow background for the game.In
essence, the `handleKeypress()` function enables user interaction by detecting specific key
presses and responding accordingly, while the `drawBackground()` function sets the background
color of the window.

6
The `display()` function renders various game elements based on the game state:If the game has
started, it draws the player character, obstacles (if not game over), score, and difficulty level.If
the game is over, it displays the "Game Over" message and final score.If the game hasn't started,
it shows the initial start screen.The function uses other drawing functions to render specific
elements accordingly.It's an essential part of the game loop responsible for updating the display
continuously.

Fig 1: Demo of the project

Text "Press 's' to Start Game" is shown at the top.A red rectangle represents the player
character.Green rectangles depict obstacles.A white line signifies the game path.Instructions for
controls ('A' and 'D') are displayed in green.Additional guidance urges players to avoid obstacles
and reach the other side to score .Certainly, here are four more points summarizing the
`drawStartGame()` function:The function centers the preview elements using translations based
on the window dimensions. Obstacles are drawn using a loop, translating and rendering each one
with green color. The white path line is drawn with increased line width for better
visibility.Further instructions inform players to avoid obstacles and collect points while
emphasizing the core objective.

7
Fig 2: Racing moment

The display() function manages the visual representation of the game:It clears the screen by
wiping the color buffer to prepare for drawing.If the game is in progress:It renders the player
character.If the game is ongoing, it draws each obstacle using a loop.Displays the current score
and level.If the game has ended, it displays the game over screen.If the game hasn't begun, it
displays the initial game start screen.Finally, it swaps the buffer to show the updated frame.The
display() function orchestrates the visual presentation of different game stages, including active
gameplay, game start, and game over, and handles the necessary rendering and swapping of
frames.

Fig 3 : Display the level and score of the game

8
The `drawLevel()` function is responsible for displaying the current game difficulty level: The
function translates to a specific position at the top-left corner of the window. It sets the text color
to red. Using a stringstream, it creates a dynamic text string indicating the current difficulty
level. The switch statement converts the current Difficulty enum into its corresponding difficulty
level (Easy, Medium, or Hard).The function uses `glRasterPos2f()` to position the text .A loop
iterates through each character of the level Text string, rendering it using the
`GLUT_BITMAP_HELVETICA_12` font. DrawLevel()` generates and displays the game's
current difficulty level at a specified location on the screen, with the difficulty level determined
by the value of the `currentDifficulty` variable.

The `drawScorecard()` function is responsible for displaying the player's current score: The
function begins by using `glPushMatrix()` to save the current transformation matrix and then
translates to a specific position at the top-right corner of the window.It sets the text color to red
using `glColor3f()`.A `stringstream` (`ss`) is used to dynamically create the score text string. It
combines the word "Score:" with the player's score using `setw()` and `setfill()` to format the
score to have a fixed width of 4 digits, with leading zeros if necessary.The `scoreText` string is
obtained from the `stringstream`. `glRasterPos2f()` positions the starting point for rendering the
text. A loop iterates through each character of the `scoreText` string, rendering it using the
`GLUT_BITMAP_HELVETICA_12` font. After rendering the text, `glPopMatrix()` is used to
restore the original transformation matrix. In summary, the `drawScorecard()` function calculates
and displays the player's current score on the screen, ensuring that the score is properly formatted
with leading zeros to maintain a consistent appearance. The score is positioned at the top-right
corner of the window.

9
Fig 4: Situation after collision and restart

The `drawGameOver()` function is responsible for showing the "Game Over" screen in the
game:This function starts by positioning the screen's content at the center using `glTranslatef()`
and sets the text color to red.It creates a text string using a `stringstream`, which includes the
"Game Over" message and the final score formatted with leading zeros.The function then renders
the "Game Over" text using a larger font (`GLUT_BITMAP_HELVETICA_18`).After that, it
creates and displays a smaller text instructing the player to press 'r' to restart the game.The entire
content is positioned, colored, and displayed using OpenGL functions.Once the drawing is
complete, the function restores the original transformation with `glPopMatrix()`.In essence, the
`drawGameOver()` function displays the "Game Over" message along with the final score and
instructions for restarting the game, all positioned at the center of the screen. Different font sizes
provide visual distinction between the messages.

CODE SECTION:

#include <GL/glut.h> #include<math.h>

#include <iostream> using namespace std;

#include <iomanip> const int windowWidth = 800;

#include <sstream> const int windowHeight = 600;

10
float characterX = windowWidth / 2.0f; const int levelThresholds[] = { 10, 20, 30 }; //
Increase level after reaching these scores
const float characterY = 50.0f;
const int numLevels = sizeof(levelThresholds) /
const float characterStep = 20.0f; sizeof(levelThresholds[0]);
const int numObstacles = 4; bool checkCollision(float charX, float charY,
float obstacleX[numObstacles] = { 100.0f, float obsX, float obsY) {
300.0f, 500.0f, 700.0f }; if (charX + 10.0f >= obsX - obstacleWidth / 2
float obstacleY = windowHeight - 50.0f; && charX - 10.0f <= obsX + obstacleWidth / 2

const float obstacleWidth = 50.0f; && charY + 10.0f >= obsY - obstacleHeight /
2 && charY - 10.0f <= obsY + obstacleHeight / 2)
const float obstacleHeight = 20.0f;
return true;
const float obstacleSpeedEasy = 5.0f * 0.5f; //
Reduce speed by 50% return false;

const float obstacleSpeedMedium = 7.5f * 0.5f; }

const float obstacleSpeedHard = 10.0f * 0.5f; void resetGame() {

int score = 0; characterX = windowWidth / 2.0f;

bool gameOver = false; obstacleY = windowHeight - 50.0f;

bool gameStarted = false; for (int i = 0; i < numObstacles; ++i) {

enum Difficulty { obstacleX[i] = (rand() %


static_cast<int>(windowWidth -
EASY, obstacleWidth)) + obstacleWidth / 2;

MEDIUM, }

HARD score = 0;

}; gameOver = false;

Difficulty currentDifficulty = EASY; currentDifficulty = EASY;

int currentLevel = 1; currentLevel = 1;

void drawScorecard() { glTranslatef(windowWidth - 150.0f,


windowHeight - 50.0f, 0.0f);
glPushMatrix();
glColor3f(1.0f, 0.0f, 0.0f); // Red color for text

11
stringstream ss; string levelText = ss.str();

ss << "Score: " << setw(4) << setfill('0') <<


score;
glRasterPos2f(0.0f, 0.0f);
string scoreText = ss.str();
for (char c : levelText) {
glRasterPos2f(0.0f, 0.0f);

for (char c : scoreText) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA


glutBitmapCharacter(GLUT_BITMAP_HELVETICA _12, c); }
_12, c); }
glPopMatrix();}
glPopMatrix();}
void drawGameOver() {
void drawLevel() {
glPushMatrix();
glPushMatrix();
glTranslatef(windowWidth / 2.0f - 150.0f,
glTranslatef(50.0f, windowHeight - 50.0f, windowHeight / 2.0f, 0.0f);
0.0f);
glColor3f(1.0f, 0.0f, 0.0f); // Red color
glColor3f(1.0f, 0.0f, 0.0f); // Red color for text
stringstream ss;
stringstream ss;
ss << "Game Over! Final Score: " << setw(4)
ss << "Level: "; << setfill('0') << score;

switch (currentDifficulty) { string gameOverText = ss.str();

case EASY: glRasterPos2f(0.0f, 0.0f);

ss << "Easy"; for (char c : gameOverText) {


glutBitmapCharacter(GLUT_BITMAP_HELVETICA
break; _18, c);
case MEDIUM: }
ss << "Medium"; string restartText = "Press 'r' to Restart
break; Game";

case HARD: glRasterPos2f(0.0f, -30.0f);

ss << "Hard"; for (char c : restartText) {


glutBitmapCharacter(GLUT_BITMAP_HELVETICA
break; _12, c);

} }

12
glPopMatrix();} glColor3f(0.0f, 1.0f, 0.0f); // Green color for
obstacles
void drawStartGame() {
for (int i = 0; i < numObstacles; ++i) {
glPushMatrix();
glPushMatrix();
glTranslatef(windowWidth / 2.0f - 150.0f,
windowHeight / 2.0f, 0.0f); glTranslatef(obstacleX[i], -10.0f, 0.0f);

glColor3f(0.0f, 1.0f, 0.0f); // Green color for glBegin(GL_QUADS);


text
glVertex2f(-obstacleWidth / 2, -
string startGameText = "Press 's' to Start obstacleHeight / 2);
Game";
glVertex2f(-obstacleWidth / 2,
glRasterPos2f(0.0f, 40.0f); obstacleHeight / 2);

for (char c : startGameText) { glVertex2f(obstacleWidth / 2,


obstacleHeight / 2);

glutBitmapCharacter(GLUT_BITMAP_HELVETICA glVertex2f(obstacleWidth / 2, -
_18, c); obstacleHeight / 2);

} glEnd();

// Draw the game preview illustration glPopMatrix(); }

glTranslatef(0.0f, -20.0f, 0.0f); // Draw path

// Draw character glColor3f(1.0f, 1.0f, 1.0f); // White color for


path
glColor3f(1.0f, 0.0f, 0.0f); // Red color for
character glLineWidth(2.0f);

glBegin(GL_QUADS); glBegin(GL_LINES);

glVertex2f(-10.0f, -10.0f); glVertex2f(-windowWidth / 4, -10.0f);

glVertex2f(-10.0f, 10.0f); glVertex2f(windowWidth / 4, -10.0f);

glVertex2f(10.0f, 10.0f); glEnd();

glVertex2f(10.0f, -10.0f); // Draw instructions

glEnd(); glTranslatef(0.0f, -40.0f, 0.0f);

glColor3f(0.0f, 1.0f, 0.0f); // Green color for


text
// Draw obstacles

13
void drawGameOver() { glColor3f(0.0f, 1.0f, 0.0f); // Green color for
text
glPushMatrix();
string startGameText = "Press 's' to Start
glTranslatef(windowWidth / 2.0f - 150.0f,
Game";
windowHeight / 2.0f, 0.0f);
glRasterPos2f(0.0f, 40.0f);
glColor3f(1.0f, 0.0f, 0.0f); // Red color
for (char c : startGameText) {
stringstream ss; glutBitmapCharacter(GLUT_BITMAP_HELVETICA
ss << "Game Over! Final Score: " << setw(4) _18, c);
<< setfill('0') << score; }
string gameOverText = ss.str(); // Draw the game preview illustration
glRasterPos2f(0.0f, 0.0f); glTranslatef(0.0f, -20.0f, 0.0f);
for (char c : gameOverText) {
// Draw character

glColor3f(1.0f, 0.0f, 0.0f); // Red color for


glutBitmapCharacter(GLUT_BITMAP_HELVETICA
character
_18, c);
glBegin(GL_QUADS);
}
glVertex2f(-10.0f, -10.0f);
string restartText = "Press 'r' to Restart
Game"; glVertex2f(-10.0f, 10.0f);

glRasterPos2f(0.0f, -30.0f); glVertex2f(10.0f, 10.0f);

for (char c : restartText) { glVertex2f(10.0f, -10.0f);

glEnd();
glutBitmapCharacter(GLUT_BITMAP_HELVETICA
_12, c); // Draw obstacles

glPopMatrix(); glColor3f(0.0f, 1.0f, 0.0f); // Green color for


obstacles
}
for (int i = 0; i < numObstacles; ++i) {
void drawStartGame() {
glPushMatrix();
glPushMatrix();
glTranslatef(obstacleX[i], -10.0f, 0.0f);
glTranslatef(windowWidth / 2.0f - 150.0f,
windowHeight / 2.0f, 0.0f); glBegin(GL_QUADS);

14
glVertex2f(-obstacleWidth / 2, - // Additional instructions
obstacleHeight / 2);
glColor3f(0.0f, 1.0f, 0.0f); // Green color for
glVertex2f(-obstacleWidth / 2, text
obstacleHeight / 2);
string additionalInstructionsText = "Avoid
glVertex2f(obstacleWidth / 2, obstacles and reach the other side to score!";
obstacleHeight / 2);
glRasterPos2f(0.0f, -20.0f);
glVertex2f(obstacleWidth / 2, -
obstacleHeight / 2); for (char c : additionalInstructionsText) {

glEnd();
glutBitmapCharacter(GLUT_BITMAP_HELVETICA
glPopMatrix(); _12, c);

}// Draw path }

glColor3f(1.0f, 1.0f, 1.0f); // White color for glPopMatrix();


path
}void display() {
glLineWidth(2.0f);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINES);
if (gameStarted) {
glVertex2f(-windowWidth / 4, -10.0f);
drawCharacter();
glVertex2f(windowWidth / 4, -10.0f);
if (!gameOver) {
glEnd();
for (int i = 0; i < numObstacles; ++i) {
// Draw instructions
drawObstacle(obstacleX[i], obstacleY);
glTranslatef(0.0f, -40.0f, 0.0f);
}}
glColor3f(0.0f, 1.0f, 0.0f); // Green color for
text drawScorecard();

string instructionsText = "Use 'A' and 'D' to drawLevel();


move left and right"; if (gameOver) {
glRasterPos2f(0.0f, 0.0f); drawGameOver(); } }
for (char c : instructionsText) { else {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA
_12, c); drawStartGame();

} glutSwapBuffers();

15
}void update(int value) { break;

if (!gameOver && gameStarted) { }}

float obstacleSpeed; if (currentLevel < numLevels && score >=


levelThresholds[currentLevel - 1]) {
switch (currentDifficulty) {
currentLevel++;
case EASY:
if (currentLevel <= numLevels) {
obstacleSpeed = obstacleSpeedEasy;
currentDifficulty =
break; static_cast<Difficulty>(currentLevel - 1);
case MEDIUM: }
obstacleSpeed = cout << "Level Up! Difficulty increased to:
obstacleSpeedMedium; ";
break; switch (currentDifficulty) {
case HARD: case EASY:
obstacleSpeed = obstacleSpeedHard; cout << "Easy";
break;} break;
for (int i = 0; i < numObstacles; ++i) { case MEDIUM:
obstacleY -= obstacleSpeed; cout << "Medium";
if (obstacleY < 0.0f) { break;
obstacleY = windowHeight; case HARD:
obstacleX[i] = (rand() %
cout << "Hard";
static_cast<int>(windowWidth -
obstacleWidth)) + obstacleWidth / 2; break;

score++; } }

if (checkCollision(characterX, characterY, cout << endl;


obstacleX[i], obstacleY)) {
} }
cout << "Game Over! You collided with
an obstacle." << endl; glutPostRedisplay();

gameOver = true; glutTimerFunc(16 * 2, update, 0);

16
}void handleKeypress(unsigned char key, int x,
int y) {
// Handle special key input here (if needed)
if (!gameStarted && key == 's') {
}string instructionsText = "Use 'A' and 'D' to
gameStarted = true; move left and right";

} glRasterPos2f(0.0f, 0.0f);

else if (gameOver && key == 'r') { for (char c : instructionsText) {

resetGame(); }
glutBitmapCharacter(GLUT_BITMAP_HELVETICA
else if (gameStarted) { _12, c);
switch (key) { }
case 'a': // Additional instructions
case 'A': glColor3f(0.0f, 1.0f, 0.0f); // Green color for
characterX -= characterStep; text

break; string additionalInstructionsText = "Avoid


obstacles and reach the other side to score!";
case 'd':
glRasterPos2f(0.0f, -20.0f);
case 'D':
for (char c : additionalInstructionsText) {
characterX += characterStep;

break; glutBitmapCharacter(GLUT_BITMAP_HELVETICA
_12, c);
} }}
}
void drawBackground() {
glPopMatrix();
glClearColor(1.0f, 1.0f, 0.0f, 1.0f); // Set
background color to yellow} }

void handleSpecialKeypress(int key, int x, int y) {

17
DISCUSSION:
This game called "Cross Road" using the OpenGL graphics library and GLUT (OpenGL Utility
Toolkit) for window management.The game features a character that the player controls to
navigate across a road while avoiding obstacles. The character can move left ('A') or right ('D') to
avoid oncoming cars. The obstacles are represented as cars moving from the top to the bottom of
the screen.The game incorporates basic graphics rendering using geometric shapes and lines to
create the character and obstacles. The character is drawn as a humanoid figure, while the
obstacles are drawn as rectangles representing cars.The user interaction is managed through key
presses. The player can start the game by pressing 's' and control the character using the 'A' and
'D' keys for left and right movement, respectively. After a collision with an obstacle, the player
can press 'r' to restart the game.

The game implements a scoring system that keeps track of the number of obstacles the player
successfully avoids. There are three difficulty levels: Easy, Medium, and Hard. The difficulty
level increases as the player's score crosses predefined thresholds.
The user interface includes displaying the player's score and the current difficulty level. When
the game ends, a "Game Over" message is displayed along with the final score, and the player is
prompted to restart by pressing 'r'.The project offers a basic example of game development using
OpenGL and GLUT. It covers fundamental concepts such as collision detection, game loops,
graphics rendering, and user input handling.

The character's appearance is created using simple geometric shapes and lines, providing a
straightforward representation of a humanoid figure. Similarly, obstacles are depicted as basic
rectangles representing cars.Although the graphics are minimalistic, the project can serve as a
stepping stone for beginners to learn about game development and graphics programming. It
demonstrates the core components needed to create a basic 2D game and offers insights into
implementing game mechanics, user interaction, and simple graphics rendering.

Overall, the project provides an opportunity to gain hands-on experience with OpenGL, GLUT,
and basic game development concepts. It offers a foundation for us to build upon and create
more complex games with advanced graphics and features.

18

You might also like