learning from 100 Days of Code: The Complete Python Pro Bootcamp for 2022
# main.py
from turtle import Screen
from scoreboard import ScoreBoard
from paddle import Paddle
from ball import Ball
import time
screen = Screen()
screen.setup(height=600, width=800)
screen.bgcolor("black")
screen.title("Pong")
ball = Ball()
screen.tracer(0)
screen.listen()
scoreboard = ScoreBoard()
r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
screen.onkey(r_paddle.up, "Up")
screen.onkey(r_paddle.down, "Down")
screen.onkey(l_paddle.up, "w")
screen.onkey(l_paddle.down, "s")
is_game_on = True
while is_game_on:
time.sleep(ball.move_speed)
screen.update()
ball.move()
if ball.ycor() > 280 or ball.ycor() < -280:
ball.bounce_y()
if ball.distance(r_paddle) < 90 and ball.xcor() > 320 or ball.distance(l_paddle) < 90 and ball.xcor() < -320:
ball.bounce_x()
if ball.xcor() > 390:
scoreboard.l_point()
ball.re_start()
if ball.xcor() < -390:
scoreboard.r_point()
ball.re_start()
screen.exitonclick()
# paddle.py
from turtle import Turtle
class Paddle(Turtle):
def __init__(self,position):
super().__init__()
self.shape("square")
self.shapesize(stretch_wid=5, stretch_len=1)
self.penup()
self.speed("fastest")
self.color("white")
self.goto(position)
def up(self):
new_y = self.ycor() + 20
self.goto(self.xcor(), new_y)
def down(self):
new_y = self.ycor() - 20
self.goto(self.xcor(), new_y)
# ball.py
from turtle import Turtle
class Ball(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.color("white")
self.penup()
self.x_dir = 10
self.y_dir = 10
self.move_speed = 0.1
def re_start(self):
self.move_speed = 0.1
self.goto(0, 0)
self.bounce_x()
def move(self):
new_x = self.xcor() + self.x_dir
new_y = self.ycor() + self.y_dir
self.goto(new_x, new_y)
def bounce_y(self):
self.move_speed *= 0.9
self.y_dir *= -1
def bounce_x(self):
self.move_speed *= 0.9
self.x_dir *= -1
# scoreboard.py
from turtle import Turtle
class ScoreBoard(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.hideturtle()
self.penup()
self.l_score = 0
self.r_score = 0
self.update_score()
def update_score(self):
self.clear()
self.goto(-100, 220)
self.write(self.l_score, align='center', font=('Courier', 40, 'normal'))
self.goto(100, 220)
self.write(self.r_score, align='center', font=('Courier', 40, 'normal'))
def l_point(self):
self.l_score += 1
self.update_score()
def r_point(self):
self.r_score += 1
self.update_score()