2D PONG GAME ABSTRACT This project involves creating a 2D Pong game using the OpenGL graphics API. The game will feature a ball and paddles represented by basic shapes like rectangles and circles. It will incorporate essential game physics, including ball movement, paddle movement, and collision detection. The game will be rendered using OpenGL, with a defined game window and coordinates mapped within it. The score of each player will be displayed on the screen, and the game will update scores when the ball hits the walls or paddles. Players will control their paddles using specific keys on the keyboard. Player A will use 'W' and 'S' to move the paddle up and down, while Player B will use 'I' and 'K'. The ball's movement will be regularly updated, and collision detection will determine if it hits the walls or paddles, resulting in appropriate changes in direction. By creating this 2D Pong game, the project showcases the principles of game development and demonstrates the use of computer graphics techniques. It highlights the application of OpenGL for rendering game elements, handling user input, and simulating basic physics. Overall, this project provides an introduction to computer graphics and game development, allowing users to explore fundamental concepts while enjoying an interactive gaming experience. DEPT OF CSE, GECR 2D PONG GAME Table of Contents: CHAPTER 1. INTRODUCTION ...................................................................................................................... 1 1.1 INTRODUCTION TO COMPUTER GRAPHICS ............................................................ 1 CHAPTER 2. SYSTEM REQUIREMENTS ..................................................................................................... 3 2.1 SOFTWARE REQUIREMENTS ....................................................................................... 3 2.2 HARDWARE REQUIREMENTS ..................................................................................... 3 CHAPTER 3. SYSTEM DESIGN ..................................................................................................................... 4 3.1 INTRODUCTION TO OPENGL....................................................................................... 4 3.2 BRIEF DESCRIPTION ABOUT PROJECT ..................................................................... 6 3.3 KEYS USED...................................................................................................................... 7 CHAPTER 4. APPLICATIONS ........................................................................................................................ 9 CHAPTER 5. ADVANTAGES......................................................................................................................... 11 CHAPTER 6. SOURCE CODE ....................................................................................................................... 13 CHAPTER 7. OUTPUT: ................................................................................................................................. 22 CONCLUSION: ....................................................................................................................... 23 REFERENCES ......................................................................................................................... 25 DEPT OF CSE, GECR 2D PONG GAME CHAPTER 1.INTRODUCTION 1.1 INTRODUCTION TO COMPUTER GRAPHICS Computer graphics is a multidisciplinary field that involves the creation, manipulation, and display of visual content using computers. It encompasses various domains such as entertainment, design, simulations, virtual reality, and data visualization. By leveraging mathematical models and algorithms, computer graphics professionals can generate realistic and immersive visuals that mimic the real world or explore imaginative realms. In the entertainment industry, computer graphics plays a crucial role in creating visually stunning movies, video games, and animated content. It enhances the visual appeal and storytelling capabilities of these media by enabling realistic character animations and breathtaking visual effects. In design, computer graphics allows professionals to visualize concepts and designs in a virtual space, aiding architects, industrial designers, and graphic artists in making informed decisions and effectively communicating their ideas. Simulation and modeling benefit from computer graphics as scientists and engineers can simulate complex phenomena and study the behavior of physical systems in a controlled environment. Moreover, computer graphics is integral to virtual reality (VR) and augmented reality (AR), as it enables the rendering and display of virtual objects in real-time, creating immersive and interactive experiences for users in virtual environments or overlaying digital content onto the real world. Overall, computer graphics is a powerful tool that combines mathematics, computer science, physics, and art to create visually captivating and technologically advanced experiences across various fields. Basic Concepts and Principles: 1. Coordinate systems and transformations: In computer graphics, coordinate systems play a crucial role in representing the positions, orientations, and transformations of objects in a 2D or 3D space. A coordinate system provides a reference framework with axes, typically X, Y, and Z, along which points can be located. Cartesian coordinates are commonly used, where distances are measured along each axis. This allows precise positioning of objects in a virtual environment. Additionally, coordinate systems can be transformed through various operations such as translation, rotation, and scaling. Translation involves moving objects in the coordinate system along the axes. It allows for changing the position of objects in a linear manner, either in a specific direction or based on user input. Rotation, on the other hand, enables the transformation of objects by changing their orientation. Objects can be rotated around a specific point or axis, resulting in visually appealing animations and simulations. Scaling modifies the size of objects, allowing them to be enlarged or reduced uniformly or non-uniformly along different axes. This transformation is useful for creating visual effects, such as zooming in or out, or resizing objects dynamically. Transformations in computer graphics are often represented using matrices. Transformation matrices combine translation, rotation, and scaling operations into a single matrix that can be DEPT OF CSE, GECR 1 2D PONG GAME applied to a set of coordinates. By multiplying these matrices together, complex transformations can be achieved, enabling the manipulation of objects in a virtual environment. Understanding coordinate systems and transformations is vital for accurately positioning and manipulating objects in computer graphics. It provides the foundation for creating visually appealing scenes, realistic animations, and interactive experiences. 2. Color models and representation: Color is a fundamental aspect of computer graphics, enabling the depiction of realistic scenes, conveying information, and evoking emotions. Color models define how colors are represented and organized. The RGB (Red, Green, Blue) color model is widely used in computer graphics and digital displays. In this model, colors are created by combining different intensities of red, green, and blue components. Each component typically ranges from 0 to 255, allowing for a vast array of color possibilities. Another commonly used color model is CMYK (Cyan, Magenta, Yellow, Black), which is widely used in print media. It represents colors by subtractive mixing of pigments. The CMYK model is particularly suitable for representing colors in physical printing, as it can reproduce a wide range of colors using a combination of cyan, magenta, yellow, and black inks. In addition to RGB and CMYK, there are other color models such as HSL (Hue, Saturation, Lightness) and HSV (Hue, Saturation, Value), which provide alternative ways to represent and manipulate colors. These models offer advantages in specific applications, such as image editing or color adjustments. Color representation in computer graphics involves encoding color values in digital systems. Digital color representation typically utilizes integer or floating-point formats to store color information accurately. For example, 8-bit per channel representation allocates 8 bits (or 1 byte) for each color component in the RGB model, allowing 256 intensity levels per component. This high level of precision enables the creation of vibrant and realistic graphics. Understanding color models and representation is crucial for precise rendering, color manipulation, and color management in computer graphics applications. It allows for the creation of visually appealing and meaningful graphics by harnessing the power of color. Whether it's selecting an appropriate color scheme, performing color corrections, or achieving accurate color reproduction, a solid understanding of color models and representation is essential for producing high-quality computer graphics. DEPT OF CSE, GECR 2 2D PONG GAME CHAPTER 2. SYSTEM REQUIREMENTS 2.1 SOFTWARE REQUIREMENTS To run the 2D Pong game using OpenGL, It need the following software requirements: 1. Operating System: The game should be compatible with the operating system you are using, such as Windows, macOS, or Linux. 2. OpenGL Library: Install the appropriate OpenGL library for your operating system. In this code snippet, the game is using the GLUT (OpenGL Utility Toolkit) library, so ensure that GLUT is installed and properly configured. Compiler: A C++ compiler is required to compile and run the game code. You can use popular compilers such as GCC (GNU Compiler Collection) or Microsoft Visual C++ Compiler 2.2 HARDWARE REQUIREMENTS To run the 2D Pong game using OpenGL, the system needs to meet the following hardware requirements: 1. Computer: A desktop or laptop computer capable of running OpenGL applications. 2. Processor: A modern processor capable of handling real-time graphics processing. 3. Graphics Card: A graphics card that supports OpenGL with hardware acceleration. The card should have adequate memory and processing power to render 2D graphics smoothly. 4. Memory (RAM): Sufficient RAM to support the operating system and the game application simultaneously. A minimum of 4GB of RAM is recommended. 5. Display: A monitor or screen capable of displaying a resolution of at least 800x600 pixels. Higher resolutions will provide a better gaming experience. 6. Input Devices: A keyboard to control the game's paddles and interact with the game interface. DEPT OF CSE, GECR 3 2D PONG GAME CHAPTER 3. SYSTEM DESIGN 3.1 INTRODUCTION TO OPENGL OpenGL (Open Graphics Library) is a widely-used open-source graphics API (Application Programming Interface) that provides a set of functions and commands for rendering 2D and 3D graphics. It is a platform-independent and hardware-accelerated graphics library that allows developers to create interactive applications with rich visual content. OpenGL provides a high-level abstraction for interacting with graphics hardware, enabling efficient rendering and manipulation of geometric primitives, textures, and shaders. It offers a wide range of rendering capabilities, including lighting, shading, texture mapping, and transformations. OpenGL is supported by various programming languages, making it accessible and versatile for developers working on different platforms. OpenGL (Open Graphics Library) is an open-source graphics API widely used for rendering 2D and 3D graphics. It provides developers with a powerful set of functions and commands to create interactive applications with rich visual content. One of the key advantages of OpenGL is its platform independence, allowing developers to write code that can run on various operating systems and hardware configurations. This portability eliminates the need for platform-specific code and simplifies application development. Furthermore, OpenGL leverages the GPU's capabilities to achieve high-performance rendering, enabling real-time and interactive graphics. Its flexible pipeline architecture provides fine-grained control over the rendering process, allowing developers to optimize performance and achieve desired visual effects. Additionally, OpenGL supports extensions, enabling developers to access advanced rendering techniques and new hardware capabilities. The extensive community support and availability of resources, documentation, and libraries make OpenGL an accessible and wellsupported choice for computer graphics programming. By seamlessly integrating with other libraries and frameworks, developers can combine technologies and create comprehensive and immersive applications. Overall, OpenGL empowers developers to create visually stunning graphics and deliver immersive experiences across multiple platforms. DEPT OF CSE, GECR 4 2D PONG GAME INTRODUCTION TO OPENGL LIBRARIES OpenGL (Open Graphics Library) is a cross-platform graphics API (Application Programming Interface) that enables developers to create and render 2D and 3D graphics. It provides a set of functions for accessing and utilizing graphics hardware efficiently, abstracting the complexities of hardware interaction Features: 1. Cross-platform: OpenGL is supported on various operating systems, including Windows, macOS, Linux, and mobile platforms like Android and iOS. 2. Low-level API: It offers a low-level programming interface, allowing developers direct access to the graphics hardware for efficient rendering. 3. Standardization: OpenGL has become a widely adopted industry standard for graphics programming, ensuring compatibility across different platforms and systems. 4. State machine model: Developers can set various states and parameters to control the rendering process and manipulate graphical objects. 5. Pipeline architecture: OpenGL follows a pipeline architecture, consisting of stages for processing geometry, vertices, primitives, rasterization, and fragments, providing developers control over each stage. 6. Shader programming: It supports shaders, which are small programs that execute custom operations on the GPU, enabling advanced and flexible graphics rendering. 7. Integration with libraries: OpenGL can be used alongside libraries like GLUT and GLFW, which provide additional functionality for window creation, input handling, and application management. HEADER FILES: 1. `#include <GL/gl.h>`: This line includes the `gl.h` header file, which is the primary header file of the OpenGL library. It contains the core OpenGL functions and constants that are required for rendering and manipulating graphics primitives, managing the OpenGL state, and applying transformations, lighting, and shading effects. 2. `#include <GL/glu.h>`: This line includes the `glu.h` header file, which is part of the OpenGL Utility Library (GLU). GLU provides additional utility functions and constants that are built on top of the core OpenGL functionality. It includes functions for creating and manipulating geometric primitives, managing viewing transformations, performing projection calculations, and handling image loading and texture mapping. 3. `#include <GL/glut.h>`: This line includes the `glut.h` header file, which is part of the OpenGL Utility Toolkit (GLUT). GLUT is a library that simplifies the creation of OpenGL applications. It provides functions and constants for creating windows, handling user input (such as keyboard and mouse events), managing timers, and displaying text on the screen. By including `glut.h`, you can utilize the features and functionalities provided by GLUT to create interactive and user-friendly OpenGL applications. DEPT OF CSE, GECR 5 2D PONG GAME 3.2 BRIEF DESCRIPTION ABOUT PROJECT A simple 2D Pong game created using OpenGL. The game includes basic shapes such as rectangles and circles to create the game elements, along with simple game physics like ball movement, paddle movement, and collision detection. The game initializes variables for scores, ball position, ball direction, and paddle positions. The init function sets up the initial configuration, including the background color and projection settings. The drawText function is used to display the score on the screen. In the display function, the game elements are drawn, including the score, ball, and paddles. The update function is responsible for updating the ball's position and checking for collisions with walls and paddles. It also handles score updates. The keyboard function handles keyboard input to move the paddles up and down. The main function initializes the OpenGL environment, sets up the window, and registers the necessary callbacks. It then enters the main event loop, allowing the game to run. code implements a simple 2D Pong game using OpenGL. It involves creating game elements such as the ball and paddles using basic shapes like rectangles and circles. The game includes features like ball movement, paddle movement, collision detection, and score tracking for two players. The init function initializes the OpenGL environment, sets the clear color, and defines the orthographic projection. The drawText function is used to display text on the screen. The display function is responsible for rendering the game elements. It clears the color buffer, draws the score text, ball, and paddles using appropriate OpenGL functions. The update function is called periodically to update the game state. It updates the ball's position, checks for collisions with walls and paddles, and updates the score accordingly. It also handles the ball's reflection upon collision and triggers the screen redisplay. The keyboard function handles keyboard input and allows players to control the paddles. The 'w' and 's' keys control paddle A's movement (up and down, respectively), while the 'i' and 'k' keys control paddle B's movement. In the main function, the GLUT library is initialized, the display mode and window properties are set, and the window is created. The necessary callbacks, such as display and keyboard functions, are registered, and the main event loop is started with glutMainLoop(). DEPT OF CSE, GECR 6 2D PONG GAME 3.3 KEYS USED HERE'S HOW THE KEYS ARE USED IN THE KEYBOARD FUNCTION: Key Action ‘w’ or’W’ Move paddle A upwards if paddleAY<120 ‘s’ or ‘S’ Move paddle A downwards if paddleAY>120 ‘i’ or ‘I’ Move paddle B upwards if paddleBY<120 ‘k’ or ‘K’ Move paddle B downwards if paddleBY>0 1. The 'w' or 'W' key: When this key is pressed, it checks if the paddleAY (the y-coordinate of paddle A) is less than 120 (the upper boundary). If it is, it increments the paddleAY value by 10, moving the paddle A upwards. 2. The 's' or 'S' key: When this key is pressed, it checks if the paddleAY is greater than 0 (the lower boundary). If it is, it decrements the paddleAY value by 10, moving the paddle A downwards. 3. The 'i' or 'I' key: When this key is pressed, it checks if the paddleBY (the y-coordinate of paddle B) is less than 120. If it is, it increments the paddleBY value by 10, moving the paddle B upwards. 4. The 'k' or 'K' key: When this key is pressed, it checks if the paddleBY is greater than 0. If it is, it decrements the paddleBY value by 10, moving the paddle B downwards. IMPLEMENTATION 1. Window Initialization: The project uses the OpenGL utility toolkit (GLUT) to create a window for the game. The glutInit() function is called to initialize GLUT, and glutCreateWindow() creates the game window with a specified title, size, and position. 2. Game Elements: The game consists of several elements, including the ball and two paddles. The ball is represented as a solid sphere using glutSolidSphere(), and the paddles are drawn as rectangles using glRectf(). 3. Coordinate System and Viewport: The game uses a 2D coordinate system, and gluOrtho2D() is called in the init() function to set up the orthographic projection. This defines the range of the coordinate system that maps to the game window. 4. Display Function: The display() function is responsible for rendering the game scene. It clears the color buffer using glClear() and sets the color for subsequent drawing operations using glColor3f(). The game elements (ball, paddles) are drawn using appropriate transformation functions like glTranslatef() and glRotatef(). DEPT OF CSE, GECR 7 2D PONG GAME 5. Game Logic: The update() function is called periodically using glutTimerFunc() to update the game state. It handles the movement of the ball, collision detection with walls and paddles, and updates the scores. The ball's position is updated by changing the ballX and ballY variables based on the ballDirX and ballDirY values. 6. User Input: The keyboard() function handles user input from the keyboard. It detects key presses for controlling the movement of the paddles. For example, pressing 'w' or 'W' moves paddle A up, and pressing 's' or 'S' moves paddle A down. 7. Score Display: The drawText() function is used to display the score on the screen. It uses glRasterPos2i() to position the text on the screen and glutBitmapCharacter() to render each character of the text using the specified bitmap font. 8. Main Loop: The glutMainLoop() function enters the main event processing loop, where it handles user input, updates the game state, and renders the scene. This loop continues until the user closes the game window. DEPT OF CSE, GECR 8 2D PONG GAME CHAPTER 4. APPLICATIONS 1. Entertainment and Media: Computer graphics revolutionize the entertainment industry by enabling visually stunning and immersive experiences. They are widely used in movies, video games, virtual reality (VR), and augmented reality (AR). From lifelike characters to breathtaking environments, computer graphics bring stories to life and captivate audiences. 2. Design and Visualization: Computer graphics find applications in various design fields, empowering architects, industrial designers, fashion designers, and interior designers. They help in creating realistic 3D models, visualizing concepts, and simulating real-world environments. Designers can iterate, explore different possibilities, and communicate ideas effectively through computer-generated visuals. 3. Simulation and Training: Computer graphics are indispensable in simulating and training for diverse scenarios. Flight simulators, driving simulators, medical simulations, and military training all rely on computer graphics to create realistic virtual environments. Professionals can gain hands-on experience, practice complex tasks, and enhance their skills in a safe and controlled setting. 4. Scientific and Data Visualization: Computer graphics aid scientists and researchers in visualizing complex data sets. They are used to represent molecular structures, weather patterns, astronomical phenomena, and medical imaging. By presenting data in a visual form, computer graphics facilitate analysis, interpretation, and communication of scientific findings. 5. Computer-Aided Design (CAD): Computer graphics are the backbone of CAD software, which is widely used in engineering, product design, and manufacturing industries. CAD enables precise drafting, 3D modeling, and prototyping of products. Designers can create and refine designs, simulate functionality, and optimize their work using computer graphics. 6. Advertising and Marketing: Computer graphics play a significant role in advertising and marketing campaigns. They allow the creation of visually appealing and persuasive content, including eye-catching graphics, animations, and visual effects. Computer graphics help businesses engage and attract their target audience, conveying their message in a compelling manner. 7. Virtual Reality (VR) and Augmented Reality (AR): Computer graphics are vital components of VR and AR technologies. They enable users to immerse themselves in virtual worlds or overlay digital information onto the real world. Computer graphics provide interactive and realistic experiences in gaming, education, training, and various industries. 8. Computer-Generated Imagery (CGI): CGI is extensively used in the film and animation industry to create both realistic and fantastical visuals. It involves generating images, characters, and environments entirely through computer graphics. CGI pushes the boundaries of imagination and brings extraordinary stories to life on the big screen. 9. User Interfaces and User Experience (UI/UX): Computer graphics contribute to the design and development of user interfaces that are visually appealing, intuitive, and engaging. They enhance the overall user experience in software applications, websites, and interactive systems. DEPT OF CSE, GECR 9 2D PONG GAME Through thoughtful graphic design, users can navigate and interact with digital interfaces seamlessly. 10. Medical Visualization: Computer graphics have a significant impact on medical visualization. They are utilized in surgical planning, anatomical modeling, and patient education. By rendering detailed and accurate visuals, doctors and researchers can explore and understand complex medical data, aiding in diagnosis, treatment planning, and educational purposes. DEPT OF CSE, GECR 10 2D PONG GAME CHAPTER 5. ADVANTAGES 1. Visualization and Communication: Computer graphics enable the visual representation of complex data, concepts, and ideas. It allows for effective communication of information through visual aids, charts, graphs, and interactive presentations. Visualizing data and concepts can enhance understanding, engagement, and decision-making processes. 2. Realism and Immersion: With advanced rendering techniques, computer graphics can create highly realistic and immersive visual experiences. This is particularly beneficial in fields such as gaming, virtual reality, and simulation, where users can be transported to virtual worlds and interact with lifelike environments and characters. 3. Creativity and Expression: Computer graphics provide a powerful medium for artistic expression and creativity. Artists, designers, and animators can use digital tools to create stunning visual artworks, animations, and visual effects. The ability to manipulate and transform digital objects opens up new possibilities for artistic exploration and experimentation. 4. Product Design and Prototyping: Computer-aided design (CAD) software allows for the creation and visualization of 3D models of products, buildings, and prototypes. This enables designers and engineers to iterate, refine, and test their designs virtually before physically manufacturing them. It reduces costs, accelerates the design process, and helps identify and resolve potential issues early on. 5. Simulation and Training: Computer graphics play a crucial role in simulation and training applications. For example, flight simulators replicate realistic flying conditions, allowing pilots to practice in a safe and controlled environment. Virtual simulations also enable training in medical procedures, emergency response scenarios, and industrial operations, improving learning outcomes and reducing risks. 6. Entertainment and Media: Computer graphics have revolutionized the entertainment industry, including movies, TV shows, and video games. Visual effects, computergenerated imagery (CGI), and animation techniques have opened up new possibilities for storytelling, creating visually stunning and captivating experiences for audiences worldwide. 7. Data Visualization and Analysis: Computer graphics help in analyzing and presenting large and complex datasets. By representing data visually, patterns, trends, and correlations can be easily identified, aiding decision-making and data-driven insights. Infographics, dashboards, and interactive visualizations make data more accessible and understandable to a broader audience. 8. Virtual Prototyping and Testing: Computer graphics enable virtual prototyping and testing of various products and systems. Engineers can simulate and evaluate the performance, behavior, and interactions of objects, structures, or simulations without the need for physical prototypes. This saves time, resources, and provides opportunities for optimization and refinement. DEPT OF CSE, GECR 11 2D PONG GAME 9. User Interface Design: Graphical user interfaces (GUIs) are a fundamental aspect of modern software applications. Computer graphics contribute to creating visually appealing, intuitive, and interactive interfaces that enhance user experience and productivity. Icons, buttons, menus, and visual feedback improve usability and accessibility. 10. Scientific Visualization: Computer graphics assist in visualizing scientific phenomena, simulations, and experimental results. It helps researchers and scientists better understand complex data, simulate physical processes, and communicate their findings effectively. DEPT OF CSE, GECR 12 2D PONG GAME CHAPTER 6. SOURCE CODE //2D Pong Game: Create a simple 2D Pong game using OpenGL. Use basic shapes such as rectangles and circles to create the game elements. Add simple game physics such as ball movement, paddle movement, and collision detection. #include <GL/glut.h> #include <stdlib.h> #include <time.h> #include <cstdio> int scoreA = 0; int scoreB = 0; int ballX = 50; int ballY = 50; int ballDirX = 1; int ballDirY = 1; int paddleAX = 10; int paddleAY = 30; int paddleBX = 10; int paddleBY = 30; void init(void) { glClearColor(0.0, 0.0, 0.0, 0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, 200.0, 0.0, 150.0); } void drawText(char* text, int length, int x, int y) { glMatrixMode(GL_PROJECTION); DEPT OF CSE, GECR 13 2D PONG GAME double* matrix = new double[16]; glGetDoublev(GL_PROJECTION_MATRIX, matrix); glLoadIdentity(); glOrtho(0, 400, 0, 300, -5, 5); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glPushMatrix(); glLoadIdentity(); glRasterPos2i(x,y); for(int i=0; i<length; i++) { glutBitmapCharacter(GLUT_BITMAP_9_BY_15, (int)text[i]); } glPopMatrix(); glMatrixMode(GL_PROJECTION); glLoadMatrixd(matrix); glMatrixMode(GL_MODELVIEW); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0, 1.0, 1.0); // Draw score char buffer[50]; sprintf(buffer, "Player A: %d Player B: %d", scoreA, scoreB); drawText(buffer, strlen(buffer), 100, 280); // Draw ball DEPT OF CSE, GECR 14 2D PONG GAME glPushMatrix(); glColor3f(1.0, 1.0, 1.0); glTranslatef(ballX, ballY, 0.0); glutSolidSphere(3.0, 20, 20); glPopMatrix(); // Draw paddle A glPushMatrix(); glColor3f(1.0, 1.0, 1.0); glTranslatef(paddleAX, paddleAY, 0.0); glRectf(0.0, 0.0, 10.0, 30.0); glPopMatrix(); // Draw paddle B glPushMatrix(); glColor3f(1.0, 1.0, 1.0); glTranslatef(180.0, paddleBY, 0.0); glRectf(0.0, 0.0, 10.0, 30.0); glPopMatrix(); glutSwapBuffers(); } void keyboard(unsigned char key, int x, int y) { // Move paddle A up if (key == 'w' || key == 'W') { if (paddleAY < 120) { paddleAY += 10; DEPT OF CSE, GECR 15 2D PONG GAME } } // Move paddle A down if (key == 's' || key == 'S') { if (paddleAY > 0) { paddleAY -= 10; } } // Move paddle B up if (key == 'i' || key == 'I') { if (paddleBY < 120) { paddleBY += 10; } } // Move paddle B down if (key == 'k' || key == 'K') { if (paddleBY > 0) { paddleBY -= 10; } } } DEPT OF CSE, GECR 16 2D PONG GAME void update(int value) { // Update ball position ballX += ballDirX; ballY += ballDirY; // Check if ball hit left wall if (ballX < 0) { ballDirX = -ballDirX; scoreB++; } // Check if ball hit right wall if (ballX > 190) { ballDirX = -ballDirX; scoreA++; } // Check if ball hit top wall if (ballY > 140) { ballDirY= -ballDirY; } // Check if ball hit bottom wall if (ballY < 0) { DEPT OF CSE, GECR 17 2D PONG GAME ballDirY = -ballDirY; } // Check if ball hit paddle A if (ballX < paddleAX + 10 && ballY > paddleAY && ballY < paddleAY + 30) { ballDirX = -ballDirX; } // Check if ball hit paddle B if (ballX > 170 && ballY > paddleBY && ballY < paddleBY + 30) { ballDirX = -ballDirX; } glutPostRedisplay(); glutTimerFunc(25, update, 0); } void keyboard(unsigned char key, int x, int y) { // Move paddle A up if (key == 'w' || key == 'W') { if (paddleAY < 120) { paddleAY += 10; } } DEPT OF CSE, GECR 18 2D PONG GAME // Move paddle A down if (key == 's' || key == 'S') { if (paddleAY > 0) { paddleAY -= 10; } } // Move paddle B up if (key == 'i' || key == 'I') { if (paddleBY < 120) { paddleBY += 10; } } // Move paddle B down if (key == 'k' || key == 'K') { if (paddleBY > 0) { paddleBY -= 10; } } } int main(int argc, char** argv) { DEPT OF CSE, GECR 19 2D PONG GAME glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(400, 300); glutInitWindowPosition(100, 100); glutCreateWindow("Pong Game"); init(); glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutTimerFunc(25, update, 0); glutMainLoop(); return 0; } #include <iostream> #include <windows.h> // Function to set console text color void SetConsoleColor(int color) { HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(consoleHandle, color); } // Function to reset console text color to default void ResetConsoleColor() { SetConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); } int main() DEPT OF CSE, GECR 20 2D PONG GAME { // Changing console text color to red SetConsoleColor(FOREGROUND_RED | FOREGROUND_INTENSITY); std::cout << "This is some red text!" << std::endl; // Changing console text color to green SetConsoleColor(FOREGROUND_GREEN | FOREGROUND_INTENSITY); std::cout << "This is some green text!" << std::endl; // Changing console text color to blue SetConsoleColor(FOREGROUND_BLUE | FOREGROUND_INTENSITY); std::cout << "This is some blue text!" << std::endl; // Resetting console text color to default ResetConsoleColor(); std::cout << "This is the default text color." << std::endl; return 0; } DEPT OF CSE, GECR 21 2D PONG GAME CHAPTER 7.OUTPUT: Figure 1: showing paddles A & B Figure 2: score get increase if opposite player miss DEPT OF CSE, GECR 22 2D PONG GAME Figure 3: showing display color to blue Figure 4: showing display color to red DEPT OF CSE, GECR 23 2D PONG GAME CONCLUSION: Computer graphics is a multidisciplinary field that combines math, computer science, physics, and art to create visual content using computers. It finds applications in entertainment, design, simulations, virtual reality, and data visualization. OpenGL, an open-source graphics API, enables the rendering of 2D and 3D graphics. It revolutionizes industries, fosters creativity, and enhances immersive experiences. From video games to architectural visualization, computer graphics plays a crucial role in delivering captivating visuals. Simulations and virtual reality benefit from realistic graphics, while data visualization simplifies complex information through visual representation. With continuous advancements, computer graphics drives innovation in various fields. Understanding its principles unlocks endless possibilities for creative expression and effective visual communication. DEPT OF CSE, GECR 24 2D PONG GAME REFERENCES 1. Donald Hearn & Pauline Baker: Computer Graphics with OpenGL Version,3rd / 4th Edition, Pearson Education,2011 2. Edward Angel: Interactive Computer Graphics- A Top Down approach with OpenGL, 5th edition. Pearson Education, 2008 2. James D Foley, Andries Van Dam, Steven K Feiner, John F Huges. "Computer Graphics with OpenGL". Pearson Education. 3. Xiang, Plastock. "Computer Graphics". Sham's Outline Series, 2nd edition, TMG. 4. Kelvin Sung, Peter Shirley, Steven Baer. "Interactive Computer Graphics: Concepts and Applications". Cengage Learning. 5. M M Raikar & Shreedhara K S. "Computer Graphics using OpenGL". 6. Foley, J. D., van Dam, A., Feiner, S. K., Hughes, J. F. (1995). Computer Graphics: Principles and Practice. Addison-Wesley Professional. 7. Shreiner, D., Sellers, G., Kessenich, J., Licea-Kane, B. (2013). OpenGL Programming Guide: The Official Guide to Learning OpenGL. Addison-Wesley Professional. 8. Nystrom, R. (2014). Game Programming Patterns. Genever Benning. 9. Learn OpenGL. (n.d.). Retrieved from https://learnopengl.com/ 10. OGLdev. (n.d.). Retrieved from http://www.ogldev.org/ 11. OpenGL-Tutorial.org. (n.d.). Retrieved from http://www.opengl-tutorial.org/ DEPT OF CSE, GECR 25