Skip to content

Instantly share code, notes, and snippets.

@RobinBoers
Created March 15, 2025 13:58
Show Gist options
  • Save RobinBoers/6538ba2917309bbdc3605e40e36dda35 to your computer and use it in GitHub Desktop.
Save RobinBoers/6538ba2917309bbdc3605e40e36dda35 to your computer and use it in GitHub Desktop.
Pong in 85 lines of Python :)
#!/usr/bin/python3
import pygame
s = 80
v = 5
w = 50
h = 300
d = 40
pygame.init()
screen = pygame.display.set_mode((1280, 780))
font = pygame.freetype.Font("font.ttf", s)
clock = pygame.time.Clock()
running = True
dt = 0
fps = 60
ball = {
"pos": pygame.Vector2(screen.get_width() / 2, screen.get_height() / 2),
"vel": pygame.Vector2(v, v)
}
p1_points = 0
p2_points = 0
player1 = pygame.Rect(0, screen.get_height()/2 - h/2, w, h)
player2 = pygame.Rect(screen.get_width() - w, screen.get_height()/2 - h/2, w, h)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill("purple")
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
player1.y -= abs(ball["vel"].x) * fps * dt
if keys[pygame.K_s]:
player1.y += abs(ball["vel"].x) * fps * dt
if keys[pygame.K_UP]:
player2.y -= abs(ball["vel"].x) * fps * dt
if keys[pygame.K_DOWN]:
player2.y += abs(ball["vel"].x) * fps * dt
# Rechts uit het scherm
if ball["pos"].x + d/2 >= screen.get_width():
ball["pos"].x = screen.get_width() / 2
ball["pos"].y = screen.get_height() / 2
ball["vel"] = pygame.Vector2(-v, v)
p1_points += 1
# Links uit het scherm
if ball["pos"].x <= d/2:
ball["pos"].x = screen.get_width() / 2
ball["pos"].y = screen.get_height() / 2
ball["vel"] = pygame.Vector2(v, v)
p2_points += 1
if ball["pos"].y + d/2 >= screen.get_height():
ball["vel"].y *= -1
if ball["pos"].y <= d/2:
ball["vel"].y *= -1
if player1.collidepoint(ball["pos"]) or player2.collidepoint(ball["pos"]):
ball["vel"].x *= -1.2
ball["pos"].x += ball["vel"].x * fps * dt
ball["pos"].y += ball["vel"].y * fps * dt
pygame.draw.circle(screen, "white", ball["pos"], d)
pygame.draw.rect(screen, "white", player1)
pygame.draw.rect(screen, "white", player2)
font.render_to(screen, (s, s), str(p1_points), (255, 255, 255))
font.render_to(screen, (screen.get_width() - 2*s, s), str(p2_points), (255, 255, 255))
pygame.display.flip()
dt = clock.tick(fps) / 1000
pygame.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment