Python: Sample Pong game

Return to Python resources

import pygame, time, random
from pygame.locals import *

pygame.init()
window = pygame.display.set_mode((500,500))
fps = pygame.time.Clock()

# Declare colors
BLACK = (0,0,0)
WHITE = (255,255,255)

# Variables needed for keeping track of positions
ball_x = 250
ball_y = 250
ball_move_x = random.randint(-10,10)
ball_move_y = random.randint(-10,10)
paddle_x = 220
paddle_y = 470
paddle_move_x = 0
paddle_move_y = 0

# Game will end when this is set to True
quit = False

# Main game loop
while not quit:

    # Process events
    for event in pygame.event.get():
        print(event)
        if event.type == QUIT:
            quit = True
        elif event.type == KEYDOWN:
            if event.key == K_LEFT:
                paddle_move_x = -20
            elif event.key == K_RIGHT:
                paddle_move_x = 20
            elif event.key == K_ESCAPE:
                quit = True
            elif event.key == K_SPACE:
                ball_x = 250
                ball_y = 250
                ball_move_x = random.randint(5,10)
                ball_move_y = random.randint(5,10)
        elif event.type == KEYUP:
            if event.key == K_LEFT or event.key == K_RIGHT:
                paddle_move_x = 0

    # Perform calculations
    ball_x = ball_x + ball_move_x
    ball_y = ball_y + ball_move_y
    if ball_x < 0:
        ball_move_x = -ball_move_x
    if ball_x > 500:
        ball_move_x = -ball_move_x
    if ball_y < 0:
        ball_move_y = -ball_move_y
    if ball_y > 500:
        ball_x = 250
        ball_y = 250
        ball_move_x = 0
        ball_move_y = 0

    paddle_x = paddle_x + paddle_move_x
    if paddle_x < 0:
        paddle_x = 0
    if paddle_x > 440:
        paddle_x = 440

    if Rect(paddle_x, paddle_y, 60, 20).colliderect(Rect(ball_x-5, ball_y-5,10,10)):
        ball_move_y = -abs(ball_move_y)
        ball_move_x = int(ball_move_x * 1.2)
        ball_move_y = int(ball_move_y * 1.2)

    # Draw graphics
    window.fill(BLACK)
    pygame.draw.circle(window, WHITE, (ball_x, ball_y), 10)
    pygame.draw.rect(window, WHITE, (paddle_x, paddle_y, 60, 20))
    pygame.display.update()
    fps.tick(25)

pygame.quit()