create a python game using pygame.... the game will be a ping pong game where i will be playing against computer and it should be in windowed mode .. the game should have accurate graphics and physics and dynamics. make a stunning game.
Assistant
Creating a visually appealing and dynamically accurate Ping Pong game using Pygame involves several components, including game initialization, rendering, handling user input, implementing game physics, and managing the computer opponent's behavior. Below is a complete Python script using Pygame that fulfills your requirements. This script provides a windowed Ping Pong game where you play against the computer with smooth graphics and physics.
Prerequisites
Python Installation: Ensure you have Python installed (preferably Python 3.6 or higher).
Pygame Installation: Install Pygame library if you haven't already. You can install it using pip:
bash
pip install pygame
Complete Python Ping Pong Game Using Pygame
python
import pygame
import sys
import random
import math
# Initialize Pygame
pygame.init()
# ------------------------------
# Constants and Configuration
# ------------------------------
WIDTH, HEIGHT = 800, 600
FPS = 60
# Colors
WHITE = (255, 255, 255)
LIGHT_GRAY = (200, 200, 200)
DARK_GRAY = (50, 50, 50)
RED = (255, 50, 50)
BLUE = (50, 50, 255)
GREEN = (50, 255, 50)
# Paddle settings
PADDLE_WIDTH, PADDLE_HEIGHT = 10, 100
PADDLE_SPEED = 7
# Ball settings
BALL_RADIUS = 10
BALL_SPEED = 5
# Fonts
SCORE_FONT = pygame.font.SysFont("comicsans", 40)
WIN_FONT = pygame.font.SysFont("comicsans", 60)
# Screen setup
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ping Pong Game")
clock = pygame.time.Clock()
# ------------------------------
# Game Objects
# ------------------------------
class Paddle:
def __init__(self, x, y, width, height, speed, is_player=True):
self.x = x
self.y = y
self.width = width
self.height = height
self.speed = speed
self.is_player = is_player
self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
def move(self, up=True):
if up:
self.y -= self.speed
else:
self.y += self.speed
# Keep paddle on the screen
if self.y < 0:
self.y = 0
if self.y + self.height > HEIGHT:
self.y = HEIGHT - self.height
self.rect.y = self.y
def auto_move(self, ball):
# Simple AI to follow the ball with some delay
if ball.y < self.y + self.height / 2:
self.move(up=True)
elif ball.y > self.y + self.height / 2:
self.move(up=False)
def draw(self, surface):
pygame.draw.rect(surface, WHITE, self.rect)
class Ball:
def __init__(self, x, y, radius, speed):
self.x = x
self.y = y
self.radius = radius
angle = random.uniform(-math.pi / 4, math.pi / 4)
self.speed_x = speed * math.cos(angle) * random.choice([-1, 1])
self.speed_y = speed * math.sin(angle) * random.choice([-1, 1])
self.speed = speed
def reset(self):
self.x = WIDTH // 2
self.y = HEIGHT // 2
angle = random.uniform(-math.pi / 4, math.pi / 4)
self.speed_x = self.speed * math.cos(angle) * random.choice([-1, 1])
self.speed_y = self.speed * math.sin(angle) * random.choice([-1, 1])
def move(self):
self.x += self.speed_x
self.y += self.speed_y
# Collision with top and bottom
if self.y - self.radius <= 0 or self.y + self.radius >= HEIGHT:
self.speed_y *= -1
# Collision with paddles is handled outside
def draw(self, surface):
pygame.draw.circle(surface, WHITE, (int(self.x), int(self.y)), self.radius)
def collide(self, paddle):
# Check collision with a paddle
if self.speed_x < 0:
if paddle.rect.right >= self.x - self.radius >= paddle.rect.left:
if paddle.y <= self.y <= paddle.y + paddle.height:
self.speed_x *= -1
self.increase_speed()
else:
if paddle.rect.left <= self.x + self.radius <= paddle.rect.right:
if paddle.y <= self.y <= paddle.y + paddle.height:
self.speed_x *= -1
self.increase_speed()
def increase_speed(self):
# Increase speed slightly after each paddle hit
self.speed_x *= 1.05
self.speed_y *= 1.05
# ------------------------------
# Game Functions
# ------------------------------
def draw(screen, paddles, ball, scores):
screen.fill(DARK_GRAY)
# Draw middle line
pygame.draw.aaline(screen, LIGHT_GRAY, (WIDTH//2, 0), (WIDTH//2, HEIGHT))
# Draw paddles and ball
for paddle in paddles:
paddle.draw(screen)
ball.draw(screen)
# Draw scores
score_text = SCORE_FONT.render(f"{scores['player']} {scores['computer']}", True, WHITE)
screen.blit(score_text, (WIDTH//2 - score_text.get_width()//2, 20))
pygame.display.flip()
def handle_collision(ball, paddles):
# Left paddle (player)
ball.collide(paddles[0])
# Right paddle (computer)
ball.collide(paddles[1])
def display_winner(screen, text):
win_text = WIN_FONT.render(text, True, GREEN)
screen.blit(win_text, (WIDTH//2 - win_text.get_width()//2, HEIGHT//2 - win_text.get_height()//2))
pygame.display.flip()
pygame.time.delay(3000)
# ------------------------------
# Main Game Loop
# ------------------------------
def main():
run = True
player = Paddle(20, HEIGHT//2 - PADDLE_HEIGHT//2, PADDLE_WIDTH, PADDLE_HEIGHT, PADDLE_SPEED, is_player=True)
computer = Paddle(WIDTH - 20 - PADDLE_WIDTH, HEIGHT//2 - PADDLE_HEIGHT//2, PADDLE_WIDTH, PADDLE_HEIGHT, PADDLE_SPEED * 0.8, is_player=False)
ball = Ball(WIDTH//2, HEIGHT//2, BALL_RADIUS, BALL_SPEED)
paddles = [player, computer]
scores = {"player": 0, "computer": 0}
WIN_SCORE = 10
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
sys.exit()
# Key presses
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and player.y > 0:
player.move(up=True)
if keys[pygame.K_s] and player.y + player.height < HEIGHT:
player.move(up=False)
# Computer paddle movement
computer.auto_move(ball)
# Move ball
ball.move()
# Handle collisions
handle_collision(ball, paddles)
# Check for scoring
if ball.x < 0:
scores['computer'] += 1
ball.reset()
elif ball.x > WIDTH:
scores['player'] += 1
ball.reset()
# Check for winner
if scores['player'] >= WIN_SCORE:
display_winner(screen, "You Win!")
run = False
elif scores['computer'] >= WIN_SCORE:
display_winner(screen, "Computer Wins!")
run = False
# Draw everything
draw(screen, paddles, ball, scores)
main_menu()
def main_menu():
while True:
screen.fill(DARK_GRAY)
title = WIN_FONT.render("Ping Pong Game", True, BLUE)
instructions = SCORE_FONT.render("Press SPACE to Play", True, WHITE)
screen.blit(title, (WIDTH//2 - title.get_width()//2, HEIGHT//3 - title.get_height()//2))
screen.blit(instructions, (WIDTH//2 - instructions.get_width()//2, HEIGHT//2))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
main()
if __name__ == "__main__":
main_menu()
Features of the Game
Player vs Computer: You control the left paddle using W (up) and S (down) keys. The computer controls the right paddle with basic AI.
Accurate Physics:
The ball bounces off the top and bottom edges.
The ball's speed increases slightly each time it hits a paddle, making the game progressively challenging.
Scoring System:
First to reach 10 points wins.
The score is displayed at the top center of the screen.
Graphics:
Clean and simple design with a dark background.
Middle dividing line for better visual separation.
Smooth paddle and ball movement.
Main Menu:
A simple main menu where you can start the game by pressing the SPACE bar.
How to Play
Start the Game:
Run the script. You'll see the main menu with the title "Ping Pong Game" and instructions to press SPACE to play.
Control the Paddle:
Use the W key to move the left paddle up.
Use the S key to move the left paddle down.
Objective:
Hit the ball past the computer's paddle to score points.
Prevent the ball from passing your paddle to avoid giving points to the computer.
Winning the Game:
The game ends when either the player or the computer reaches 10 points.
A message will display the winner, and the game will return to the main menu after a short delay.
Customization
Feel free to customize the game further to make it more "stunning" by:
Adding Sound Effects: Incorporate sounds for paddle hits, scoring, and game over events.
Enhancing Graphics: Use images or more advanced drawing techniques for paddles and the ball.
Improving AI: Make the computer opponent smarter by adjusting its reaction time or movement speed.
Adding Features: Implement power-ups, different ball types, or multiplayer support.
Running the Game
Save the script to a file named, for example, ping_pong.py, and run it using the following command: