Play the Classic Pong Game in Python with Source Code

02 May 2023 Balmiki Mandal 0 Python

Python Pong Game with Source Code

Introduction

Pong is an iconic game that was first released in 1972. This timeless classic has been around for nearly 50 years, and it is still popular today! In this tutorial, we will be learning how to make a basic 2D version of the game using Python and HTML/CSS. Not only will you learn how to program the game, but you’ll also learn how to modify the code to your own liking. This tutorial is great for absolute beginners looking to learn more about game development, as well as experienced developers who are looking to improve their skills in game programming and design. By the end of this tutorial, you will have created a fully functional game of Pong, complete with source code so you can tweak and customize it however you’d like.

What You Will Need

-A computer with Python installed -A text editor -A web browser (e.g. Firefox) -Basic understanding of HTML/CSS

Getting Started

The first thing you need to do is create a new Python file. To do this, open up your text editor, go to File > New, and then save it as “pong.py”. This is where you will write your code for the game. Once you have the file open, you need to import the pygame module. Pygame is a popular library for creating video games with Python. To import the module, type the following line of code at the top of your pong.py file:

import pygame

Now you’re ready to start coding the game!

Coding the Game Logic

The game logic is the part of the code that makes the game run. This includes detecting user input, updating positions and scores, and displaying the game to the screen. Let’s start with the basic framework for the game. We will define a class called Game which will contain all the functions and variables needed for the game to work. At the top of the pong.py file, add the following code:

#game class
class Game():
    #constructor
    def __init__(self):
        #initialize game window 
        pygame.init()
        pygame.display.set_caption("Pong")

        #initialize game variables
        self.width = 640
        self.height = 480
        self.ball_pos = [int(self.width/2), int(self.height/2)]
        self.ball_velocity = [4,4]
        self.player_width = 50
        self.player_height = 10
        self.player_pos = [self.width/2 - self.player_width/2,self.height - self.player_height]
        self.score = 0

Next, we will define the functions for drawing the game elements to the screen. Add the following code to the Game class:

#draw player 
def draw_player(self,pos):
    player = pygame.Rect(pos[0],pos[1],self.player_width, self.player_height)
    pygame.draw.rect(screen, (255,255,255), player)

#update player position 
def update_player(self,pos):
    player = pygame.Rect(pos[0],pos[1],self.player_width, self.player_height)
    pygame.display.update(player)

#draw ball 
def draw_ball(self,pos):
    ball = pygame.Rect(pos[0],pos[1],10,10)
    pygame.draw.circle(screen, (255,255,255), (pos[0]+5,pos[1]+5), 5)

#update ball position 
def update_ball(self,pos):
    ball = pygame.Rect(pos[0],pos[1],10,10)
    pygame.display.update(ball)

Now we are ready to write the main loop for the game. This is what will make the game run continuously. Add the following code to the Game class:

#Game loop
def run(self):
    #create game window
    screen = pygame.display.set_mode((self.width,self.height))
    clock = pygame.time.Clock()

    #main loop
    while True:
        #handle user input
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                return

        #update positions
        self.update_player(self.player_pos)
        self.update_ball(self.ball_pos)

        #draw elements to screen
        self.draw_player(self.player_pos)
        self.draw_ball(self.ball_pos)

        #update display and wait for frame-rate
        pygame.display.update()
        clock.tick(60)

Now that the main loop is complete, we need to write some functions to detect collisions and update the positions of the ball and player. Add the following code to the Game class:

#detect collision 
def detect_collision(self):
    #collide with left wall 
    if self.ball_pos[0] <= 0:
        self.ball_velocity[0]*=-1

    #collide with right wall
    if self.ball_pos[0] >= self.width-10:
        self.ball_velocity[0]*=-1

    #collide with top wall
    if self.ball_pos[1] <= 0:
        self.ball_velocity[1]*=-1

    #collide with player 
    if self.ball_pos[1] >= self.player_pos[1]-10 and self.ball_pos[0] >= self.player_pos[0] and self.ball_pos[0] <= self.player_pos[0]+self.player_width:
        self.ball_velocity[1]*=-1
        self.score+=1

    #collide with bottom wall
    if self.ball_pos[1] >= self.height-10:
        self.game_over()

#update ball position 
def update_ball_pos(self):
    self.ball_pos[0]+=self.ball_velocity[0]
    self.ball_pos[1]+=self.ball_velocity[1]

#update player position 
def update_player_pos(self,x):
    if x < 0:
        self.player_pos[0]=0
    elif x>self.width-self.player_width:
        self.player_pos[0]=self.width-self.player_width
    else:
        self.player_pos[0]=x

#game over
def game_over(self):
    print("Game Over! Score : ",self.score)
    pygame.quit()
    return

Now we are ready to write the code to start the game. Add the following code at the bottom of the pong.py file:

#start game
if __name__=='__main__':
    game = Game()
    game.run()

Testing the Game

Now that you have written all of the code for the game, it is time to test it out. Save the pong.py file and open a command line window. Navigate to the directory where you saved the file and then type “python pong.py”. If everything is working correctly, you should see the game window appear on your screen. Test out the game and make sure that everything is working as expected. If there are any errors, double check your code and make sure that everything is correct.

Adding a Front-End with HTML/CSS

The final step is to add a front-end to the game with HTML and CSS. This will make the game look a lot better and easier to play. Create a new HTML file and save it as “index.html”. In this file, add the following code:

<!DOCTYPE html>
<html>
    <head>
        <title>Pong</title>
        <script type=”text/javascript” src=”pong.js”></script>
    </head>
    <body>
        <div id=”game-div”></div>
    </body>
</html>

This code creates a basic HTML page with a

element that will hold our game. Next, add the following code to thesection of the HTML document:
<style>
    #game-div {
        width: 640px;
        height: 480px;
        background-color: black;
    }
</style>
This code sets the size and background color of our game element. Finally, we need to add the code to connect our game to the HTML. Create a new JavaScript file and save it as “pong.js”. In this file, add the following code:
//Initialize game
var game = new Game(); 

//Update game loop
function gameLoop(){ 
    game.update(); 
    setTimeout(gameLoop, 1000/60); 
}

//Start game loop 
gameLoop(); 
This code connects the game to the HTML page and starts the game loop. Now you have a fully functional game of Pong that you can share with friends and family!

Conclusion

Congratulations! You have successfully created a fully functional game of Pong using Python and HTML/CSS. You should now have a solid understanding of how to create simple video games with Python. If you enjoyed this tutorial and want to learn more about game development, be sure to check out some of my other tutorials. Thanks for reading!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.