"""Pong - a Pygame.net game project. Classic paddle tennis against a computer opponent. First to 7 points wins. Where the ball meets your paddle decides its rebound angle. Run it: pip install pygame-ce (or: pip install pygame) python pong.py Controls: Up/Down or W/S to move, Space to serve or restart. License: MIT - https://pygame.net/licenses/ """ import asyncio import math import random import pygame WIDTH, HEIGHT = 640, 480 FPS = 60 PADDLE_W, PADDLE_H = 12, 80 BALL = 12 WIN_SCORE = 7 BG = (16, 26, 48) LINE = (44, 62, 100) WHITE = (230, 236, 247) YELLOW = (244, 197, 49) BLUE = (91, 147, 230) class Paddle: def __init__(self, x, color): self.rect = pygame.Rect(0, 0, PADDLE_W, PADDLE_H) self.rect.center = (x, HEIGHT // 2) self.color = color self.y = float(self.rect.y) def move(self, dy): self.y = max(0, min(HEIGHT - PADDLE_H, self.y + dy)) self.rect.y = round(self.y) class Ball: def __init__(self): self.rect = pygame.Rect(0, 0, BALL, BALL) self.reset(direction=1) def reset(self, direction): self.pos = pygame.Vector2(WIDTH / 2, HEIGHT / 2) self.vel = pygame.Vector2(0, 0) self.direction = direction self.rect.center = (round(self.pos.x), round(self.pos.y)) def serve(self, rng): angle = rng.uniform(-0.6, 0.6) speed = 320 self.vel = pygame.Vector2(math.cos(angle) * speed * self.direction, math.sin(angle) * speed) @property def moving(self): return self.vel.length_squared() > 0 class Game: def __init__(self, seed=None): self.rng = random.Random(seed) self.font = pygame.font.Font(None, 72) self.small = pygame.font.Font(None, 28) self.player = Paddle(30, BLUE) self.cpu = Paddle(WIDTH - 30, YELLOW) self.ball = Ball() self.scores = [0, 0] self.winner = None self.cpu_speed = 260 def handle_event(self, event): if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: if self.winner is not None: self.__init__() elif not self.ball.moving: self.ball.serve(self.rng) elif event.type == pygame.MOUSEBUTTONDOWN and not self.ball.moving and self.winner is None: self.ball.serve(self.rng) def update(self, dt, keys=None): if keys is None: keys = pygame.key.get_pressed() speed = 360 * dt if keys[pygame.K_UP] or keys[pygame.K_w]: self.player.move(-speed) if keys[pygame.K_DOWN] or keys[pygame.K_s]: self.player.move(speed) # Computer: follows the ball with a speed limit and a small dead zone. target = self.ball.pos.y if self.ball.vel.x > 0 else HEIGHT / 2 diff = target - self.cpu.rect.centery if abs(diff) > 10: self.cpu.move(max(-self.cpu_speed * dt, min(self.cpu_speed * dt, diff))) if not self.ball.moving or self.winner is not None: return b = self.ball b.pos += b.vel * dt b.rect.center = (round(b.pos.x), round(b.pos.y)) if b.rect.top <= 0 and b.vel.y < 0 or b.rect.bottom >= HEIGHT and b.vel.y > 0: b.vel.y *= -1 for paddle, side in ((self.player, 1), (self.cpu, -1)): if b.rect.colliderect(paddle.rect) and b.vel.x * side < 0: # -1 at the top edge, +1 at the bottom edge of the paddle offset = (b.rect.centery - paddle.rect.centery) / (PADDLE_H / 2) offset = max(-1.0, min(1.0, offset)) speed = min(b.vel.length() * 1.06, 760) angle = offset * math.radians(55) b.vel = pygame.Vector2(math.cos(angle) * speed * side, math.sin(angle) * speed) if side == 1: b.rect.left = paddle.rect.right else: b.rect.right = paddle.rect.left b.pos.x = b.rect.centerx if b.rect.right < 0: self.point(1) elif b.rect.left > WIDTH: self.point(0) def point(self, who): self.scores[who] += 1 if self.scores[who] >= WIN_SCORE: self.winner = who self.ball.reset(direction=-1 if who == 0 else 1) def draw(self, surface): surface.fill(BG) for y in range(0, HEIGHT, 24): pygame.draw.rect(surface, LINE, (WIDTH // 2 - 2, y + 4, 4, 14)) left = self.font.render(str(self.scores[0]), True, BLUE) right = self.font.render(str(self.scores[1]), True, YELLOW) surface.blit(left, left.get_rect(midtop=(WIDTH // 2 - 60, 18))) surface.blit(right, right.get_rect(midtop=(WIDTH // 2 + 60, 18))) pygame.draw.rect(surface, self.player.color, self.player.rect, border_radius=4) pygame.draw.rect(surface, self.cpu.color, self.cpu.rect, border_radius=4) pygame.draw.rect(surface, WHITE, self.ball.rect, border_radius=3) if self.winner is not None: msg = "You win!" if self.winner == 0 else "Computer wins" t = self.font.render(msg, True, WHITE) surface.blit(t, t.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 10))) h = self.small.render("Press Space for a new match", True, WHITE) surface.blit(h, h.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 40))) elif not self.ball.moving: h = self.small.render("Press Space to serve", True, WHITE) surface.blit(h, h.get_rect(center=(WIDTH // 2, HEIGHT - 40))) async def main(): pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Pong - Pygame.net") clock = pygame.time.Clock() game = Game() running = True while running: dt = min(clock.tick(FPS) / 1000, 0.05) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False else: game.handle_event(event) game.update(dt) game.draw(screen) pygame.display.flip() await asyncio.sleep(0) pygame.quit() if __name__ == "__main__": asyncio.run(main())