Petit projet pour bien finir l’année !
Comme toujours, pour partir du bon pied dans un projet, il faut :
- bien réfléchir aux types des données et donc des variables,
- un bon découpage fonctionnel.
Ici, on va veiller à appliquer le « motif » MVC : Modèle – Vue – Contrôleur.
Les (dix) tableaux de ce matin, avec du pythontutor et des étapes :
Les codes produits ce matin en cliquant sur « lire la suite ».
D’ici la prochaine séance :
- mettre en place le « coulé » qui rajoute 10 aux valeurs des grilles des bateaux « coulés » après avoir été « touchés »,
- améliorer l’affichage console avec le titre des lignes et des colonnes pour faciliter le gameplay.
Le fichier donnees.py
from random import randint def affichage(g): '''affiche la grille g en argument''' for y in range(10): # attention d'abord y print('|', end = '') for x in range(10): print(g[y][x], end = '|') print() # retour à ligne def tirage_bateau(): # coord du début x = randint(0, 9) y = randint(0, 9) if randint(0,1) : # booléen 0 pour faux et 1 pour vrai h, v = 0, 1 # vertical else : h, v = 1, 0 # horizontal return x, y, h, v def place_pour(g, taille, x, y, h, v): for i in range(taille): # on pourrait un seul if mais plus clair if x < 10 and y < 10 : # dans la grille ? if 0 < g[y][x]: # déjà quelqu'un return False x += h y += v else : return False return True def place_bateau(g, t, x, y, h, v): for i in range(t): g[y][x] = t x += h y += v return g def creation_grille(): # en compréhension : grille = [[0] * 10 for i in range(10)] # tirages des bateaux for taille in range(2, 7): # de 2 à 6 x, y, h, v = tirage_bateau() while not place_pour(grille, taille, x, y, h, v): x, y, h, v = tirage_bateau() grille = place_bateau(grille, taille, x, y, h, v) return grille # affichage(creation_grille())
Le fichier le_jeu.py
from donnees import creation_grille grille = creation_grille() def affichage(g): for y in range(10): print("|", end='') for x in range(10): if g[y][x] == 10: print('o', end ='|') elif g[y][x] > 10: print('x', end ='|') elif g[y][x] > 20: print('m', end ='|') else: print(' ', end ='|') print() nom = input("Saisir votre nom, capitaine : ") coup = 20 print() print("Bienvenue Capitaine", nom) print() score = 0 combo = -1 while coup > 0 : affichage(grille) chaine = input("Quel est ton coup, Capt'ain " + nom + ' ?') while len(chaine) < 2 or \ chaine[0]<'A' or 'K' <= chaine[0] < 'a' or 'k' <= chaine[0] or chaine[1] < '0' or chaine [1] > '9': print("C'est pas ça : une lettre et un chiffre, stp !") chaine = input("QUel est ton coup, Capt'ain " + nom + ' ?') print("Tu as joué",chaine[0].upper()+ chaine[1]) y = ord(chaine[0].upper())-65 x = int(chaine[1]) print("soit", x, y) if 1 < grille[y][x] < 7: print("Touché !") combo += 1 score += (8 - grille[y][x]) + combo * 2 print("Score :", score) else: print("Nan !") combo = -1 coup -= 1 print("Reste", coup, "coup(s) !") grille[y][x] += 10