-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpong_game.py
76 lines (60 loc) · 2.46 KB
/
pong_game.py
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
#
import pygame
import sys
pygame.init()
WIDTH, HEIGHT = 600, 400
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BALL_SPEED = 5
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong Game")
ball_x, ball_y = WIDTH // 2, HEIGHT // 2
ball_speed_x, ball_speed_y = BALL_SPEED, BALL_SPEED
paddle_width, paddle_height = 15, 60
left_paddle_x, right_paddle_x = 10, WIDTH - 25
left_paddle_y, right_paddle_y = HEIGHT // 2 - paddle_height // 2, HEIGHT // 2 - paddle_height // 2
paddle_speed = 7
score_left, score_right = 0, 0
# Font for display
font = pygame.font.Font(None, 35)
def reset_ball():
return WIDTH // 2, HEIGHT // 2, BALL_SPEED, BALL_SPEED
# Game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and left_paddle_y > 0:
left_paddle_y -= paddle_speed
if keys[pygame.K_s] and left_paddle_y < HEIGHT - paddle_height:
left_paddle_y += paddle_speed
if keys[pygame.K_UP] and right_paddle_y > 0:
right_paddle_y -= paddle_speed
if keys[pygame.K_DOWN] and right_paddle_y < HEIGHT - paddle_height:
right_paddle_y += paddle_speed
ball_x += ball_speed_x
ball_y += ball_speed_y
if (left_paddle_x < ball_x < left_paddle_x + paddle_width and
left_paddle_y < ball_y < left_paddle_y + paddle_height) or \
(right_paddle_x < ball_x < right_paddle_x + paddle_width and
right_paddle_y < ball_y < right_paddle_y + paddle_height):
ball_speed_x = -ball_speed_x
if ball_y <= 0 or ball_y >= HEIGHT:
ball_speed_y = -ball_speed_y
if ball_x <= 0:
score_right += 1
ball_x, ball_y, ball_speed_x, ball_speed_y = reset_ball()
if ball_x >= WIDTH:
score_left += 1
ball_x, ball_y, ball_speed_x, ball_speed_y = reset_ball()
# Drawing the screen
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE, (left_paddle_x, left_paddle_y, paddle_width, paddle_height))
pygame.draw.rect(screen, WHITE, (right_paddle_x, right_paddle_y, paddle_width, paddle_height))
pygame.draw.ellipse(screen, WHITE, (ball_x - 10, ball_y - 10, 20, 20))
score_display = font.render("Score: {} - {}".format(score_left, score_right), True, WHITE)
screen.blit(score_display, (WIDTH // 2 - 40, 10))
pygame.display.flip()
pygame.time.Clock().tick(60)