code a ping pong game
- User
code a ping pong game
- Assistant
code a ping pong game
Sure! Let's create a simple Ping Pong (Pong) game using Python and the pygame library. This game will feature two paddles, a ball that bounces between them, and basic scoring.
Python Installation: Ensure you have Python installed on your system. You can download it from python.org.
Pygame Installation: Install the pygame library, which is a popular Python library for creating games.
You can install it using pip:
pip install pygame
Below is the complete Python code for the Pong game using pygame:
import pygame
import sys
import random
# Initialize pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Paddle properties
PADDLE_WIDTH, PADDLE_HEIGHT = 10, 100
PADDLE_SPEED = 7
# Ball properties
BALL_SIZE = 20
BALL_SPEED_X = 5
BALL_SPEED_Y = 5
# Fonts
SCORE_FONT = pygame.font.SysFont("comicsans", 50)
# Set up the screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ping Pong Game")
# Clock
clock = pygame.time.Clock()
FPS = 60
# Define the Paddle class
class Paddle:
def __init__(self, x, y):
self.rect = pygame.Rect(x, y, PADDLE_WIDTH, PADDLE_HEIGHT)
self.speed = PADDLE_SPEED
def move_up(self):
if self.rect.top > 0:
self.rect.y -= self.speed
def move_down(self):
if self.rect.bottom < HEIGHT:
self.rect.y += self.speed
def draw(self, surface):
pygame.draw.rect(surface, WHITE, self.rect)
# Define the Ball class
class Ball:
def __init__(self, x, y):
self.rect = pygame.Rect(x, y, BALL_SIZE, BALL_SIZE)
self.speed_x = BALL_SPEED_X * random.choice((1, -1))
self.speed_y = BALL_SPEED_Y * random.choice((1, -1))
def move(self):
self.rect.x += self.speed_x
self.rect.y += self.speed_y
# Collision with top or bottom
if self.rect.top <= 0 or self.rect.bottom >= HEIGHT:
self.speed_y *= -1
def reset(self):
self.rect.center = (WIDTH // 2, HEIGHT // 2)
self.speed_x *= random.choice((1, -1))
self.speed_y *= random.choice((1, -1))
def draw(self, surface):
pygame.draw.ellipse(surface, WHITE, self.rect)
# Initialize paddles and ball
left_paddle = Paddle(30, HEIGHT // 2 - PADDLE_HEIGHT // 2)
right_paddle = Paddle(WIDTH - 30 - PADDLE_WIDTH, HEIGHT // 2 - PADDLE_HEIGHT // 2)
ball = Ball(WIDTH // 2 - BALL_SIZE // 2, HEIGHT // 2 - BALL_SIZE // 2)
# Scores
left_score = 0
right_score = 0
def draw():
screen.fill(BLACK)
# Draw paddles and ball
left_paddle.draw(screen)
right_paddle.draw(screen)
ball.draw(screen)
# Draw the center line
for i in range(10, HEIGHT, HEIGHT // 20):
if i % 2 == 0:
pygame.draw.rect(screen, WHITE, (WIDTH//2 - 5, i, 10, HEIGHT//20))
# Draw scores
score_text = SCORE_FONT.render(f"{left_score} : {right_score}", True, WHITE)
screen.blit(score_text, (WIDTH//2 - score_text.get_width()//2, 20))
pygame.display.flip()
def handle_collision():
global left_score, right_score
# Collision with left paddle
if ball.rect.colliderect(left_paddle.rect):
ball.speed_x *= -1
ball.rect.left = left_paddle.rect.right
# Collision with right paddle
if ball.rect.colliderect(right_paddle.rect):
ball.speed_x *= -1
ball.rect.right = right_paddle.rect.left
# Check for scoring
if ball.rect.left <= 0:
right_score += 1
ball.reset()
if ball.rect.right >= WIDTH:
left_score += 1
ball.reset()
def main():
global left_score, right_score
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Handle key presses
keys = pygame.key.get_pressed()
# Left paddle controls (W and S)
if keys[pygame.K_w]:
left_paddle.move_up()
if keys[pygame.K_s]:
left_paddle.move_down()
# Right paddle controls (Up and Down arrows)
if keys[pygame.K_UP]:
right_paddle.move_up()
if keys[pygame.K_DOWN]:
right_paddle.move_down()
# Move the ball
ball.move()
# Handle collisions
handle_collision()
# Draw everything
draw()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Initialization:
pygame, set up the display window, define colors, paddle and ball properties, and set up the frame rate.Paddle Class:
draw method to render itself on the screen.Ball Class:
draw method to render itself on the screen.Drawing Function (draw):
Collision Handling (handle_collision):
Main Game Loop (main):
W (up) and S (down).Up and Down arrow keys.Save the Code: Copy the code into a file named pong.py.
Run the Game:
Open your terminal or command prompt, navigate to the directory containing pong.py, and run:
python pong.py
Controls:
WSUp Arrow keyDown Arrow keyExit: Close the game window or press Ctrl+C in the terminal to exit.
Once you have the basic game running, you can consider adding the following features to enhance it:
Feel free to experiment and make the game your own! If you have any questions or need further assistance, feel free to ask.
Not yet included in a published release.