#1 Le 04/01/2022, à 20:27
- chris7522
[RESOLU]Probleme compréhension jeux Labyrinthe (python orienté objet))
Bonjour a toutes et a tous ,
J'ai pensé que vous pourriez m'aider sur un ou deux points que je ne comprends pas . Je vous donne l'ensemble du code pas trop long , puis je vous pose ma question .
Le main :
import pygame, random, sys
from CLASSES import *
from CONSTANTES import *
def AFFICHER_SCORE():
font = pygame.font.SysFont('Arial', TUILE_TAILLE - 5)
background = pygame.Surface((LARGEUR, SCORE_HAUTEUR))
background = background.convert()
background.fill(BLANC)
text = font.render(_personnage.chrono.Timer.strftime("%H:%M:%S"), 1, NOIR)
textpos = text.get_rect(centerx = LARGEUR / 2, centery = SCORE_HAUTEUR / 2)
background.blit(text, textpos)
screen.blit(background, (0, 0))
pygame.init()
screen = pygame.display.set_mode([LARGEUR, HAUTEUR])
pygame.display.set_caption('Le jeu du labyrinthe')
XX = 0
YY = 0
with open("Labyrinthe.txt", "r") as fichier:
for ligne in fichier:
for sprite in ligne:
if sprite == 'M':
_mur = MUR(XX, YY)
LISTE_MURS.add(_mur)
LISTE_GLOBALE_SPRITES.add(_mur)
XX = XX + 1
XX = 0
YY = YY + 1
_personnage = None
RECHERCHE_PERSONNAGE = True
while RECHERCHE_PERSONNAGE:
_personnage = PERSONNAGE()
LISTE_CONFLIT = pygame.sprite.spritecollide(_personnage, LISTE_MURS, False)
if len(LISTE_CONFLIT) == 0:
LISTE_GLOBALE_SPRITES.add(_personnage)
RECHERCHE_PERSONNAGE = False
while len(LISTE_OBJETS) < 10:
_objet = OBJET()
LISTE_CONFLIT = pygame.sprite.spritecollide(_objet, LISTE_GLOBALE_SPRITES, False)
if len(LISTE_CONFLIT) == 0:
LISTE_GLOBALE_SPRITES.add(_objet)
LISTE_OBJETS.add(_objet)
clock = pygame.time.Clock()
print("C'est parti...")
RUN = True
while RUN:
for event in pygame.event.get():
if event.type == pygame.QUIT:
RUN = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
_personnage.DIRECTION = 'G'
break
elif event.key == pygame.K_RIGHT:
_personnage.DIRECTION = 'D'
break
elif event.key == pygame.K_UP:
_personnage.DIRECTION = 'H'
break
elif event.key == pygame.K_DOWN:
_personnage.DIRECTION = 'B'
break
LISTE_GLOBALE_SPRITES.update()
screen.fill(BLANC)
LISTE_GLOBALE_SPRITES.draw(screen)
AFFICHER_SCORE()
if _personnage.TERMINE:
pygame.time.wait(5000)
TERMINE = False
pygame.display.flip()
dt = clock.tick(60)
_personnage.chrono.update(dt)
print("Nombre d'objets ramassés : %d" % _personnage.POINTS)
pygame.quit()
CLASSES.py :
import pygame, random, sys
from CONSTANTES import *
from datetime import timedelta, datetime, date, time
LISTE_OBJETS = pygame.sprite.Group()
LISTE_MURS = pygame.sprite.Group()
LISTE_GLOBALE_SPRITES = pygame.sprite.Group()
class MUR(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("MUR.png").convert_alpha()
self.rect = self.image.get_rect()
self.rect.y = TUILE_TAILLE * y + SCORE_HAUTEUR
self.rect.x = TUILE_TAILLE * x
class OBJET(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("OBJET.png").convert_alpha()
self.rect = self.image.get_rect()
self.rect.y = random.randint(0, TUILE_NOMBRE - 1) * TUILE_TAILLE + SCORE_HAUTEUR
self.rect.x = random.randint(0, TUILE_NOMBRE - 1) * TUILE_TAILLE
class PERSONNAGE(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("PERSONNAGE.png").convert_alpha()
self.rect = self.image.get_rect()
self.rect.y = random.randint(0, TUILE_NOMBRE - 1) * TUILE_TAILLE + SCORE_HAUTEUR
self.rect.x = random.randint(0, TUILE_NOMBRE - 1) * TUILE_TAILLE
self.POINTS = 0
self.TERMINE = False
self.DIRECTION = '-'
self.chrono = Chrono()
def update(self):
X_COURANT = self.rect.x
Y_COURANT = self.rect.y
if self.DIRECTION == 'G':
self.rect.x -= TUILE_TAILLE
self.DIRECTION = '-'
elif self.DIRECTION == 'D':
self.rect.x += TUILE_TAILLE
self.DIRECTION = '-'
elif self.DIRECTION == 'H':
self.rect.y -= TUILE_TAILLE
self.DIRECTION = '-'
elif self.DIRECTION == 'B':
self.rect.y += TUILE_TAILLE
self.DIRECTION = '-'
LISTE_COLLISION_MUR = pygame.sprite.spritecollide(self, LISTE_MURS, False)
if len(LISTE_COLLISION_MUR) > 0:
self.rect.x = X_COURANT
self.rect.y = Y_COURANT
LISTE_COLLISION_OBJET = pygame.sprite.spritecollide(self, LISTE_OBJETS, False)
for objet in LISTE_COLLISION_OBJET:
objet.kill()
self.POINTS += POINT_UNITE
if self.POINTS == 10:
self.chrono.stop()
class Chrono:
def __init__(self):
self.Timer = datetime.combine(date.today(), time(0, 0))
self.STOP = False
def stop(self):
self.STOP = True
def update(self, dt):
if self.STOP == False:
self.Timer += timedelta(milliseconds=dt)
CONSTANTES.py :
[NOIR = (0, 0, 0)
BLANC = (255, 255, 255)
TUILE_TAILLE = 30
TUILE_NOMBRE = 25
SCORE_HAUTEUR = 32
LARGEUR = TUILE_TAILLE * TUILE_NOMBRE
HAUTEUR = TUILE_TAILLE * TUILE_NOMBRE + SCORE_HAUTEUR
POINT_UNITE = 1
Dans le main :
1) Pourquoi ont ils donné la valeur None a l'instance : _personnage ? Etait ce vraiment nécéssaire ?
2) Un peu plus loin j'ai :
if _personnage.TERMINE: # sous entendu : if _personnage.TERMINE True
pygame.time.wait(5000)
TERMINE = False
L'attribut TERMINE de la classe PERSONNAGE est initialisé a la valeur False , a quel moment va t il pouvoir passer a True ?
Desolé , je suis pas sur d'avoir été super claire . Merci de votre aide !
Dernière modification par chris7522 (Le 13/01/2022, à 14:08)
Hors ligne
#2 Le 05/01/2022, à 12:38
- Compte supprimé
Re : [RESOLU]Probleme compréhension jeux Labyrinthe (python orienté objet))
Bonjour,
De ce que je vois:
Pour le 1) effectivement cela n'est pas nécessaire, vu que la valeur de _personnage est par la suite immédiatement assignée comme instance de la classe PERSONNAGE.
Pour le 2), dans le code actuel l'attribut ne passera pas à True. J'imagine que le code actuel n'est que les prémisses d'un code plus complet et que cela prend sens dans le code complet...
Dernière modification par Compte supprimé (Le 05/01/2022, à 12:39)
#3 Le 05/01/2022, à 20:02
- chris7522
Re : [RESOLU]Probleme compréhension jeux Labyrinthe (python orienté objet))
Merci de ton aide !
Dans quel cas peut on utiliser None ? Je ne vois pas trop son utilité .
Je ne voudrai pas abuser de ta gentillesse mais pourquoi avoir importé le module "sys" ?
Contrairement a Monsieur Macron , je ne veux pas t'emmerder avec mes questions , si tu n'as pas le temps de repondre aux 2 premieres qui sont un peu hors sujet , je prefere que tu reponde a celle-ci :
- Dans le fichier main :
LISTE_GLOBALE_SPRITES.update()
LISTE_GLOBALE_SPRITES a t il le droit d'utiliser la methode " def update(self): " qui se trouve dans la classe PERSONNAGE ?
Meme si on importe la classe PERSONNAGE dans le main , elle n'appartient qu'a cette classe , non ?
Dernière modification par chris7522 (Le 05/01/2022, à 20:58)
Hors ligne
#4 Le 06/01/2022, à 09:03
- Compte supprimé
Re : [RESOLU]Probleme compréhension jeux Labyrinthe (python orienté objet))
Bonjour,
Pour sys, vu qu'il semble pas utilisé, l'import est inutile.
Pour None, perso je l'utilise surtout avec une fonction:
>>> def bidon(arg=None):
if arg is None:
print('fait ceci')
else:
print(f'mon arg= {arg}')
>>> bidon()
fait ceci
>>> bidon(99999)
mon arg= 99999
>>>
LISTE_GLOBALE_SPRITES a t il le droit d'utiliser la methode " def update(self): " qui se trouve dans la classe PERSONNAGE ?
Je ne connais pas pygame et ses méthodes natives ,mais à priori il ne le fait pas.La méthode appellée appartiendrais à pygame.sprite. Tu es donc plutôt dans le cas de figure suivant:
class A:
def __init__(self):
pass
def yop(self):
print('youplaboum in A')
class B(A):
def __init__(self):
A.__init__(self)
def yop(self):
print('youplaboum redéfinie in B')
a = A()
a.yop()
b = B()
b.yop()
Note: Les import * ne sont pas une bonne pratique. Avec des import explicite on évite ce type de confusion et de risque de collision dans les espaces de nommages...
#5 Le 06/01/2022, à 10:53
- chris7522
Re : [RESOLU]Probleme compréhension jeux Labyrinthe (python orienté objet))
Ok je comprends .
Je te remercie une nouvelle fois pour toute l'aide que tu m'as apporté
Dernière modification par chris7522 (Le 06/01/2022, à 12:09)
Hors ligne
#6 Le 06/01/2022, à 11:28
- Compte supprimé
Re : [RESOLU]Probleme compréhension jeux Labyrinthe (python orienté objet))
Avec plaisir