inheritance - Python calling method from super class via child class not working as expected -
i have extended pygame.rect ball class. when use nstanceofball.colliderect() (line 66), no errors thrown, yet never returns true. insight why colliderect isn't working ball instances?
import sys, pygame import os import ball import random import math #from ball import ball ############################################################################################### class ball(pygame.rect): def __init__(self, x, y, width, height, screenwidth, screenheight): super(pygame.rect,self).__init__(x, y, width, height) self.floatx=x self.floaty=x self.screenwidth=screenwidth self.screenheight=screenheight self.speed=[random.random()*5-2.5, random.random()*5-2.5] def runlogic(self): self.floatx+=self.speed[0] self.floaty+=self.speed[1] if self.floatx+16<0: self.floatx=self.screenwidth if self.floatx>self.screenwidth: self.floatx=-16 if self.floaty+16<0: self.floaty=self.screenheight if self.floaty>self.screenheight: self.floaty=-16 self.x=self.floatx self.y=self.floaty ############################################################################################### os.environ['sdl_video_window_pos'] = "%d,%d" % (700, 200)#1680,1440) pygame.init() size = width, height = 320, 240 white = 255, 255, 255 blue=0,0,255 screen = pygame.display.set_mode(size) image = pygame.image.load("ball.png") ballrect=image.get_rect() balls = [] x in range(0, 100): balls.append(ball(random.random()*width, random.random()*height, ballrect.width, ballrect.height, width, height)) lastframestarttime=pygame.time.get_ticks() while 1: event in pygame.event.get(): if event.type == pygame.quit: sys.exit() if event.type == pygame.keydown: if event.key == pygame.k_escape: sys.exit() ball in balls: ball.runlogic() ball2 in balls: if ball != ball2: if ball.colliderect(ball2): print("collision detected!") balls.pop(balls.index(ball)) balls.pop(balls.index(ball2)) #balls.remove(ball2) screen.fill(blue) ball in balls: screen.blit(image, ball) pygame.display.flip() pygame.time.wait(33-(pygame.time.get_ticks()-lastframestarttime)) lastframestarttime=pygame.time.get_ticks() using super(ball, self) instead of super(pygame.rect, self) in ball.init did trick.
thank you.
the first arument super must current class, i.e. ball instead of pygame.rect:
class ball(pygame.rect): def __init__(self, x, y, width, height, screenwidth, screenheight): super(ball, self).__init__(x, y, width, height) ... there example in documentation on super.
the point of super allows call next method in inheritance order without requiring refer parent class explicitly. comes handy when using multiple inheritance, see e.g. super confusing python multiple inheritance super()
Comments
Post a Comment