Create main.py file and paste the following code
from turtle import Turtle, Screen
from paddle import Paddle
from ball import Ball
import time
from score_board import ScoreBoard
screen = Screen()
screen.listen()
screen.setup(height=600, width=1000)
screen.title("PinPong Game")
screen.bgcolor("Black")
screen.tracer(0)
r_paddle = Paddle((480, 0))
l_paddle = Paddle((-490, 0))
ball = Ball((0, 0))
screen.onkey(r_paddle.move_up, "Up")
screen.onkey(r_paddle.move_down, "Down")
screen.onkey(l_paddle.move_up, "w")
screen.onkey(l_paddle.move_down, "s")
score = ScoreBoard()
game_on = True
while game_on:
screen.update()
time.sleep(ball.bounce_speed)
ball.change_location()
if ball.ycor() < -275 or ball.ycor() > 280:
ball.bounce_on_wall()
elif ball.distance(l_paddle) < 50 and ball.xcor() < -460:
score.score_update_l()
ball.bounce_on_peddle()
elif ball.distance(r_paddle) < 50 and ball.xcor() > 450:
score.score_update_r()
ball.bounce_on_peddle()
elif ball.xcor() > 460 or ball.xcor() < -470:
ball.reset_location()
ball.bounce_on_peddle()
screen.exitonclick()
Create paddle.py and paste the following code
from turtle import Turtle
class Paddle(Turtle):
def __init__(self,position):
super().__init__()
self.shape("square")
self.shapesize(stretch_len=0.8, stretch_wid=4.0)
self.penup()
self.color("White")
self.goto(position)
def move_up(self):
y = self.ycor() + 25
if self.ycor() < 265:
self.goto(self.xcor(), y)
def move_down(self):
y = self.ycor() - 25
if self.ycor() > -265:
self.goto(self.xcor(), y)
create ball.py and paste the following code
import turtle
import random
class Ball(turtle.Turtle):
turtle.colormode(255)
def __init__(self, position):
super().__init__()
self.shape("circle")
self.penup()
self.random_color()
self.goto(position)
self.x_move = 10
self.y_move = 10
self.bounce_speed = 0.3
def change_location(self):
new_x = self.xcor() + self.x_move
new_y = self.ycor() + self.y_move
self.goto(new_x, new_y)
def bounce_on_wall(self):
self.y_move *= -1
def bounce_on_peddle(self):
self.bounce_speed *= 0.9
self.x_move *= -1
self.random_color()
def random_color(self):
r = random.randint(10, 255)
g = random.randint(10, 255)
b = random.randint(10, 255)
self.color(r, g, b)
def reset_location(self):
self.goto(0, 0)
Create score_board.py and paste the following code
from turtle import Turtle
class ScoreBoard(Turtle):
def __init__(self):
super().__init__()
self.r_score = 0
self.l_score = 0
self.show_score()
def show_score(self):
self.penup()
self.hideturtle()
self.goto(50, 270)
self.color("yellow")
self.write(self.r_score, move=False, align="left", font=("Arial", 28, "normal"))
self.goto(-50, 270)
self.color("yellow")
self.write(self.l_score, move=False, align="right", font=("Arial", 28, "normal"))
def score_update_r(self):
self.clear()
self.r_score += 1
self.show_score()
def score_update_l(self):
self.clear()
self.l_score += 1
self.show_score()
Comments
Post a Comment