How do I code pong in python.
- User
How do I code pong in python.
- Assistant
Here is a code for Pong game in Python using Pygame library:
import pygame import random
Initialize the game
pygame.init()
Set screen width and height
screen_width = 700 screen_height = 500
Set screen color
screen_color = (255, 255, 255)
Set ball color
ball_color = (255, 0, 0)
Set ball radius
ball_radius = 20
Set ball speed
ball_speed = [2, 2]
Set paddle color
paddle_color = (0, 0, 255)
Set paddle width and height
paddle_width = 20 paddle_height = 80
Set paddle speed
paddle_speed = 5
Set score color
score_color = (0, 0, 0)
Set font size
font_size = 30
Set screen
screen = pygame.display.set_mode((screen_width, screen_height))
Set title
pygame.display.set_caption("Pong")
Load font
font = pygame.font.Font(None, font_size)
Initialize clock
clock = pygame.time.Clock()
Initialize score
score = 0
Initialize ball
ball = pygame.draw.circle(screen, ball_color, (screen_width//2, screen_height//2), ball_radius)
Initialize paddle
paddle = pygame.draw.rect(screen, paddle_color, (screen_width-paddle_width, screen_height//2, paddle_width, paddle_height))
Function to draw ball
def draw_ball(screen, color, pos, radius): x, y = pos pygame.draw.circle(screen, color, (int(x), int(y)), int(radius))
Function to draw paddle
def draw_paddle(screen, color, pos, width, height): x, y = pos pygame.draw.rect(screen, color, (x, y, width, height))
Function to draw score
def draw_score(screen, font, pos, text, color): text = font.render(text, True, color) screen.blit(text, pos)
Game loop
running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False
# Move ball ball.x += ball_speed[0] ball.y += ball_speed[1] # Check for ball collision with walls if ball.y <= ball_radius or ball.y >= screen_height-ball_radius: ball_speed[1] = -ball_speed[1] if ball.x <= ball_radius: ball_speed[0] = -ball_speed[0] score += 1 # Check for ball collision with paddle if ball.x >= screen_width-paddle_width-ball_radius and paddle.y < ball.y < paddle.y+paddle_height: ball_speed[0] = -ball_speed[0] # Move paddle keys = pygame.key.get_pressed()if keys[pygame.K_UP]: paddle.y -= paddle_speed if keys[pygame.K_DOWN]: paddle.y += paddle_speed
Check for paddle collision with walls
if paddle.y <= 0: paddle.y = 0 if paddle.y >= screen_height-paddle_height: paddle.y = screen_height-paddle_height
Clear screen
screen.fill(screen_color)
Draw ball
draw_ball(screen, ball_color, [ball.x, ball.y], ball_radius)
Draw paddle
draw_paddle(screen, paddle_color, [paddle.x, paddle.y], paddle_width, paddle_height)
Draw score
draw_score(screen, font, (screen_width//2, screen_height//4), str(score), score_color)
Update screen
pygame.display.update()
Set clock speed
clock.tick(60)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.