I'm quite new in Python and after learning the principles I want to improve my skills by programming games. So I started with a game where simply spoken the player has to collect books (it's not that boring).
For the books I have two lists: list_classes with different names in it (e.g. Book1, Book2, Book3... Book 15) and list_book_images which includes the four different images for the books. Because there should be only three books at once visible, I create them with the following method in the main loop:
def draw_books(list_classes, reset=False, degree=BACHELOR):
global num_books_drawn
while len(books_sprites) < BOOKS_MAX_VISIBLE:
name = random.randint(0,len(list_classes)-1)
image = random.randint(0,len(list_book_images)-1)
ects = random.randint(3,5)
value = random.randint(100,1000)
book = Book(str(list_classes[name]), list_book_images[image], value, ects)
book.draw()
books_sprites.add(book)
all_sprites.add(book)
num_books_drawn += 1
Here's the class Book with the draw method.
class Book(pygame.sprite.Sprite):
def __init__(self, ID, image, value, ECTS, onscreen=False):
pygame.sprite.Sprite.__init__(self)
self.onscreen = onscreen
self.ID = ID
self.value = value
self.ECTS = ECTS
self.image = image
self.costs = 50
self.text = font_books.render(str(ID), True , WHITE)
self.rect = self.image.get_rect()
self.x = random.randint(0,WIDTH_IN_CLASSES-self.rect.width)
self.y = random.randint(MENUHEIGHT_IN_CLASSES, HEIGHT_IN_CLASSES-self.rect.height)
def draw(self):
#get width and height of text for destination
w = self.text.get_rect().width
h = self.text.get_rect().height
#blits the image on x and y
self.rect.x = self.x
self.rect.y = self.y
#prints the name of the book
self.image.blit(self.text, [int(w/2),h+10])
So the books get almost drawn how I want it, three books at once and they appear randomly. But as you can see in the (class Book) draw function I also want to blit the name (self.text). Everytime a new book appears, with an image that has already been shown, the name of the new book will overlay the old one and it isn't readable anymore. I don't know why this occurs because the old book got killed with .kill() (it fully disappeared, also the name) when the collision is detected.
How does it come that the books get killed but the self.text "survives" and still gets shown when the next book is drawn.? I couldn't find a solution for that, yet - could you please give me further information how to solve this?
Thank you very much!