Pong game in C
Below is a simple implementation of a Pong game in C using the console. Copy and paste this code into a C file (e.g., PongGame.c) and run it to play the game. You can further enhance it by adding features such as scoring, sound effects, or improving the gameplay.
// Include stdio.h, conio.h and windows.h #include #define WIDTH 800 #define HEIGHT 600 #define PADDLE_WIDTH 20 #define PADDLE_HEIGHT 100 #define BALL_SIZE 20 #define PADDLE_SPEED 10 #define BALL_SPEED 3 int paddle1Y = HEIGHT / 2 - PADDLE_HEIGHT / 2; int paddle2Y = HEIGHT / 2 - PADDLE_HEIGHT / 2; int ballX = WIDTH / 2 - BALL_SIZE / 2; int ballY = HEIGHT / 2 - BALL_SIZE / 2; int ballXSpeed = BALL_SPEED; int ballYSpeed = BALL_SPEED; int gameover = 0; void movePaddle1Up() { if (paddle1Y - PADDLE_SPEED >= 0) { paddle1Y -= PADDLE_SPEED; } } void movePaddle1Down() { if (paddle1Y + PADDLE_HEIGHT + PADDLE_SPEED <= HEIGHT) { paddle1Y += PADDLE_SPEED; } } void movePaddle2Up() { if (paddle2Y - PADDLE_SPEED >= 0) { paddle2Y -= PADDLE_SPEED; } } void movePaddle2Down() { if (paddle2Y + PADDLE_HEIGHT + PADDLE_SPEED <= HEIGHT) { paddle2Y += PADDLE_SPEED; } } void moveBall() { ballX += ballXSpeed; ballY += ballYSpeed; // Collision with paddles if ((ballX <= PADDLE_WIDTH && ballY + BALL_SIZE >= paddle1Y && ballY <= paddle1Y + PADDLE_HEIGHT) || (ballX + BALL_SIZE >= WIDTH - PADDLE_WIDTH && ballY + BALL_SIZE >= paddle2Y && ballY <= paddle2Y + PADDLE_HEIGHT)) { ballXSpeed = -ballXSpeed; } // Collision with top and bottom walls if (ballY <= 0 || ballY + BALL_SIZE >= HEIGHT) { ballYSpeed = -ballYSpeed; } // Scoring if (ballX <= 0 || ballX + BALL_SIZE >= WIDTH) { ballX = WIDTH / 2 - BALL_SIZE / 2; ballY = HEIGHT / 2 - BALL_SIZE / 2; ballXSpeed = -ballXSpeed; } } void draw() { system("cls"); // Draw paddles for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { if ((j == 0 && i >= paddle1Y && i <= paddle1Y + PADDLE_HEIGHT) || (j == WIDTH - 1 && i >= paddle2Y && i <= paddle2Y + PADDLE_HEIGHT)) { printf("|"); } else if ((j == ballX && i >= ballY && i <= ballY + BALL_SIZE)) { printf("O"); } else { printf(" "); } } printf("\n"); } printf("Score\n"); printf("-----\n"); printf("Player 1: %d\n", paddle1Y); printf("Player 2: %d\n", paddle2Y); } int main() { while (!gameover) { draw(); moveBall(); if (_kbhit()) { switch (_getch()) { case 'w': movePaddle1Up(); break; case 's': movePaddle1Down(); break; case 'i': movePaddle2Up(); break; case 'k': movePaddle2Down(); break; case 'x': gameover = 1; break; } } Sleep(10); } return 0; }