-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPong.py
More file actions
91 lines (73 loc) · 2.52 KB
/
Pong.py
File metadata and controls
91 lines (73 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import pygame
import random
# Initialize Pygame
pygame.init()
# Set up the game window
width = 800
height = 400
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("Ping Pong")
# Set up the colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Set up the paddles
paddle_width = 10
paddle_height = 60
paddle_speed = 5
left_paddle_pos = pygame.Rect(50, height // 2 - paddle_height // 2, paddle_width, paddle_height)
right_paddle_pos = pygame.Rect(width - 50 - paddle_width, height // 2 - paddle_height // 2, paddle_width, paddle_height)
# Set up the ball
ball_radius = 10
ball_speed_x = 3
ball_speed_y = 3
ball_pos = pygame.Rect(width // 2 - ball_radius // 2, height // 2 - ball_radius // 2, ball_radius, ball_radius)
ball_direction = random.choice([-1, 1])
# Set up the game clock
clock = pygame.time.Clock()
# Game loop
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Move the paddles
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and left_paddle_pos.y > 0:
left_paddle_pos.y -= paddle_speed
if keys[pygame.K_s] and left_paddle_pos.y < height - paddle_height:
left_paddle_pos.y += paddle_speed
if keys[pygame.K_UP] and right_paddle_pos.y > 0:
right_paddle_pos.y -= paddle_speed
if keys[pygame.K_DOWN] and right_paddle_pos.y < height - paddle_height:
right_paddle_pos.y += paddle_speed
# Move the ball
ball_pos.x += ball_speed_x * ball_direction
ball_pos.y += ball_speed_y
# Check for collisions with paddles
if ball_pos.colliderect(left_paddle_pos) or ball_pos.colliderect(right_paddle_pos):
ball_direction *= -1
# Check for collisions with walls
if ball_pos.y <= 0 or ball_pos.y >= height - ball_radius:
ball_speed_y *= -1
# Check for scoring
if ball_pos.x <= 0 or ball_pos.x >= width - ball_radius:
# Reset ball position
ball_pos.x = width // 2 - ball_radius // 2
ball_pos.y = height // 2 - ball_radius // 2
# Reset ball speed
ball_speed_x = 3
ball_speed_y = 3
ball_direction = random.choice([-1, 1])
# Clear the window
window.fill(BLACK)
# Draw the paddles and ball
pygame.draw.rect(window, WHITE, left_paddle_pos)
pygame.draw.rect(window, WHITE, right_paddle_pos)
pygame.draw.ellipse(window, WHITE, ball_pos)
# Update the window
pygame.display.update()
# Set the frame rate
clock.tick(60)
# Quit the game
pygame.quit()