Reputation: 1
I was writing a code to make a simple game of pong using pygame and I've run into a problem which I can't seem to troubleshoot. I made a class for paddles since I wanted to recognize it as an object and now I'm getting a positional error that says that draw has no argument paddles.
Here's the code
import pygame
pygame.init()
WIDTH, HEIGHT = 700, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ping Pong!")
FPS = 60
WHITE = 255,255,255
BLACK = 0,0,0
PADDLE_WIDTH, PADDLE_HEIGHT = 20, 100
class Paddle:
color = WHITE
VEL = 4
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def draw(self,win):
pygame.draw.rect(win, self.color, (self.x, self.y, self.width,self.height))
#x and y coords will be the top left corner of the object rectangle
#The other variables will be in respect of the top left coordinate
def move(self, up=True):
if up:
self.y -= self.VEL
else:
self.y += self.VEL
def draw(win, paddles):
win.fill(BLACK)
for paddle in paddles:
paddle.draw(win)
pygame.display.update() #Updates the display
def handle_paddle_movement(keys, left_paddle, right_paddle):
if keys[pygame.K_w]:
left_paddle.move(up=True)
if keys[pygame.K_s]:
left_paddle.move(up=False)
if keys[pygame.K_UP]:
right_paddle.move(up=True)
if keys[pygame.K_DOWN]:
right_paddle.move(up=False)
def main():
run = True
clock = pygame.time.Clock()
left_paddle = Paddle(10, HEIGHT//2 - PADDLE_HEIGHT//2, PADDLE_WIDTH, PADDLE_HEIGHT)
right_paddle = Paddle(WIDTH - 10 - PADDLE_WIDTH, HEIGHT//2 - PADDLE_HEIGHT//2, PADDLE_WIDTH, PADDLE_HEIGHT)
while run:
#Limits Frames per Second
clock.tick(FPS)
draw(WIN, [left_paddle, right_paddle])
draw(WIN)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
break
keys = pygame.key.get_pressed()
handle_paddle_movement(keys, [left_paddle, right_paddle])
pygame.quit()
if __name__ == "__main__":
main()
The error im getting is draw(WIN) TypeError: draw() missing 1 required positional argument: 'paddles'
im not sure how to fix this
Upvotes: 0
Views: 395
Reputation: 1235
The draw
function requires 2 positional (or keyword) arguments:
def draw(win, paddles):
win.fill(BLACK)
for paddle in paddles:
paddle.draw(win)
pygame.display.update() #Updates the display
You use it here:
draw(WIN, [left_paddle, right_paddle]) # Here "win" is WIN and "paddles" is a list [left_paddle, right_paddle]
draw(WIN) # Here "win" is WIN and "paddles"...are not passed at all
First line is correct, second is missing the value for "paddles" argument. Also maybe in the while loop you are confusing an instance method of class Paddle
(which takes a single argument, considering that self
is let's say auto-provided) and the function draw
, which I referred to above.
Here is a very good answer regarding argument types and the issue of them being required optional and how to provide them when calling a function https://stackoverflow.com/a/57819001/15923186
Upvotes: 1