Source Code of ball game
Source Code of ball game
#include <iostream>
#include <GL/glut.h>
#include <cmath>
void setRandomBallDirection() {
ballSpeedX = (rand() % 2 == 0 ? 2.0f : -2.0f) * (1 + (rand() % 3)); // Random speed and direction
ballSpeedY = (rand() % 2 == 0 ? 2.0f : -2.0f) * (1 + (rand() % 3)); // Random speed and direction
// Initialization function
void myInit() {
glClearColor(1.0, 1.0, 1.0, 0.0); // Set background color to white
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
void drawScore() {
switch (key) {
rectX -= moveSpeed;
if (rectX < -600 + rectWidth / 2) rectX = -600 + rectWidth / 2; // Keep inside left wall
break;
rectX += moveSpeed;
if (rectX > 600 - rectWidth / 2) rectX = 600 - rectWidth / 2; // Keep inside right wall
break;
}
glutPostRedisplay(); // Request to redraw
ballX += ballSpeedX;
ballY += ballSpeedY;
if (ballY - ballRadius <= -300 && ballX >= rectX - rectWidth / 2 && ballX <= rectX + rectWidth / 2) {
score++;
ballY = 0.0f;
std::cout << "Game Over! Final Score: " << score << std::endl;
exit(0); // End the game
// Display function
void myDisplay() {
glBegin(GL_TRIANGLE_FAN);
glVertex2f(ballX, ballY);
glEnd();
glBegin(GL_QUADS);
glEnd();
// Main function
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
return 0;