search
HomeBackend DevelopmentPython TutorialPing Pong game in Pygame python

Importing

import pygame
import sys

Pygame is the module we are using to make games. It provided us with tools for graphics, sound, and more.

sys is a module in Python that helps us interact with the Python interpreter.

Intializes

pygame.init()

Initializes all the Pygame modules and makes them ready to use.

Constants

#dimensions
WIDTH, HEIGHT=800,600
#frame rate
FPS=60
#the paddles at the side of ping pong
PADDLE_WIDTH, PADDLE_HEIGHT=15,90
#the balls radius
BALL_RADIUS=15
#the color of the ball and paddle
WHITE=(255, 255, 255)
  • WIDTH and HEIGHT: Dimensions of the game window. 800px is for the width and 600px is for the height
  • FPS: Frames per second, which controls the game’s speed and smoothness.
  • PADDLE_WIDTH, PADDLE_HEIGHT: Dimensions of the paddles.
  • BALL_RADIUS: Radius of the ball.
  • WHITE: The RGB value for white, is used for paddles, ball, and text.

Make a Screen

screen=pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Ping Pong")

you will have a window named Ping Pong with the assigned WIDTH and HEIGHT

Ping Pong game in Pygame python

Paddles and Ball setup

left_paddle=pygame.Rect(50, HEIGHT//2 - PADDLE_HEIGHT //2, PADDLE_WIDTH, PADDLE_HEIGHT)

right_paddle=pygame.Rect(WIDTH - 50 - PADDLE_WIDTH, HEIGHT //2- PADDLE_HEIGHT //2, PADDLE_WIDTH, PADDLE_HEIGHT)

ball=pygame.Rect(WIDTH //2 - BALL_RADIUS, HEIGHT //2 - BALL_RADIUS, BALL_RADUIS *2, BALL_RADIUS *2)

Ping Pong game in Pygame python

In Pygame the left top corner of the screen represents (0,0) in coordinates.

  • pygame.Rect: Is used to create rectangles in pygame(used here for the paddles and the ball).
pygame.Rect(x, y, width, height)
  • left_paddle: Positioned near the left side of the screen, vertically centered.
pygame.Rect(50, HEIGHT//2 - PADDLE_HEIGHT //2, PADDLE_WIDTH, PADDLE_HEIGHT)
  1. First, we position the left paddle 50px towards the right from the left side.

  2. Then we do HEIGHT//2 - PADDLE_HEIGHT //2 because if you just did HEIGHT//2 it will look like the way it is in the picture. It goes down the screen. To center it we do - PADDLE_HEIGHT //2

Ping Pong game in Pygame python

This is what we did for the right paddle to center it.

  • right_paddle: Positioned near the right side of the screen, vertically centered.
right_paddle=pygame.Rect(WIDTH - 50 - PADDLE_WIDTH, HEIGHT //2- PADDLE_HEIGHT //2, PADDLE_WIDTH, PADDLE_HEIGHT)
  • ball: Initially positioned in the center of the screen.
ball=pygame.Rect(WIDTH //2 - BALL_RADIUS, HEIGHT //2 - BALL_RADIUS, BALL_RADUIS *2, BALL_RADIUS *2)

For the ball to center it, we subtracted by the radius.

Speed

ball_speed_x=7
ball_speed_y=7
paddle_speed=10

ball_speed_x and ball_speed_y controls the horizontal and vertical speed of the ball.

paddle_speed: Controls the movement speed of the paddles.

Score Variables

import pygame
import sys
  • left_score and right_score: Track the scores of the players.
  • font: Used to render text on the screen for scores. None uses the default font, and 55 is the font size.

Function to draw everything

pygame.init()
  • fill((0, 0, 0)): Fills the screen with black (RGB: 0, 0, 0).
  • pygame.draw.rect: Draws the rectangular paddles.
  • pygame.draw.ellipse: Draws the ball as a circle (bounded by the rectangle ball).

Draw the center line

#dimensions
WIDTH, HEIGHT=800,600
#frame rate
FPS=60
#the paddles at the side of ping pong
PADDLE_WIDTH, PADDLE_HEIGHT=15,90
#the balls radius
BALL_RADIUS=15
#the color of the ball and paddle
WHITE=(255, 255, 255)
  • Draws a vertical center line to divide the playing field.

Draw Scores

screen=pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Ping Pong")

Renders the scores for both players and positions them on the screen.

Update the screen

left_paddle=pygame.Rect(50, HEIGHT//2 - PADDLE_HEIGHT //2, PADDLE_WIDTH, PADDLE_HEIGHT)

right_paddle=pygame.Rect(WIDTH - 50 - PADDLE_WIDTH, HEIGHT //2- PADDLE_HEIGHT //2, PADDLE_WIDTH, PADDLE_HEIGHT)

ball=pygame.Rect(WIDTH //2 - BALL_RADIUS, HEIGHT //2 - BALL_RADIUS, BALL_RADUIS *2, BALL_RADIUS *2)

Updates the display with the latest changes.

pygame.Rect(x, y, width, height)

Keeps the game running indefinitely.

pygame.Rect(50, HEIGHT//2 - PADDLE_HEIGHT //2, PADDLE_WIDTH, PADDLE_HEIGHT)

This will go through all the events that can happen in pygame and if one of them is closing the window then quit pygame and close the window.

Paddle Controls

right_paddle=pygame.Rect(WIDTH - 50 - PADDLE_WIDTH, HEIGHT //2- PADDLE_HEIGHT //2, PADDLE_WIDTH, PADDLE_HEIGHT)

Detects key presses:

  • W and S: Move the left paddle up and down.
    • pygame.K_w is the w key
    • pygame.K_s is the s key
  • UP and DOWN: Move the right paddle up and down.
    • pygame.K_UP is the up key
    • pygame.K_DOWN is the down key
  • Includes checks to prevent paddles from moving off the screen.
    • left_paddle.top > 0checks to see if top of paddles coordinates is greater than 0. To check to see if it is hitting the top of the screen when you click W.
    • left_paddle.bottom
    • right_paddle.top > 0checks to see if top of paddles coordinates is greater than 0. To check to see if it is hitting the top of the screen when you click Up key.
    • right_paddle.bottom

Ball movement

ball=pygame.Rect(WIDTH //2 - BALL_RADIUS, HEIGHT //2 - BALL_RADIUS, BALL_RADUIS *2, BALL_RADIUS *2)

Moves the ball by adding its speed to its current position

Ball collision with top and bottom walls

ball_speed_x=7
ball_speed_y=7
paddle_speed=10

Reverses the ball's vertical direction if it hits the top or bottom of the screen

Ball collision with paddles

import pygame
import sys

Reverses the ball's horizontal direction if it collides with a paddle.

Scoring

pygame.init()
  • Updates the score if the ball goes out of bounds.
  • Resets the ball to the center and reverses its direction.

Timing

#dimensions
WIDTH, HEIGHT=800,600
#frame rate
FPS=60
#the paddles at the side of ping pong
PADDLE_WIDTH, PADDLE_HEIGHT=15,90
#the balls radius
BALL_RADIUS=15
#the color of the ball and paddle
WHITE=(255, 255, 255)

Limits the game to run at a maximum of 60 frames per second, ensuring smooth gameplay.

Full code

screen=pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Ping Pong")

Ping Pong game in Pygame python

The above is the detailed content of Ping Pong game in Pygame python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python's Execution Model: Compiled, Interpreted, or Both?Python's Execution Model: Compiled, Interpreted, or Both?May 10, 2025 am 12:04 AM

Pythonisbothcompiledandinterpreted.WhenyourunaPythonscript,itisfirstcompiledintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).Thishybridapproachallowsforplatform-independentcodebutcanbeslowerthannativemachinecodeexecution.

Is Python executed line by line?Is Python executed line by line?May 10, 2025 am 12:03 AM

Python is not strictly line-by-line execution, but is optimized and conditional execution based on the interpreter mechanism. The interpreter converts the code to bytecode, executed by the PVM, and may precompile constant expressions or optimize loops. Understanding these mechanisms helps optimize code and improve efficiency.

What are the alternatives to concatenate two lists in Python?What are the alternatives to concatenate two lists in Python?May 09, 2025 am 12:16 AM

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

Python: Efficient Ways to Merge Two ListsPython: Efficient Ways to Merge Two ListsMay 09, 2025 am 12:15 AM

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiled vs Interpreted Languages: pros and consCompiled vs Interpreted Languages: pros and consMay 09, 2025 am 12:06 AM

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

Python: For and While Loops, the most complete guidePython: For and While Loops, the most complete guideMay 09, 2025 am 12:05 AM

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

Python concatenate lists into a stringPython concatenate lists into a stringMay 09, 2025 am 12:02 AM

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment