ARTICLE AD BOX
I need to dump a group's objects into a .dat file.
The problem is that when I write (using the open function) the .dat file and dump the objects in the group the program gives me the following error: cannot pickle 'pygame.surface.Surface' object.
I don't know how to get around this.
import pygame import pickle pygame.init() #create an entity class class entity(pygame.sprite.Sprite): def __init__(self, img, x, y, identity): pygame.sprite.Sprite.__init__(self) self.img = img self.img = pygame.transform.scale(self.img, (50, 50)) self.x = x self.y = y self.identity = identity def draw(self, surface): surface.blit(self.img, (self.x, self.y)) #def group variables entity_group = pygame.sprite.Group() #def int varibles screen_height = 500 screen_width = 500 #load images entity_img = pygame.image.load("assets/entity.png") entity_2_img = pygame.image.load("assets/entity 2.png") #def surface screen = pygame.display.set_mode((screen_width, screen_height)) #def entities objects entity_0 = entity(entity_img, 0, 0, "hello!") entity_1 = entity(entity_2_img, 50, 50, "hola!") entity_2 = entity(entity_img, 100, 100, "ciao!") #add the entities objects to the entity group entity_group.add(entity_0) entity_group.add(entity_1) entity_group.add(entity_2) #save the data of the group in to a .dat file with open(f"entities.dat", "wb") as file: pickle.dump(entity_group, file) #clear the data of the group entity_group.empty() #load the data of the group from the .dat file with open(f"entities.dat", "rb") as file: entity_group.add(pickle.load(file)) run = True while run: #fill the background screen.fill((255, 55, 50)) #draw the entities and print theyr identity for entity in entity_group: entity.draw(screen) print(entity.identity) #event loop for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.display.update() pygame.quit()This is the image of entity one:
and this is the image of entity two:


