A neat game I aw on the website
It is a two player pong
with python in two hours
Not really any
How to move and control objects with python
Not much really
The source code because I couldn't put it in any other way: import turtle window = turtle.Screen() window.title("Pong by Mateo Hoffer") window.bgcolor("black") window.setup(width=800, height=600) window.tracer(0)
Score
sa = 0 sb = 0
Net
net = turtle.Turtle() net.shape("square") net.color("white") net.shapesize(stretch_wid=50, stretch_len=0.3)
Paddle A
pa = turtle.Turtle() pa.speed(0) pa.shape("square") pa.color("white") pa.shapesize(stretch_wid=7, stretch_len=1) pa.penup() pa.goto(-350,0)
Paddle B
pb = turtle.Turtle() pb.speed(0) pb.shape("square") pb.color("white") pb.shapesize(stretch_wid=7, stretch_len=1) pb.penup() pb.goto(350,0)
Ball
ball = turtle.Turtle() ball.speed(0) ball.shape("square") ball.color("white") ball.penup() ball.goto(0,0) ball.dx = 1 ball.dy = -1
Functions
def pa_up(): y = pa.ycor() y += 20 pa.sety(y) def pa_down(): y = pa.ycor() y -= 20 pa.sety(y) def pb_up(): y = pb.ycor() y += 20 pb.sety(y) def pb_down(): y = pb.ycor() y -= 20 pb.sety(y)
Pen
pen = turtle.Turtle() pen.speed(0) pen.color("green") pen.penup() pen.hideturtle() pen.goto(0,260) pen.write("Player A: 0 Player B: 0", align="center", font=("Ariel", 24, "bold"))
Keybord binding
window.listen() window.onkeypress(pa_up, "w") window.onkeypress(pa_down, "s") window.onkeypress(pb_up, "Up") window.onkeypress(pb_down, "Down")
Main Game Loop
while True: window.update()
# Move the ball ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy)
# Border Checking if ball.ycor() > 290: ball.sety(290) ball.dy *= -1 if ball.ycor() < -290: ball.sety(-290) ball.dy *= -1
if ball.xcor() > 390: ball.goto(0, 0) ball.dx *= -1 sa += 1 pen.clear() pen.write("Player A: {} Player B: {}".format(sa, sb), align="center", font=("Ariel", 24, "bold"))
if ball.xcor() < -390: ball.goto(0, 0) ball.dx *= -1 sb += 1 pen.clear() pen.write("Player A: {} Player B: {}".format(sa, sb), align="center", font=("Ariel", 24, "bold"))
# Paddle and ball colision if (ball.xcor() > 340 and ball.xcor() <350) and (ball.ycor() < pb.ycor() + 70 and ball.ycor() > pb.ycor() -70): ball.setx(340) ball.dx *= -1
if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < pa.ycor() + 70 and ball.ycor() > pa.ycor() -70): ball.setx(-340)