IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Python Discussion :

Jeu de la vie


Sujet :

Python

  1. #1
    Nouveau Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2014
    Messages
    1
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Enseignement

    Informations forums :
    Inscription : Janvier 2014
    Messages : 1
    Points : 1
    Points
    1
    Par défaut Jeu de la vie
    Bonsoir, je me suis lancé un petit défi : programmer le jeu de la vie en python.
    J'ai déjà les bases grâce au site France IOI. Seulement, je, comme diraient les jeunes : "galére".
    J'ai les fonctions de départ mais, je n'arrive pas à coder celle qui sert à compter le nombre de cellules vivantes autour d'une cellule choisie.
    Quelqu'un aurait une idée?

    Sinon, quelqu'un aurait-il une version simple de ce code afin que je le compare au mien et m'en aide?

    Merci d'avance

    Castor-Python

  2. #2
    Membre éprouvé
    Homme Profil pro
    Aucune activité
    Inscrit en
    Novembre 2011
    Messages
    505
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Aucune activité

    Informations forums :
    Inscription : Novembre 2011
    Messages : 505
    Points : 926
    Points
    926
    Par défaut
    Bonsoir,
    En premier il serait peut-être bon de voir quelques bouts de code! Au moins pour savoir comment vous utilisez les coordonnées…

    Sinon, pour comptabiliser les cellules "vivantes" autour d'une cellule, le plus immédiat est tout simplement de parcourir les coordonnées des places possibles (dans mes souvenirs 4 pour le jeu de la vie) et de comptabiliser les "cellules" présentes.

    Clodion

  3. #3
    Membre averti
    Profil pro
    Inscrit en
    Août 2006
    Messages
    243
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 243
    Points : 328
    Points
    328
    Par défaut
    Citation Envoyé par Clodion Voir le message
    dans mes souvenirs 4 pour le jeu de la vie
    8 plutôt non ? haut/bas/droite/gauche et les 4 coins ?

  4. #4
    Expert éminent

    Homme Profil pro
    Inscrit en
    Octobre 2008
    Messages
    4 298
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 298
    Points : 6 778
    Points
    6 778
    Par défaut
    Ben normalement on met les paramètres en entrées utilisateur pour pouvoir simuler divers scénari de reproduction-destruction.

  5. #5
    Membre du Club
    Profil pro
    Inscrit en
    Juin 2013
    Messages
    43
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2013
    Messages : 43
    Points : 60
    Points
    60
    Par défaut
    Bonjour,

    Je ne connaissais pas ce jeu du coup j'ai trouvé ça intéressant et j'me suis lancé dedans...

    J'ai juste lu le principe sur Internet, je ne sais pas trop quel était exactement ce que tu cherchais à faire mais j'ai rapidement fait cette "version" :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    from Tkinter import *
     
    def AddPoint():
    	#Fonction pour l'ajout de point en début de jeu
    	global repartition, L, H
    	can.create_rectangle(10*int(Abs.get()),10*int(Ord.get()),10*(int(Abs.get())+1),10*(int(Ord.get())+1),fill='white')
    	repartition[int(Abs.get())+L*int(Ord.get())] = 1
     
    def CreatePoint(x,y,color):
    	#Fonction pour la création d'un nouveau point
    	global repartition, L, H
    	can.create_rectangle(10*x,10*y,10*(x+1),10*(y+1),fill=color)
    	repartition[x+L*y] = 1
     
    def DestructPoint(x,y):
    	#Fonction pour la création d'un nouveau point
    	global repartition, L, H
    	can.create_rectangle(10*x,10*y,10*(x+1),10*(y+1),fill='black')
    	repartition[x+L*y] = 0
     
    def coord(X):
    	#Fonction qui renvoit le nombre de point voisin à la position X, note: X=x+y*L
    	global repartition, L, H
    	if X<L:
    		if X%L==0:
    			voisins = repartition[X+1] + repartition[X+L] + repartition[X+L+1] 
    		elif X%L==L-1:
    			voisins = repartition[X-1] + repartition[X+L-1] + repartition[X+L]
    		else:
    			voisins = repartition[X-1] + repartition[X+1] + repartition[X+L-1]\
    			+ repartition[X+L] + repartition[X+L+1]
    	elif X>H*L-L-1:
    		if X%L==0:
    			voisins = repartition[X-L] + repartition[X-L+1] + repartition[X+1]
    		elif X%L==L-1:
    			voisins = repartition[X-L-1] + repartition[X-L] + repartition[X-1]
    		else:
    			voisins = repartition[X-L-1] + repartition[X-L] + repartition[X-L+1]\
    			+ repartition[X-1] + repartition[X+1]
    	elif X%L==0:
    		voisins = repartition[X-L] + repartition[X-L+1] + repartition[X+1]\
    		+ repartition[X+L] + repartition[X+L+1]
    	elif X%L==L-1:
    		voisins = repartition[X-L-1] + repartition[X-L] + repartition[X-1]\
    		+ repartition[X+L-1] + repartition[X+L]
    	else:
    		voisins = repartition[X-L-1] + repartition[X-L] + repartition[X-L+1]\
    		+ repartition[X-1] + repartition[X+1]\
    		+ repartition[X+L-1] + repartition[X+L] + repartition[X+L+1]
    	return voisins
     
    def analyse():
    	#Analyse les points qui vont être créés et ceux qui vont disparaitres à ce tour-ci
    	global repartition
    	next = [-1 if (repartition[x]==1)*(coord(x)>3 or coord(x)<2) else\
    	1 if (coord(x)==3)*(repartition[x]==0) else 0 for x in range(len(repartition))]
    	return next
     
    def NextStep(next):
    	#Fonction qui détruits les points morts et qui génére les nouveaux points
    	global L,H
    	for x in range(len(next)):
    		if next[x]==-1:
    			DestructPoint(x%L,(x-x%L)/L)
    			repartition[x]=0
    		elif next[x]==1:
    			CreatePoint(x%L,(x-x%L)/L,'green')
    			repartition[x]=1
     
    def GreenWhite(next):
    	#Fonction qui transforme les points verts neufs en points blanch anciens
    	global L,H
    	for x in range(len(next)):
    		if next[x]==1:
    			CreatePoint(x%L,(x-x%L)/L,'white')
    			repartition[x]=1
     
    def RunNext():
    	global n, next
    	if n > 0:
    		#Au premier lancement il n'y a pas de points verts
    		GreenWhite(next)
    	next=analyse()
    	NextStep(next)
    	n += 1
     
     
    fn = Tk()
    fn.title("Jeu de la vie")
    L = 50
    H = 50
    n = 0
    Lcanvas = L*10
    Hcanvas = H*10
    repartition = [0]*L*H
     
    # Creation de points
     
    #Absisse
    Label1 = Label(fn, text = 'Absisse :')
    Label1.pack(side = LEFT, padx = 5, pady = 5)
     
    Abs= StringVar()
    Champ = Entry(fn, textvariable= Abs)
    Champ.focus_set()
    Champ.pack(side = LEFT, padx = 5, pady = 5)
    Abs.set("0")
     
    #Ordonnée
    Label2 = Label(fn, text = 'Ordonnee :')
    Label2.pack(side = LEFT, padx = 5, pady = 5)
     
    Ord= StringVar()
    Champ = Entry(fn, textvariable= Ord)
    Champ.focus_set()
    Champ.pack(side = LEFT, padx = 5, pady = 5)
    Ord.set("0")
     
    #bouton d'ajout
    BoutonAjout = Button(fn, text ='Ajouter point', command = AddPoint)
    BoutonAjout.pack(side = LEFT, padx = 5, pady = 5)
     
    #Canvas
    can = Canvas(fn, width = Lcanvas, height = Hcanvas, bg = 'black')
    can.pack()
     
    #bouton de lancement
    boutonRun = Button(fn, text = 'Run', command = RunNext)
    boutonRun.pack()
     
    fn.mainloop()
    Il faut d'abord ajouter les premiers points puis cliquer sur Run pour chaque étape.

    Alors, à noter que mon code n'est ABSOLUMENT PAS optimisé, j'ai fais avec mon peu de connaissance et cela "assez rapidement". Je pense qu'il serait intéressant de faire l'ajout de point à la sourie. Voilà!!

    Edit: pour une raison surement simple mais qui m'échappe, le code fonctionne sans message d'erreur sur la console mais ne fonctionne pas en le lançant simplement d'un fichier...

  6. #6
    Expert éminent

    Homme Profil pro
    Inscrit en
    Octobre 2008
    Messages
    4 298
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 298
    Points : 6 778
    Points
    6 778
    Par défaut
    Tu veux dire si tu le rend exécutable et que tu double-click dessus ? Peut-être te manque-t-il le shebang pour ça.

    Côté optimisation, j'ai pas vraiment tout regardé mais ceci:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
     
    def coord(X):
    	#Fonction qui renvoit le nombre de point voisin à la position X, note: X=x+y*L
    	global repartition, L, H
    	if X<L:
    		if X%L==0:
    			voisins = repartition[X+1] + repartition[X+L] + repartition[X+L+1] 
    		elif X%L==L-1:
    			voisins = repartition[X-1] + repartition[X+L-1] + repartition[X+L]
    		else:
    			voisins = repartition[X-1] + repartition[X+1] + repartition[X+L-1]\
    			+ repartition[X+L] + repartition[X+L+1]
    	elif X>H*L-L-1:
    		if X%L==0:
    			voisins = repartition[X-L] + repartition[X-L+1] + repartition[X+1]
    		elif X%L==L-1:
    			voisins = repartition[X-L-1] + repartition[X-L] + repartition[X-1]
    		else:
    			voisins = repartition[X-L-1] + repartition[X-L] + repartition[X-L+1]\
    			+ repartition[X-1] + repartition[X+1]
    	elif X%L==0:
    		voisins = repartition[X-L] + repartition[X-L+1] + repartition[X+1]\
    		+ repartition[X+L] + repartition[X+L+1]
    	elif X%L==L-1:
    		voisins = repartition[X-L-1] + repartition[X-L] + repartition[X-1]\
    		+ repartition[X+L-1] + repartition[X+L]
    	else:
    		voisins = repartition[X-L-1] + repartition[X-L] + repartition[X-L+1]\
    		+ repartition[X-1] + repartition[X+1]\
    		+ repartition[X+L-1] + repartition[X+L] + repartition[X+L+1]
    	return voisins
    est particulièrement indigeste et souvent source d'erreur.

    Ce qui peut être aisément simplifié:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
     
    # Largeur du damier
    WIDTH = 100
    # Hauteur du damier
    HEIGHT = 100
    # Hors-limites ((axe x), (axe y))
    LIMITS = ((-1, WIDTH), (-1, HEIGHT))
    # Décalage des cases voisines ((Nord), (Nord-Ouest), (Ouest), (Ouest-Sud), etc)
    ADJACENTS = ((0, -1), (-1, -1), (-1, 0), (-1, 1), 
                    (0, 1), (1, 1), (1, 0), (1, -1))
     
    cells = # liste de listes représentant le damier, 1 = cellule vivante et 0 = morte
            # sans doute nomée repartition dans le code initial
     
    def get_voisinnage(cell):
        # cell -> (pos x, pos y) de la cellule examinée
        voisins = []
        for adj in ADJACENTS:
            v = get_voisin(cell, adj)
            if v is not None:
                voisins.append(v)
     
        print('voisins: %s vivantes, %s mortes' %(sum(voisins), len(voisins)-sum(voisins)
     
    def get_voisin(pos, offset):
        x, y = pos[0] + offset[0], pos[1] + offset[1]
        if x in LIMITS[0] or y in LIMITS[1]:
            return
     
        return cells[y][x]
    J'ai omis global et autres dispositions ménagères, mais ce code fonctionne.

  7. #7
    Membre du Club
    Profil pro
    Inscrit en
    Juin 2013
    Messages
    43
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2013
    Messages : 43
    Points : 60
    Points
    60
    Par défaut
    Citation Envoyé par VinsS Voir le message
    Tu veux dire si tu le rend exécutable et que tu double-click dessus ? Peut-être te manque-t-il le shebang pour ça.
    C'est la fatigue de 0H32

    Pour ta fonction c'était en effet la première chose qu'il fallait changer selon moi. J'avais pensé également à passer par append mais je ne voyais pas trop comment gérer les conditions...et en effet en utilisant simplement les limites ça fonctionne très bien... Merci!

Discussions similaires

  1. Problème jeu de la vie de Wolfram
    Par romromp dans le forum Pascal
    Réponses: 14
    Dernier message: 11/03/2007, 20h58
  2. algorithme d'évolution du "jeu de la vie" en caml
    Par nono88 dans le forum Algorithmes et structures de données
    Réponses: 6
    Dernier message: 13/12/2006, 01h56
  3. Conway's life (jeu de la vie) pour images
    Par O( N ) dans le forum C
    Réponses: 1
    Dernier message: 26/09/2006, 03h13
  4. [Conception] Jeu de la vie
    Par deuscapser dans le forum Général Java
    Réponses: 16
    Dernier message: 09/03/2006, 13h47
  5. [VB] projet à réaliser: Jeu de la vie
    Par mauriiice dans le forum VB 6 et antérieur
    Réponses: 5
    Dernier message: 02/12/2005, 21h06

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo