Ping-Pong game
- 라임 샹큼
- Mar 14
- 2 min read
This project really helped me understand OOP more and grasp the concept of inheritance in classes.
screen = Screen()
screen.setup(height = 600, width = 800)
screen.bgcolor('black')
screen.title('Ping Pong')
screen.tracer(0)
The code starts off with setting up the screen. The most important aspect here is the screen tracer being turned off.
from turtle import Turtle,Screen
class Paddle(Turtle):
def init(self,position):
super().__init__()
self.shape('square')
self.color('white')
self.shapesize(stretch_wid=5, stretch_len=1)
self.penup()
self.goto(position)
def go_up(self):
new_y = self.ycor() + 30
self.goto(self.xcor(), new_y)
def go_down(self):
new_y = self.ycor() - 30
self.goto(self.xcor(), new_y)
The paddles were then created. By inheriting the turtle class, I didn't need to clarify the variable and referred to it simply as self.
the go up and go down methods are for the later to be used onkey methods.
from turtle import Turtle
import random
class Ball(Turtle):
def init(self):
super().__init__()
self.color('white')
self.shape('circle')
self.penup()
self.goto((0,0))
self.x_move = 10
self.y_move = 10
def move(self):
new_x = self.xcor() + self.x_move
new_y = self.ycor() + self.y_move
self.goto(new_x,new_y)
def bounce_y(self):
self.y_move *= -1
def bounce_x(self):
self.x_move *= -1
def reset_position(self):
self.goto(0,0)
self.x_move *= -1
Comments