« Pygame/Introduction au module Sprite » : différence entre les versions

Contenu supprimé Contenu ajouté
Aucun résumé des modifications
Ligne 25 :
 
Lorsque vous utilisez les classes Sprite, il est mieux de penser à eux comme "valide" ou "vivant" lorsqu'ils sont contenus dans un ou plusieurs groupes. Lorsque vous supprimez l'instance de tous les groupes, pygame va nettoyer l'objet. (Sauf si vous possédez une référence de l'objet quelque part). La méthode kill() supprime le sprite de tous les groupes qui le contiennent. Ça supprime proprement l'objet sprite. Si , par hasard, vous avez déjà rassemblé le code source de deux jeux, vous savez certainement que supprimer proprement un objet du jeu peut être ardu. Un sprite possède également une méthode alive(), qui retourne vrai si elle est encore membre d'un groupe au moins.
 
=La classe Group=
The Group Class
The Group class is just a simple container. Similar to the sprite, it has an add() and remove() method which can change which sprites belong to the group. You also can pass a sprite or list of sprites to the contructor (__init__ method) to create a Group instance that contains some initial sprites.
 
The Group has a few other methods like empty() to remove all sprites from the group and copy() which will return a copy of the group with all the same members. Also the has() method will quickly check if the Group contains a sprite or list of sprites.
 
The other function you will use frequently is the sprites() method. This returns an object that can be looped on to access every sprite the group contains. Currently this is just a list of the sprites, but in later version of python this will likely use iterators for better performance.
 
As a shortcut, the Group also has an update() method, which will call an update() method on every sprite in the group. Passing the same arguments to each one. Usually in a game you need some function that updates the state of a game object. It's very easy to call your own methods using the Group.sprites() method, but this is a shortcut that's used enough to be included. Also note that the base Sprite class has a "dummy" update() method that takes any sort of arguments and does nothing.
 
Lastly, the Group has a couple other methods that allow you to use it with the builtlin len() method, getting the number of sprites it contains. and the "truth" operator, which allows you to do "if mygroup:" to check if the group has any sprites.