Skip to content

Instantly share code, notes, and snippets.

@mick-io
Created February 4, 2020 01:12
Show Gist options
  • Save mick-io/e7699804c6a302637e0cb77d76833fb0 to your computer and use it in GitHub Desktop.
Save mick-io/e7699804c6a302637e0cb77d76833fb0 to your computer and use it in GitHub Desktop.
Python Pong
#!/usr/bin/env python3
import turtle
# Adjust this value to increase or decrease the ball's movement speed.
BALL_PIXELS_PER_MOVEMENT = .15
SCORE_FONT = ("Courier", 24, "normal")
score_a, score_b = 0, 0
window = turtle.Screen()
window.title("Pong by Mick")
window.bgcolor("black")
window.setup(width=800, height=600)
window.tracer(0)
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.penup()
paddle_a.goto(-350, 0)
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5, stretch_len=1)
paddle_b.penup()
paddle_b.goto(350, 0)
ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = BALL_PIXELS_PER_MOVEMENT
ball.dy = BALL_PIXELS_PER_MOVEMENT
pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
def paddle_a_up() -> None:
y = paddle_a.ycor() + 20
paddle_a.sety(y)
def paddle_a_down() -> None:
y = paddle_a.ycor() - 20
paddle_a.sety(y)
def paddle_b_up() -> None:
y = paddle_b.ycor() + 20
paddle_b.sety(y)
def paddle_b_down() -> None:
y = paddle_b.ycor() - 20
paddle_b.sety(y)
def update_scoreboard() -> None:
score_text = f"Player A: {score_a} | Player B: {score_b}"
pen.clear()
pen.write(score_text, align="center", font=SCORE_FONT)
# Keyboard Bindings
window.listen()
window.onkeypress(paddle_a_up, "w")
window.onkeypress(paddle_a_down, "s")
window.onkeypress(paddle_b_up, "Up")
window.onkeypress(paddle_b_down, "Down")
update_scoreboard()
# Main Game Loop
while True:
window.update()
ball_x, ball_y = ball.xcor(), ball.ycor()
# Moving the ball
ball.setx(ball_x + ball.dx)
ball.sety(ball_y + ball.dy)
# Border Check
if ball_y> 290:
ball.sety(290)
ball.dy *= -1
if ball_y < -290:
ball.sety(-290)
ball.dy *= -1
# Score Check
if ball_x> 390:
ball.goto(0, 0)
ball.dx *= -1
score_a += 1
update_scoreboard()
if ball_x < -390:
ball.goto(0, 0)
ball.dx *= -1
score_b += 1
update_scoreboard()
paddle_x, paddle_y = paddle_a.xcor(), paddle_a.ycor()
# Paddle Ball collision
if (ball_x < -340 and ball_x > -350) and (ball_y < paddle_y + 40 and ball_y > paddle_y - 40):
ball.setx(-340)
ball.dx *= -1
paddle_x, paddle_y = paddle_b.xcor(), paddle_b.ycor()
if (ball_x > 340 and ball_x < 350) and (ball_y < paddle_y + 40 and ball_y > paddle_y - 40):
ball.setx(340)
ball.dx *= -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment