[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] issue with pygame.rect.inflate_ip()



Hey David. Good catch, I was a bit too hasty in asserting a strict equality. Just goes to show the problem with truncating instead of rounding or using rationals. Scaling a line from 0->10 down to length 5 results in chopping off 5 from the width, then adding 2.5 (which gets truncated to 2) to recenter. The new line then is from 2->7 with a center at (2+7)/2 = 4.5 = 4, but it should really be 2.5->7.5 with a center at (2.5+7.5)/2 = 5.

The original code is still correct in most respects, though perhaps the documentation should be changed. You can work around the issue by storing the original center and reassigning it after the inflation or by using a data structure with floats or by using your own inflate function that rounds.

The devs could also change the code such that the division by 2 will round properly but there are reasons why this might not be desirable. One relatively minor reason is that the change requires a branch for negative numbers to round properly. x/2 for x>=0 turns into (x+1)/2 == x + (1-x)/2 to avoid overflow. For x < 0, it turns into (x-1)/2 == x - (1+x)/2.


On Sun, Feb 5, 2012 at 2:54 PM, david BERTRAND <dvd.brtrnd@xxxxxxxxx> wrote:
Hi kevin, hi Lenard,
here is my try :

import pygame
pygame.init()
class Box(pygame.sprite.Sprite): Â ÂÂÂ Â Â Â
  def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    self.image = pygame.Surface((10, 10))
    self.rect = self.image.get_rect()
b = Box() Â
print "initial b.rect : %s   b.rect.center : %s" % (b.rect, b.rect.center)
b.rect.inflate_ip(5, 5)
print "inflated b.rect : %s   b.rect.center : %s\n" % (b.rect, b.rect.center)
c = Box() Â
print "initial c.rect : %s   c.rect.center : %s" % (c.rect, c.rect.center)
c.rect.inflate_ip(-5, -5)
print "inflated c.rect : %s   c.rect.center : %s" % (c.rect, c.rect.center)

# outputs :
#
# initial b.rect : <rect(0, 0, 10, 10)> Â Â b.rect.center : (5, 5)
# inflated b.rect : <rect(-2, -2, 15, 15)> Â Â b.rect.center : (5, 5)
#
# initial c.rect : <rect(0, 0, 10, 10)> Â Â c.rect.center : (5, 5)
# inflated c.rect : <rect(2, 2, 5, 5)> Â Â c.rect.center : (4, 4)

I have just said it is different from what is espected ((-2, -2), (13, 13) and (5, 5) or (0, 0), (15, 15) and (7, 7)) for b.rect and b.rect center
And he results are worse with negatives.