Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
OpenGL program for simple Animation (Revolution) in C
Next article icon

OpenGL program for Simple Ball Game

Last Updated : 28 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite – OpenGL
OpenGL is a cross-language, cross-platform API for rendering 2D and 3D Vector Graphics. Using this, we can make a lot of design as well as animations. Below is a simple Game made using OpenGL.
Description : In this, a ball is moving starting from middle and goes to up-left in starting. But, then it collides with wall and changes direction but speed remain same. Consequently, it comes to downward direction where it should be catched on a rectangle (which is capable of moving in horizontal direction) in order to continue.
For working on Ubuntu operating system: 
 

gcc filename.c -lGL -lGLU -lglut -lm  where filename.c is the name of the file with which this program is saved.

 

 

C




// C program to illustrate OpenGL game
#include<stdio.h>
#include<GL/glut.h>
#include<math.h>
#define pi 3.142857
 
// Global Declaration
// c and d tracks the number of time 'b' and 'n' pressed respectively
// left and right indicates leftmost and rightmost index of movable rectangle
int c = 0, d = 0, left = 0, right = 0;
int m = 0, j = 1, flag1 = 0, l = 1, flag2 = 0, n = 0, score = 0, count = 1;
 
// Initialization function
void myInit (void)
{
    // Reset background color with white (since all three argument is 1.0)
    glClearColor(1.0, 1.0, 1.0, 0.0);
 
    // Set picture color to red (in RGB model)
    // as only argument corresponding to R (Red) is 1.0 and rest are 0.0
    glColor3f(1.0f, 0.0f, 0.0f);
 
    // Set width of point to one unit
    glPointSize(1.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
 
    // Set window size in X- and Y- direction
    gluOrtho2D(-620.0, 620.0, -340.0, 340.0);
}
 
// keyboard function : it gets active when button pressed
void keyboard(unsigned char key, int x, int y)
{
    left = -200 + 200 * (d - c);
    right = 200 + 200 * (d - c);
 
    // if leftmost index of window is hit
    // then rectangle will not move to left on further pressing of b
    // only it will move to right on pressing n
    if (left == -600)
    {
        // '110' -> Ascii value of 'n'
        // so d is incremented when n is pressed
        if (key == 110)
            d++;
    }
    // if rightmost index of window is hit
    // then rectangle will not move to right on further pressing of n
    // only it will move to left on pressing b
    else if (right == 600)
    {
        // '98' -> Ascii value of 'b'
        // so c is incremented when b is pressed
        if (key == 98)
            c++;
    }
    // when rectangle is in middle, then it will move into both
    // direction depending upon pressed key
    else
    {
        if (key == 98)
            c++;   
        if (key == 110)
            d++;
    }
    glutPostRedisplay();
}
 
void myDisplay(void)
{
    // x and y keeps point on circumference of circle
    int x, y, k;
    // outer 'for loop' is to for making motion in ball
    for (k = 0; k <= 400; k += 5)
    {   
        glClear(GL_COLOR_BUFFER_BIT);
        glBegin(GL_LINE_STRIP);
        // i keeps track of angle
        float i = 0;
        // change in m denotes motion in vertical direction and
        // change in n denotes motion in horizontal direction
        m = m + 6;
        n = n + 4;
        // drawing of circle centre at (0, 12) iterated up to 2*pi, i.e., 360 degree
        while (i <= 2 * pi)
        {
            y = 12 + 20 * cos(i);
            x = 20 * sin(i);
            i = i + 0.1;
            // flag1 is 0 to show motion in upward direction and is 1 for downward direction
            if (m == 288 && flag1 == 0)
            {
                j = -1;
                m = -288;
                flag1 = 1;
                score++;
            }
            if (m == 288 && flag1 == 1)
            {
                j = 1;
                m = -288;
                flag1 = 0;
            }
            // flag2 is 0 to show motion in rightward direction and is 1 for leftward direction
            if (n == 580 && flag2 == 0)
            {
                l = -1;
                n = -580;
                flag2 = 1;
            }
            if (n == 580 && flag2 == 1)
            {
                l = 1;
                n = -580;
                flag2 = 0;
            }
            // equation for desired motion of ball
            glVertex2i((x - l * n), (y - j * m));
        }
        glEnd();
 
        // these four points draws outer rectangle which determines window
        glBegin(GL_LINE_LOOP);
            glVertex2i(-600, -320);
            glVertex2i(-600, 320);
            glVertex2i(600, 320);
            glVertex2i(600, -320);
        glEnd();
 
        // these four points draws smaller rectangle which is for catching ball
        glBegin(GL_LINE_LOOP);
        left = -200 + 200 * (d - c);
        right = 200 + 200 * (d - c);
            glVertex2i(left, -315);
            glVertex2i(left, -295);
            glVertex2i(right, -295);
            glVertex2i(right, -315);
        glEnd();
 
        // following condition checks if falling ball is catched on rectangle or not
        if ((j * m) == 276)
        {
            if ((left > ((-1 * l * n) + 20)) || (right < (-1 * l * n) - 20))
            {
                printf("Game Over !!!\nYour Score is :\t%d\n", score);
                exit(0);
            }
        }
        glutSwapBuffers();
    }
}
 
 
// Driver Program
int main (int argc, char** argv)
{
    glutInit(&argc, argv);
     
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
    // Declares window size
    glutInitWindowSize(1100, 600);
     
    // Declares window position which is (0, 0)
    // means lower left corner will indicate position (0, 0)
    glutInitWindowPosition(0, 0);
 
    // Name to window
    glutCreateWindow("Game");
 
    // keyboard function
    glutKeyboardFunc(keyboard);
    // Call to myInit()
    myInit();
    glutDisplayFunc(myDisplay);
    glutMainLoop();
}
 
 

Below is the screenshot of the animation. This screenshot is of one instance. In actual, ball will move in different direction which should be catched on the smaller rectangle. Rectangle can be moved to left by pressing lowercase b and towards right by lowercase n. However, this can be changed by changing the code in keyboard function where ASCII value of key can be changed.
 

 



Next Article
OpenGL program for simple Animation (Revolution) in C

A

Aditya Kumar
Improve
Article Tags :
  • Design Pattern
  • System Design

Similar Reads

  • Computer Graphics
    Recent Articles on Computer GraphicsTable of Content Basics :Output Primitives :2-Dimensional Viewing :Visible Surface Detection :3-Dimension Object Representation :Open GL :Graphics function in C :Misc : Basics :Basic Graphic Programming in C++Vector vs Raster GraphicsSegments in Computer GraphicsI
    2 min read
  • Basics

    • Basic Graphic Programming in C++
      Introduction So far we have been using C language for simple console output only.  Most of us are unaware that using C++, low level graphics program can also be made. This means we can incorporate shapes,colors and designer fonts in our program. This article deals with the steps to enable the DevC++
      2 min read

    • Vector vs Raster Graphics
      When it comes to digital images, two main types are commonly used: raster and vector graphics. Understanding the difference between these two can help you choose the right format for your project. Raster graphics, made up of tiny pixels, are ideal for detailed and colorful images like photographs. O
      7 min read

    • Segments in Computer Graphics
      Introduction : Introduction segments are a fundamental concept in computer graphics, used to represent the basic building blocks of a graphical scene. They are commonly used in 2D graphics to represent lines or curves that connect two or more points. An introduction segment is defined by two endpoin
      8 min read

    • Image Formats
      Image formats are different types of file types used for saving pictures, graphics, and photos. Choosing the right image format is important because it affects how your images look, load, and perform on websites, social media, or in print. Common formats include JPEG, PNG, GIF, and SVG, each with it
      5 min read

    Output Primitives

    • DDA Line generation Algorithm in Computer Graphics
      Introduction : DDA (Digital Differential Analyzer) is a line drawing algorithm used in computer graphics to generate a line segment between two specified endpoints. It is a simple and efficient algorithm that works by using the incremental difference between the x-coordinates and y-coordinates of th
      12 min read

    • Bresenham’s Line Generation Algorithm
      Given the coordinate of two points A(x1, y1) and B(x2, y2). The task is to find all the intermediate points required for drawing line AB on the computer screen of pixels. Note that every pixel has integer coordinates. Examples: Input : A(0,0), B(4,4)Output : (0,0), (1,1), (2,2), (3,3), (4,4) Input :
      14 min read

    • Mid-Point Line Generation Algorithm
      Given coordinate of two points A(x1, y1) and B(x2, y2) such that x1 < x2 and y1 < y2. The task to find all the intermediate points required for drawing line AB on the computer screen of pixels. Note that every pixel has integer coordinates.We have discussed below algorithms for this task. DDA
      11 min read

    • Program to find line passing through 2 Points
      Given two points P and Q in the coordinate plane, find the equation of the line passing through both points.This kind of conversion is very useful in many geometric algorithms like intersection of lines, finding the circumcenter of a triangle, finding the incenter of a triangle and many more... Exam
      6 min read

    • Bresenham’s circle drawing algorithm
      It is not easy to display a continuous smooth arc on the computer screen as our computer screen is made of pixels organized in matrix form. So, to draw a circle on a computer screen we should always choose the nearest pixels from a printed pixel so as they could form an arc. There are two algorithm
      4 min read

    • Anti-aliased Line | Xiaolin Wu's algorithm
      Anti-Aliased Line Drawing Below is the image showing line drawn with Bresenham's line algorithm (left) and Xiaolin Wu's line algorithm (right) which smooths the line. Which one looks better to you ? Anti Aliasing concept Suppose we want to draw a line from point(1 , 1) to point(8 , 4) with rectangul
      10 min read

    • Neighbors of a point on a circle using Bresenham's algorithm
      Given a center of a circle and its radius. our task is to find the neighbors of any point on the discrete circle. Examples:  Input : Center = (0, 0), Radius = 3 Point for determining neighbors = (2, 2)Output : Neighbors of given point are : (1, 3), (3, 1)Input : Center = (2, 2) Radius 2 Point of det
      15 min read

    • Mid-Point Circle Drawing Algorithm
      The mid-point circle drawing algorithm is an algorithm used to determine the points needed for rasterizing a circle. We use the mid-point algorithm to calculate all the perimeter points of the circle in the first octant and then print them along with their mirror points in the other octants. This wi
      15+ min read

    • Boundary Fill Algorithm
      Prerequisite : Flood fill algorithm, Scan-line polygon fillingIntroduction : Boundary Fill Algorithm starts at a pixel inside the polygon to be filled and paints the interior proceeding outwards towards the boundary. This algorithm works only if the color with which the region has to be filled and t
      5 min read

    • Flood fill Algorithm - how to implement fill() in paint?
      Flood Fill is a classic algorithm used to change the color of an area in a 2D image where all pixels are connected and have the same initial color. Think of it like the paint bucket tool in graphic design software like MS Paint or Photoshop—when you click on a spot, it automatically fills that area
      2 min read

    • Flood fill algorithm using C graphics
      Given a rectangle, your task to fill this rectangle using flood fill algorithm. Examples: Input : rectangle(left = 50, top = 50, right= 100, bottom = 100) flood( x = 55, y = 55, new_color = 12, old_color = 0) Output : Input : rectangle(left = 50, top = 50, right= 200, bottom = 400) flood( x = 51, y
      2 min read

    • Draw a line in C++ graphics
      graphics.h library is used to include and facilitate graphical operations in program. graphics.h functions can be used to draw different shapes, display text in different fonts, change colors and many more. Using functions of graphics.h you can make graphics programs, animations, projects and games.
      2 min read

    • Draw Rectangle in C graphics
      rectangle() is used to draw a rectangle. Coordinates of left top and right bottom corner are required to draw the rectangle. left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of right bottom corner, bottom specifie
      2 min read

    • Draw circle in C graphics
      The header file graphics.h contains circle() function which draws a circle with center at (x, y) and given radius. Syntax : circle(x, y, radius); where, (x, y) is center of the circle. 'radius' is the Radius of the circle. Examples : Input : x = 250, y = 200, radius = 50 Output : Input : x = 300, y
      1 min read

    • Draw a circle without floating point arithmetic
      Given a radius of a circle, draw the circle without using floating point arithmetic.The following program uses a simple concept. Let the radius of the circle be r. Consider a square of size (2r+1)*(2r+1) around the circle to be drawn. Now walk through every point inside the square. For every point (
      6 min read

    • Code to Generate the Map of India (With Explanation)
      Given an obfuscated code that generates the map of India, explain its working. The following code when executed generates the map of India. An obfuscated code is a code that has been deliberately made difficult to understand or difficult to read, typically for the purpose of hiding its logic or maki
      8 min read

    2-Dimensional Viewing

    • 2D Transformation in Computer Graphics | Set 1 (Scaling of Objects)
      We can use a 2 × 2 matrix to change or transform, a 2D vector. This kind of operation, which takes in a 2-vector and produces another 2-vector by a simple matrix multiplication, is a linear transformation. By this simple formula, we can achieve a variety of useful transformations, depending on what
      5 min read

    • 2D Transformation | Rotation of objects
      We have to rotate an object by a given angle about a given pivot point and print the new co-ordinates.Examples: Input : {(100, 100), (150, 200), (200, 200), (200, 150)} is to be rotated about (0, 0) by 90 degrees Output : (-100, 100), (-200, 150), (-200, 200), (-150, 200) Input : {(100, 100), (100,
      7 min read

    • Point Clipping Algorithm in Computer Graphics
      The Point Clipping Algorithm is a fundamental algorithm used in Computer Graphics to determine whether a point lies inside or outside a specific region or boundary. It is particularly useful when dealing with objects that have complex shapes or when displaying only a portion of an image. Clipping: I
      10 min read

    • Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
      Description:- In this algorithm, we are given 9 regions on the screen. Out of which one region is of the window and the rest 8 regions are around it given by 4 digit binary.  The division of the regions are based on (x_max, y_max) and (x_min, y_min). The central part is the viewing region or window,
      15+ min read

    • Polygon Clipping | Sutherland–Hodgman Algorithm
      A convex polygon and a convex clipping area are given. The task is to clip polygon edges using the Sutherland–Hodgman Algorithm. Input is in the form of vertices of the polygon in clockwise order. Examples: Input : Polygon : (100,150), (200,250), (300,200) Clipping Area : (150,150), (150,200), (200,
      15 min read

    • Implementation of a Falling Matrix
      Since the dawn of computers, Hollywood has greatly demonstrated a Hacker or a Programmer as someone sitting on a computer typing random keys on computer which ultimately compiles to a Falling matrix like simulation. Here, we will try to implement a similar falling matrix simulation on the console us
      5 min read

    Visible Surface Detection

    • A-Buffer Method
      Prerequisite : depth-buffer (or Z Buffer) method A-Buffer method in computer graphics is a general hidden face detection mechanism suited to medium scale virtual memory computers. This method is also known as anti-aliased or area-averaged or accumulation buffer. This method extends the algorithm of
      3 min read

    • Z-Buffer or Depth-Buffer method
      When viewing a picture containing non transparent objects and surfaces, it is not possible to see those objects from view which are behind from the objects closer to eye. To get the realistic screen image, removal of these hidden surfaces is must. The identification and removal of these surfaces is
      5 min read

    • Back-Face Detection Method
      When we project 3-D objects on a 2-D screen, we need to detect the faces that are hidden on 2D. Back-Face detection, also known as Plane Equation method, is an object space method in which objects and parts of objects are compared to find out the visible surfaces. Let us consider a triangular surfac
      3 min read

    3-Dimension Object Representation

    • Snowflakes Fractal using Python
      To create Snowflake fractals using Python programmingWhat are fractals A fractal is a never-ending pattern. Fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop. Driven by recu
      3 min read

    • Koch Curve or Koch Snowflake
      What is Koch Curve? The Koch snowflake (also known as the Koch curve, Koch star, or Koch island) is a mathematical curve and one of the earliest fractal curves to have been described. It is based on the Koch curve, which appeared in a 1904 paper titled "On a continuous curve without tangents, constr
      4 min read

    • Klee's Algorithm (Length Of Union Of Segments of a line)
      Given starting and ending positions of segments on a line, the task is to take the union of all given segments and find length covered by these segments.Examples: Input : segments[] = {{2, 5}, {4, 8}, {9, 12}} Output : 9 Explanation: segment 1 = {2, 5} segment 2 = {4, 8} segment 3 = {9, 12} If we ta
      9 min read

    • Cubic Bezier Curve Implementation in C
      What is a bezier curve? So a Bezier curve is a mathematically defined curve used in two-dimensional graphic applications like adobe Illustrator, Inkscape etc. The curve is defined by four points: the initial position and the terminating position i.e P0 and P3 respectively (which are called "anchors"
      11 min read

    • Fractals in C/C++
      A Fractal is a never-ending pattern. Fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop. Mathematically fractals can be explained as follows. The location of a point on a scr
      6 min read

    Open GL

    • Scan-line Polygon filling using OPENGL in C
      Figures on a computer screen can be drawn using polygons. To fill those figures with color, we need to develop some algorithm.There are two famous algorithms for this purpose: Boundary fill and Scanline fill algorithms.Boundary filling requires a lot of processing and thus encounters few problems in
      8 min read

    • Rendering a Triangle using OpenGL(using Shaders)
      In this article we'll see how to render a triangle using OpenGL. A triangle is probably the simplest shapes you can draw in OpenGL after points and lines and any complicated geometry that you make will me made up of number of triangles joined together.We'll be using the programmable pipeline, so we'
      9 min read

    • Getting started with OpenGL
      Open Graphics Library (OpenGL) is a cross-language (language independent), cross-platform (platform-independent) API for rendering 2D and 3D Vector Graphics(use of polygons to represent image). OpenGL API is designed mostly in hardware. Design : This API is defined as a set of functions which may be
      4 min read

    • OpenGL program for Simple Ball Game
      Prerequisite - OpenGLOpenGL is a cross-language, cross-platform API for rendering 2D and 3D Vector Graphics. Using this, we can make a lot of design as well as animations. Below is a simple Game made using OpenGL.Description : In this, a ball is moving starting from middle and goes to up-left in sta
      5 min read

    • OpenGL program for simple Animation (Revolution) in C
      OpenGL is a cross-language, cross-platform API for rendering 2D and 3D Vector Graphics. Using this, we can make a lot of design as well as animations. Below is the simple animation made using OpenGL.Approach : To make a picture moving, we need to understand the working procedure of a function used t
      6 min read

    • Translation of objects in computer graphics
      In computer graphics, we have seen how to draw some basic figures like line and circles. In this post we will discuss on basics of an important operation in computer graphics as well as 2-D geometry, which is transformation. In computer graphics, transformation of the coordinates consists of three m
      7 min read

    Graphics function in C

    • pieslice() function in C
      pieslice() draws and fills a pie slice with center at (x, y) and given radius r. The slice travels from s_angle to e_angle which are starting and ending angles for the pie slice. The angles for pie-slice are given in degrees and are measured counterclockwise. Syntax : void pieslice(int x, int y, int
      2 min read

    • outtextxy() function in C
      The header file graphics.h contains outtextxy() function which displays the text or string at a specified point (x, y) on the screen. Syntax : void outtextxy(int x, int y, char *string); where, x, y are coordinates of the point and, third argument contains the address of string to be displayed. Exam
      1 min read

    • settextstyle function in C
      The header file graphics.h contains settextstyle() function which is used to change the way in which text appears. Using it we can modify the size of text, change direction of text and change the font of text. Syntax : void settextstyle(int font, int direction, int font_size); where, font argument s
      2 min read

    • outtext() function in C
      The header file graphics.h contains outtext() function which displays text at current position. Syntax : void outtext(char *string); Examples : Input : string = "Hello Geek, Have a good day !" Output : Input : string = "GeeksforGeeks is the best !" Output : Note : Do not use text mode functions like
      1 min read

    • setlinestyle() function in C
      The header file graphics.h contains setlinestyle() function which sets the style for all lines drawn by line, lineto, rectangle, drawpoly, and so on. Syntax : void setlinestyle(int linestyle, unsigned upattern, int thickness); Examples : Input : x = 200, y = 100 Output : x and y are initialized as (
      2 min read

    • getx() function in C
      The header file graphics.h contains getx() function which returns the X coordinate of the current position. Syntax : int getx(); Example : Explanation : Initially, the X coordinate of the current position is 0. On moving the coordinates using moveto() function, the X coordinate changes to 80. Below
      2 min read

    • sector() function in C
      The header file graphics.h contains sector() function which draws and fills an elliptical pie slice with (x, y) as center, (s_angle, e_angle) as starting and ending angle and (x_radius, y_radius) as x and y radius of sector. Syntax : void sector(int x, int y, int s_angle, int e_angle, int x_radius,
      2 min read

    • moveto() function in C
      The header file graphics.h contains moveto() function which changes the current position to (x, y) Syntax : void moveto(int x, int y); Examples : Input : x = 70, y = 40 Output : Input : x = 50, y = 80 Output : Below is the implementation of moveto() function: // C Implementation for moveto() #includ
      2 min read

    • gety() function in C
      The header file graphics.h contains gety() function which returns the Y coordinate of the current position. Syntax : int gety(); Example : Explanation : Initially, the Y coordinate of the current position is 0. On moving the coordinates using moveto() function, the Y coordinate changes to 50. Below
      2 min read

    • getmaxx() function in C
      The header file graphics.h contains getmaxx() function which returns the maximum X coordinate for current graphics mode and driver. Syntax : int getmaxx(); Below is the implementation of getmaxx() function: // C Implementation for getmaxx() #include <graphics.h> #include <stdio.h> // dri
      1 min read

    • lineto() function in C
      The header file graphics.h contains lineto() function which draws a line from current position to the point(x,y). Note : Use getx() and gety() to get the current position. Syntax : lineto(int x, int y); where, (x, y) are the coordinates upto which the line will be drawn from previous point. CASE 1 :
      2 min read

    • arc function in C
      The header file graphics.h contains arc() function which draws an arc with center at (x, y) and given radius. start_angle is the starting point of angle and end_angle is the ending point of the angle. The value of the angle can vary from 0 to 360 degree. Syntax : void arc(int x, int y, int start_ang
      2 min read

    • bar3d() function in C graphics
      The header file graphics.h contains bar3d() function which is used to draw a 2-dimensional, rectangular filled in bar . Coordinates of left top and right bottom corner of bar are required to draw the bar. Syntax : void bar3d(int left, int top, int right, int bottom, int depth, int topflag); where, l
      2 min read

    • moverel() function in C
      The header file graphics.h contains moverel() function which moves a point from the current position(x_pos1, y_pos1) to a point that is at a relative distance (x, y) from the Current Position and then advances the Current Position by (x, y). Note : getx and gety can be used to find the current posit
      3 min read

    • cleardevice() function in C
      The header file graphics.h contains cleardevice() function which clears the screen in graphics mode and sets the current position to (0,0). Clearing the screen consists of filling the screen with current background color. Syntax : void cleardevice(); Below is the implementation of cleardevice() in C
      1 min read

    • closegraph() function in C
      The header file graphics.h contains closegraph() function which closes the graphics mode, deallocates all memory allocated by graphics system and restores the screen to the mode it was in before you called initgraph. Syntax : void closegraph(); Below is the implementation of closegraph() in C. // C
      1 min read

    • drawpoly() function in C
      The header file graphics.h contains drawpoly() function which is used to draw polygons i.e. triangle, rectangle, pentagon, hexagon etc. Syntax : void drawpoly( int number, int *polypoints ); where, number indicates (n + 1) number of points where n is the number of vertices in a polygon. polypoints p
      2 min read

    • putpixel() function in C
      The header file graphics.h contains putpixel() function which plots a pixel at location (x, y) of specified color. Syntax : void putpixel(int x, int y, int color); where, (x, y) is the location at which pixel is to be put , and color specifies the color of the pixel. Explanation : A RED color pixel
      2 min read

    • getarcoords() function in C
      The header file graphics.h contains getarccoords() function which is used to get coordinates of arc which is drawn most recently. arccoordstype is a predefined structure which is defined as follows: Syntax : struct arccoordstype { // center point of arc int x, y; // start position int xstart, ystart
      2 min read

    • getbkcolor() function in C
      The header file graphics.h contains getbkcolor() function which returns the current background color. Syntax : int getbkcolor(); As getbkcolor() returns an integer value corresponding to the background color, so below is the table for Color values. Colors Table : COLOR INT VALUES -------------------
      2 min read

    • getmaxcolor() function in C
      The header file graphics.h contains getmaxcolor() function, which returns maximum color value for current graphics mode and driver. As color numbering starts from zero, total number of colors available for current graphics mode and driver are ( getmaxcolor() + 1 ) . Syntax : int getmaxcolor(); Below
      2 min read

    • getpixel() function in C
      The header file graphics.h contains getpixel() function which returns the color of pixel present at location (x, y). Syntax : int getpixel(int x, int y); Note : By default the screen is BLACK, therefore color of pixel at (0,0) is BLACK. Below is the implementation of getpixel() function. // C Implem
      2 min read

    • setcolor function in C
      The header file graphics.h contains setcolor() function which is used to set the current drawing color to the new color. Syntax : void setcolor(int color); Explanation : In Graphics, each color is assigned a number. Total number of colors available are 16. Number of available colors depends on curre
      2 min read

    • imagesize() function in C
      The header file graphics.h contains imagesize() function which returns the number of bytes required to store a bit-image. Syntax : unsigned int imagesize(int left, int top, int right, int bottom); where, left, top, right, and bottom define the area of the screen in which image is stored. Below is th
      2 min read

    • textheight() function in C
      The header file graphics.h contains textheight() function which returns the height of input string in pixels. Syntax : int textheight(char *string); Example : Input : string = "Hello Geek ! Have a good day." Output : Below is the implementation of textheight() function. // C Implementation for texth
      1 min read

    • textwidth() function in C
      The header file graphics.h contains textwidth () function which returns the width of input string in pixels. Syntax : int textwidth(char *string); Example : Input : string = "Hello Geek ! Have a good day." Output : Below is the implementation of textwidth() function. // C Implementation for textwidt
      1 min read

    • grapherrormsg() function in C
      The header file graphics.h contains grapherrormsg() function which returns an error message string. Syntax : char *grapherrormsg( int errorcode ); where, errorcode: code for the respective error Illustration of the grapherrormsg() : In the below program, gd = DETECT is not written and thus program m
      1 min read

    • fillpoly() function in C
      The header file graphics.h contains fillpoly() function which is used to draw and fill a polygon i.e. triangle, rectangle, pentagon, hexagon etc. It require same arguments as drawpoly(). Syntax : void fillpoly( int number, int *polypoints ); where, number indicates (n + 1) number of points where, n
      3 min read

    • fillellipse() function in C
      The header file graphics.h contains fillellipse() function which draws and fills an ellipse with center at (x, y) and (x_radius, y_radius) as x and y radius of ellipse. Syntax : void fillellipse(int x, int y, int x_radius, int y_radius); where, (x, y) is center of the ellipse. (x_radius, y_radius) a
      1 min read

    • bar() function in C graphics
      The header file graphics.h contains bar() function which is used to draw a 2-dimensional, rectangular filled in bar. Syntax : void bar(int left, int top, int right, int bottom); where, left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specif
      2 min read

    Misc

    • How to add "graphics.h" C/C++ library to gcc compiler in Linux
      While trying c graphic programming on Ubuntu, I figured out that graphic.h is not a standard C library and it is not supported by gcc compiler. So I am writing this article to explain the process.If you want to use graphics.h on Ubuntu platform you need to compile and install libgraph. It is the imp
      2 min read

    • How to include graphics.h in CodeBlocks?
      Compiling graphics codes on CodeBlocks IDE shows an error: “Cannot find graphics.h”. This is because graphics.h runs is not available in the library folder of CodeBlocks. To successfully compile graphics code on CodeBlocks, setup winBGIm library. How to include graphics.h in CodeBlocks ? Please foll
      2 min read

    • Computer Graphics |Cathode Ray Oscilloscope| Cathode ray tube (video display technology)
      Computer Graphics has become a common element in today's modern world. Be it in user interfaces, data visualization, motion pictures, etc, computer graphics play an important role. The primary output device in a graphics system is a video monitor. Although many technologies exist, the operation of m
      5 min read

    • High Definition Multimedia Interface (HDMI)
      High Definition Multimedia Interface is one of the most used audio/video interfaces for transmitting uncompressed video data and compressed or uncompressed digital audio data from an HDMI-compliant source device. These devices can be a display controller, a compatible computer monitor, video project
      4 min read

    • Common Video Format
      Whenever a video file is saved it contains two file in it. One is the container and other is codecs. Container defines the structure of the video file and which codecs will be used. Codecs is used to compress and decompress video file. Some of common container format are: Flash Video Format (.flv) T
      2 min read

    • Audio Format
      Audio format defines the quality and loss of audio data. Based on application different type of audio format are used. Audio formats are broadly divided into three parts: Uncompressed Format Lossy Compressed format Lossless Compressed Format 1. Uncompressed Audio Format: PCM - It stands for Pulse-Co
      3 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences