I am trying to follow the freecodecamp python pong game tutorial. However with an object oriented approach instead of a linear one.
I created an object that both the paddles and the ball would be derived from. I wanted all of the functions to be easily accessible and manageable. However when updating the balls position and pressing a key it is also moving the paddings positions as well. I am not sure why because the objects should not have anything to do with each other. its like one object is manipulating another. if anybody could assist in helping me figure out the issue that would be greatly appreciated
import turtle
class PongObj:
score = 0
speed = 0
position = [0, 0]
direction = [0, 0]
shape = 0
def __init__(self, _x, _y, _wid=5, _len=1, _dir=0) -> object:
self.shape = turtle.Turtle()
self.shape.speed(self.speed)
self.shape.shape("square")
self.shape.color("white")
self.shape.shapesize(stretch_wid=_wid, stretch_len=_len)
self.shape.penup()
self.set_location(_x, _y)
self.direction[0] = self.direction[1] = _dir
def set_speed(self, n_speed):
self.speed = n_speed
def set_location(self, _x, _y):
self.position[0] = _x
self.position[1] = _y
self.shape.goto(self.position[0], self.position[1])
def update_coordinates(self):
self.position[1] = self.shape.ycor()
self.position[0] = self.shape.xcor()
def object_up(self):
self.position[1] += 20
self.set_location(self.position[0], self.position[1])
def object_down(self):
self.position[1] -= 20
self.set_location(self.position[0], self.position[1])
def update_pos(self):
self.set_location(self.position[0] + self.direction[0],
self.position[1] + self.direction[1])
def border_check(self, max_height=290, max_width=380):
self.update_coordinates()
if self.position[1] > max_height:
self.set_location(self.position[0], max_height)
self.direction[1] *= -1
return False
if self.position[1] < -1 * max_height:
self.set_location(self.position[0], -1 * max_height)
self.direction[1] *= -1
return False
if self.position[0] > max_width:
self.set_location(0, 0)
self.direction[0] *= -1
return True
if self.position[0] < -1 * max_width:
self.set_location(0, 0)
self.direction[0] *= -1
return True
window = turtle.Screen()
window.title("Pong 2021 by Stephan Randle the Developer")
window.bgcolor("black")
window.setup(width=800, height=600)
window.tracer(0)
paddle_a = PongObj(-350, 0)
paddle_b = PongObj(350, 0)
ball = PongObj(0, 0, 1, 1, .2)
window.listen()
window.onkeypress(paddle_a.object_up, "w")
window.onkeypress(paddle_a.object_down, "s")
window.onkeypress(paddle_b.object_up, "Up")
window.onkeypress(paddle_b.object_down, "Down")
while True:
window.update()
ball.update_pos()
if ball.border_check():
if ball.direction[0] > 0:
paddle_a.score += 1
print(f"score for a: {paddle_a.score}")
else:
paddle_b.score += 1
print(f"score for b: {paddle_b.score}")