simulate pong in python

To simulate pong in python, we can use the pygame module which provides us with the necessary tools to create a game window, handle input events, and draw shapes on the screen.

Here's a basic code example that simulates a two-player Pong game using pygame:

main.py
import pygame

# Initialize pygame
pygame.init()

# Set up the game window
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Pong")

# Set up the players and ball
player1_rect = pygame.Rect(50, window_height // 2 - 50, 20, 100)
player2_rect = pygame.Rect(window_width - 50 - 20, window_height // 2 - 50, 20, 100)
ball_rect = pygame.Rect(window_width // 2 - 10, window_height // 2 - 10, 20, 20)
ball_speed = [5, 5]

# Set up the game loop
while True:
    # Handle input events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    # Move the ball
    ball_rect.move_ip(ball_speed)

    # Check for collisions with players or walls
    if ball_rect.colliderect(player1_rect) or ball_rect.colliderect(player2_rect):
        ball_speed[0] *= -1
    if ball_rect.top < 0 or ball_rect.bottom > window_height:
        ball_speed[1] *= -1

    # Draw the game objects
    window.fill((0, 0, 0))  # fill the window with black
    pygame.draw.rect(window, (255, 255, 255), player1_rect)  # draw player 1
    pygame.draw.rect(window, (255, 255, 255), player2_rect)  # draw player 2
    pygame.draw.ellipse(window, (255, 255, 255), ball_rect)  # draw the ball

    # Update the game window
    pygame.display.update()
1358 chars
43 lines

This code sets up a game window, two players represented as rectangles, and a ball represented as an ellipse. The ball moves at a constant speed and bounces off the players and the walls.

To play the game, the player can move their respective player up and down with the w, s, up arrow and down arrow keys. The actual implementation for player movement and scoring can be left as an exercise for the reader.

gistlibby LogSnag