I randomly share pictures of houses on the screen. Then I drive a car across the screen.When the car hits a house, the image of that house should be replaced with a modified copy of that house. I distribute the images with the following function
JavaScript
x
12
12
1
while len(land) < anzahl_gegenstaende:
2
ii = len(land)
3
img = pygame.image.load(f"Bilder/Gegenstaende/geg{ii}.png").convert_alpha()
4
zb,zh = img.get_rect().size
5
scale_hoehe =100
6
scale_breite = int(100 * zb / zh)
7
img = pygame.transform.scale(img,(scale_breite,scale_hoehe))
8
m = Landschaft(img)
9
10
if not pygame.sprite.spritecollide(m, land, False):
11
land.add(m)
12
I check the collision car with house
JavaScript
1
4
1
treffer = pygame.sprite.spritecollide( auto, land, False, pygame.sprite.collide_mask)
2
3
for bumbs in treffer:
4
…. How do I then get the house number or picture number of the house that collided so that I can replace the picture with a slightly modified copy?
Advertisement
Answer
Store the image number in an attribute of the Sprite class:
JavaScript
1
7
1
class Landschaft(pygame.sprite.Sprite):
2
def __init__(self, img, ii):
3
super().__init__()
4
self.img = img
5
self.ii = ii
6
# [...]
7
JavaScript
1
9
1
while len(land) < anzahl_gegenstaende:
2
ii = len(land)
3
img = pygame.image.load(f"Bilder/Gegenstaende/geg{ii}.png").convert_alpha()
4
# [...]
5
6
m = Landschaft(img, ii)
7
if not pygame.sprite.spritecollide(m, land, False):
8
land.add(m)
9
JavaScript
1
5
1
treffer = pygame.sprite.spritecollide(auto, land, False, pygame.sprite.collide_mask)
2
for bumbs in treffer:
3
ii = bomb.ii
4
# [...]
5