mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Add drawing canvas (canvas module, DrawingView, drawing_* tests) and levels 13-14 (classes, saved patterns)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"en": {
|
||||
"11a96b961f883329": {
|
||||
"text": "For what comes next, PyQuest lends you a drawing sheet. Write import canvas, then canvas.line(x1, y1, x2, y2, \"red\") draws a line from point 1 to point 2. The point (0, 0) is in the centre of the sheet, positive numbers go right and up, to 200. The possible colours are black, red, green, blue, orange, purple and gray. Each run starts from a blank sheet.",
|
||||
"voice": "en_US-ljspeech-high"
|
||||
},
|
||||
"88964fb8545a1fb5": {
|
||||
"text": "Now put an object behind the pen: a Pencil, a pencil that knows where it is (x, y) and where it faces (angle, in degrees, 0 is to the right). The turn method changes the angle. The forward method computes the end point with math.cos and math.sin, draws the line, then remembers the new position.",
|
||||
"voice": "en_US-ljspeech-high"
|
||||
},
|
||||
"d0298d50d336e794": {
|
||||
"text": "So far you have used ready-made objects: a string, a list. With class, you build your own. A class is a blueprint; each object created from it is called an instance. The special method __init__ prepares the object when it is born, and self means the object itself.",
|
||||
"voice": "en_US-ljspeech-high"
|
||||
},
|
||||
"fd07a17a780038df": {
|
||||
"text": "An object keeps information: its attributes, like self.name. Its methods can read them, but also change them. Each instance has its own values: two counters created from the same class do not mix.",
|
||||
"voice": "en_US-ljspeech-high"
|
||||
}
|
||||
},
|
||||
"fr": {
|
||||
"2292126e0728171c": {
|
||||
"text": "Maintenant, mets un objet derrière le stylo : un Pencil, un crayon qui sait où il est (x, y) et vers où il regarde (angle, en degrés, 0 vers la droite). La méthode turn change l'angle. La méthode forward calcule le point d'arrivée avec math.cos et math.sin, trace le trait, puis mémorise la nouvelle position.",
|
||||
"voice": "fr_FR-siwis-medium"
|
||||
},
|
||||
"c06a478ff2283891": {
|
||||
"text": "Un objet garde des informations : ses attributs, comme self.name. Ses méthodes peuvent les lire, mais aussi les modifier. Chaque instance a ses propres valeurs : deux compteurs créés à partir de la même classe ne se mélangent pas.",
|
||||
"voice": "fr_FR-siwis-medium"
|
||||
},
|
||||
"da2f083949fad49f": {
|
||||
"text": "Pour la suite, PyQuest te prête une feuille de dessin. Écris import canvas, puis canvas.line(x1, y1, x2, y2, \"red\") trace un trait du point 1 au point 2. Le point (0, 0) est au centre de la feuille, les nombres positifs vont vers la droite et vers le haut, jusqu'à 200. Les couleurs possibles sont black, red, green, blue, orange, purple et gray. Chaque exécution repart d'une feuille vierge.",
|
||||
"voice": "fr_FR-siwis-medium"
|
||||
},
|
||||
"e190b03895d29478": {
|
||||
"text": "Jusqu'ici, tu as utilisé des objets déjà faits : une chaîne, une liste. Avec class, tu fabriques les tiens. Une classe est un plan de construction ; chaque objet créé avec ce plan s'appelle une instance. La méthode spéciale __init__ prépare l'objet à sa naissance, et self désigne l'objet lui-même.",
|
||||
"voice": "fr_FR-siwis-medium"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
id: 13-classes
|
||||
title:
|
||||
fr: Créer ses propres objets
|
||||
en: Creating your own objects
|
||||
difficulty: 5
|
||||
xp: 120
|
||||
requires:
|
||||
- 12-errors
|
||||
steps:
|
||||
- type: explain
|
||||
voice: true
|
||||
text:
|
||||
fr: "Jusqu'ici, tu as utilisé des objets déjà faits : une chaîne, une liste. Avec `class`, tu fabriques les tiens. Une classe est un plan de construction ; chaque objet créé avec ce plan s'appelle une instance. La méthode spéciale `__init__` prépare l'objet à sa naissance, et `self` désigne l'objet lui-même."
|
||||
en: "So far you have used ready-made objects: a string, a list. With `class`, you build your own. A class is a blueprint; each object created from it is called an instance. The special method `__init__` prepares the object when it is born, and `self` means the object itself."
|
||||
- type: code
|
||||
starter: |
|
||||
class Dog:
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
|
||||
def bark(self):
|
||||
# Affiche le nom du chien suivi de « aboie ! »
|
||||
pass
|
||||
|
||||
|
||||
rex = Dog("Rex")
|
||||
rex.bark()
|
||||
instruction:
|
||||
fr: "Complète la méthode `bark` pour qu'elle affiche Rex aboie ! (en utilisant `self.name`)."
|
||||
en: "Complete the `bark` method so that it shows Rex aboie ! (using `self.name`)."
|
||||
tests:
|
||||
- kind: stdout_equals
|
||||
value: "Rex aboie !\n"
|
||||
message:
|
||||
fr: "Il faut afficher exactement Rex aboie !"
|
||||
en: "It must show exactly Rex aboie !"
|
||||
- kind: code_contains
|
||||
value: self.name
|
||||
message:
|
||||
fr: "Utilise self.name pour retrouver le nom de l'objet."
|
||||
en: "Use self.name to get the object's name."
|
||||
hints:
|
||||
fr:
|
||||
- "Dans une méthode, `self.name` donne le nom de l'objet sur lequel on appelle la méthode."
|
||||
- "Écris `print(self.name, \"aboie !\")`."
|
||||
en:
|
||||
- "Inside a method, `self.name` gives the name of the object the method is called on."
|
||||
- "Write `print(self.name, \"aboie !\")`."
|
||||
solution: |
|
||||
class Dog:
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
|
||||
def bark(self):
|
||||
print(self.name, "aboie !")
|
||||
|
||||
|
||||
rex = Dog("Rex")
|
||||
rex.bark()
|
||||
- type: explain
|
||||
voice: true
|
||||
text:
|
||||
fr: "Un objet garde des informations : ses attributs, comme `self.name`. Ses méthodes peuvent les lire, mais aussi les modifier. Chaque instance a ses propres valeurs : deux compteurs créés à partir de la même classe ne se mélangent pas."
|
||||
en: "An object keeps information: its attributes, like `self.name`. Its methods can read them, but also change them. Each instance has its own values: two counters created from the same class do not mix."
|
||||
- type: code
|
||||
starter: |
|
||||
class Counter:
|
||||
def __init__(self):
|
||||
self.count = 0
|
||||
|
||||
def add(self):
|
||||
# Ajoute 1 au compteur
|
||||
pass
|
||||
|
||||
|
||||
c = Counter()
|
||||
c.add()
|
||||
c.add()
|
||||
c.add()
|
||||
print(c.count)
|
||||
instruction:
|
||||
fr: "Complète la méthode `add` pour qu'elle augmente `self.count` de 1. Le programme doit afficher 3."
|
||||
en: "Complete the `add` method so that it increases `self.count` by 1. The program must show 3."
|
||||
tests:
|
||||
- kind: stdout_equals
|
||||
value: "3\n"
|
||||
message:
|
||||
fr: "Après trois appels à add, le compteur doit valoir 3."
|
||||
en: "After three calls to add, the counter must be 3."
|
||||
- kind: code_contains
|
||||
value: self.count
|
||||
message:
|
||||
fr: "Modifie l'attribut self.count."
|
||||
en: "Change the self.count attribute."
|
||||
hints:
|
||||
fr:
|
||||
- "Une méthode modifie un attribut en lui réaffectant une valeur."
|
||||
- "Écris `self.count += 1`."
|
||||
en:
|
||||
- "A method changes an attribute by assigning it a new value."
|
||||
- "Write `self.count += 1`."
|
||||
solution: |
|
||||
class Counter:
|
||||
def __init__(self):
|
||||
self.count = 0
|
||||
|
||||
def add(self):
|
||||
self.count += 1
|
||||
|
||||
|
||||
c = Counter()
|
||||
c.add()
|
||||
c.add()
|
||||
c.add()
|
||||
print(c.count)
|
||||
- type: explain
|
||||
voice: true
|
||||
text:
|
||||
fr: "Pour la suite, PyQuest te prête une feuille de dessin. Écris `import canvas`, puis `canvas.line(x1, y1, x2, y2, \"red\")` trace un trait du point 1 au point 2. Le point (0, 0) est au centre de la feuille, les nombres positifs vont vers la droite et vers le haut, jusqu'à 200. Les couleurs possibles sont black, red, green, blue, orange, purple et gray. Chaque exécution repart d'une feuille vierge."
|
||||
en: "For what comes next, PyQuest lends you a drawing sheet. Write `import canvas`, then `canvas.line(x1, y1, x2, y2, \"red\")` draws a line from point 1 to point 2. The point (0, 0) is in the centre of the sheet, positive numbers go right and up, to 200. The possible colours are black, red, green, blue, orange, purple and gray. Each run starts from a blank sheet."
|
||||
- type: code
|
||||
starter: |
|
||||
import canvas
|
||||
|
||||
# Trace un trait rouge de (0, 0) à (100, 0)
|
||||
# puis un trait bleu de (0, 0) à (0, 100)
|
||||
instruction:
|
||||
fr: "Dessine un trait rouge horizontal et un trait bleu vertical, comme indiqué dans les commentaires."
|
||||
en: "Draw a horizontal red line and a vertical blue line, as described in the comments."
|
||||
tests:
|
||||
- kind: drawing_has_line
|
||||
value: "0,0 100,0 red"
|
||||
message:
|
||||
fr: "Il manque le trait rouge de (0, 0) à (100, 0)."
|
||||
en: "The red line from (0, 0) to (100, 0) is missing."
|
||||
- kind: drawing_has_line
|
||||
value: "0,0 0,100 blue"
|
||||
message:
|
||||
fr: "Il manque le trait bleu de (0, 0) à (0, 100)."
|
||||
en: "The blue line from (0, 0) to (0, 100) is missing."
|
||||
- kind: drawing_segments
|
||||
value: "2"
|
||||
message:
|
||||
fr: "Le dessin doit contenir exactement deux traits."
|
||||
en: "The drawing must contain exactly two lines."
|
||||
hints:
|
||||
fr:
|
||||
- "Un trait s'écrit `canvas.line(x1, y1, x2, y2, couleur)`, avec la couleur entre guillemets."
|
||||
- "`canvas.line(0, 0, 100, 0, \"red\")` trace le premier trait."
|
||||
en:
|
||||
- "A line is written `canvas.line(x1, y1, x2, y2, colour)`, with the colour in quotes."
|
||||
- "`canvas.line(0, 0, 100, 0, \"red\")` draws the first line."
|
||||
solution: |
|
||||
import canvas
|
||||
|
||||
canvas.line(0, 0, 100, 0, "red")
|
||||
canvas.line(0, 0, 0, 100, "blue")
|
||||
- type: explain
|
||||
voice: true
|
||||
text:
|
||||
fr: "Maintenant, mets un objet derrière le stylo : un Pencil, un crayon qui sait où il est (`x`, `y`) et vers où il regarde (`angle`, en degrés, 0 vers la droite). La méthode `turn` change l'angle. La méthode `forward` calcule le point d'arrivée avec `math.cos` et `math.sin`, trace le trait, puis mémorise la nouvelle position."
|
||||
en: "Now put an object behind the pen: a Pencil, a pencil that knows where it is (`x`, `y`) and where it faces (`angle`, in degrees, 0 is to the right). The `turn` method changes the angle. The `forward` method computes the end point with `math.cos` and `math.sin`, draws the line, then remembers the new position."
|
||||
- type: code
|
||||
starter: |
|
||||
import math
|
||||
import canvas
|
||||
|
||||
|
||||
class Pencil:
|
||||
def __init__(self):
|
||||
self.x = 0
|
||||
self.y = 0
|
||||
self.angle = 0 # en degrés ; 0 = vers la droite
|
||||
|
||||
def turn(self, degrees):
|
||||
self.angle += degrees
|
||||
|
||||
def forward(self, distance):
|
||||
# 1. Calcule le point d'arrivée : x + distance * cos(angle), y + distance * sin(angle)
|
||||
# (math.radians convertit les degrés)
|
||||
# 2. Trace le trait de la position actuelle au point d'arrivée
|
||||
# 3. Mémorise le point d'arrivée comme nouvelle position
|
||||
pass
|
||||
|
||||
|
||||
pencil = Pencil()
|
||||
pencil.forward(100)
|
||||
pencil.turn(90)
|
||||
pencil.forward(50)
|
||||
instruction:
|
||||
fr: "Écris la méthode `forward` en suivant les trois étapes. Le dessin doit montrer un trait horizontal de 100, puis un trait vertical de 50."
|
||||
en: "Write the `forward` method following the three steps. The drawing must show a horizontal line of 100, then a vertical line of 50."
|
||||
tests:
|
||||
- kind: drawing_has_line
|
||||
value: "0,0 100,0"
|
||||
message:
|
||||
fr: "Le premier trait doit aller de (0, 0) à (100, 0)."
|
||||
en: "The first line must go from (0, 0) to (100, 0)."
|
||||
- kind: drawing_has_line
|
||||
value: "100,0 100,50"
|
||||
message:
|
||||
fr: "Le second trait doit partir de (100, 0) vers le haut jusqu'à (100, 50) : mémorise la nouvelle position."
|
||||
en: "The second line must start at (100, 0) and go up to (100, 50): remember the new position."
|
||||
- kind: drawing_segments
|
||||
value: "2"
|
||||
message:
|
||||
fr: "Le dessin doit contenir exactement deux traits."
|
||||
en: "The drawing must contain exactly two lines."
|
||||
- kind: code_contains
|
||||
value: math.cos
|
||||
message:
|
||||
fr: "Utilise math.cos pour calculer la nouvelle abscisse."
|
||||
en: "Use math.cos to compute the new x."
|
||||
hints:
|
||||
fr:
|
||||
- "`new_x = self.x + distance * math.cos(math.radians(self.angle))`, et de même avec `math.sin` pour `new_y`."
|
||||
- "Appelle `canvas.line(self.x, self.y, new_x, new_y)`, puis `self.x = new_x` et `self.y = new_y`."
|
||||
en:
|
||||
- "`new_x = self.x + distance * math.cos(math.radians(self.angle))`, and likewise with `math.sin` for `new_y`."
|
||||
- "Call `canvas.line(self.x, self.y, new_x, new_y)`, then `self.x = new_x` and `self.y = new_y`."
|
||||
solution: |
|
||||
import math
|
||||
import canvas
|
||||
|
||||
|
||||
class Pencil:
|
||||
def __init__(self):
|
||||
self.x = 0
|
||||
self.y = 0
|
||||
self.angle = 0
|
||||
|
||||
def turn(self, degrees):
|
||||
self.angle += degrees
|
||||
|
||||
def forward(self, distance):
|
||||
new_x = self.x + distance * math.cos(math.radians(self.angle))
|
||||
new_y = self.y + distance * math.sin(math.radians(self.angle))
|
||||
canvas.line(self.x, self.y, new_x, new_y)
|
||||
self.x = new_x
|
||||
self.y = new_y
|
||||
|
||||
|
||||
pencil = Pencil()
|
||||
pencil.forward(100)
|
||||
pencil.turn(90)
|
||||
pencil.forward(50)
|
||||
mission:
|
||||
title:
|
||||
fr: Le carré rouge
|
||||
en: The red square
|
||||
goal:
|
||||
fr: "Donne une couleur au crayon : `Pencil` reçoit une `color` à sa création, la mémorise dans `self.color` et s'en sert pour tracer. Puis, avec une boucle, dessine un carré rouge de 100 de côté : avancer de 100, tourner de 90, quatre fois."
|
||||
en: "Give the pencil a colour: `Pencil` receives a `color` when created, stores it in `self.color` and uses it to draw. Then, with a loop, draw a red square with sides of 100: move forward 100, turn 90, four times."
|
||||
starter: |
|
||||
import math
|
||||
import canvas
|
||||
|
||||
|
||||
class Pencil:
|
||||
def __init__(self):
|
||||
self.x = 0
|
||||
self.y = 0
|
||||
self.angle = 0
|
||||
|
||||
def turn(self, degrees):
|
||||
self.angle += degrees
|
||||
|
||||
def forward(self, distance):
|
||||
new_x = self.x + distance * math.cos(math.radians(self.angle))
|
||||
new_y = self.y + distance * math.sin(math.radians(self.angle))
|
||||
canvas.line(self.x, self.y, new_x, new_y)
|
||||
self.x = new_x
|
||||
self.y = new_y
|
||||
|
||||
|
||||
pencil = Pencil()
|
||||
# Dessine le carré rouge ici
|
||||
tests:
|
||||
- kind: drawing_segments
|
||||
value: "4"
|
||||
message:
|
||||
fr: "Un carré a exactement quatre côtés."
|
||||
en: "A square has exactly four sides."
|
||||
- kind: drawing_has_line
|
||||
value: "0,0 100,0 red"
|
||||
message:
|
||||
fr: "Le premier côté (rouge) doit aller de (0, 0) à (100, 0)."
|
||||
en: "The first (red) side must go from (0, 0) to (100, 0)."
|
||||
- kind: drawing_has_line
|
||||
value: "100,0 100,100 red"
|
||||
- kind: drawing_has_line
|
||||
value: "100,100 0,100 red"
|
||||
- kind: drawing_has_line
|
||||
value: "0,100 0,0 red"
|
||||
message:
|
||||
fr: "Le carré doit se refermer sur le point de départ."
|
||||
en: "The square must close back on the starting point."
|
||||
- kind: code_contains
|
||||
value: self.color
|
||||
message:
|
||||
fr: "Le crayon doit mémoriser sa couleur dans self.color."
|
||||
en: "The pencil must store its colour in self.color."
|
||||
solution: |
|
||||
import math
|
||||
import canvas
|
||||
|
||||
|
||||
class Pencil:
|
||||
def __init__(self, color):
|
||||
self.x = 0
|
||||
self.y = 0
|
||||
self.angle = 0
|
||||
self.color = color
|
||||
|
||||
def turn(self, degrees):
|
||||
self.angle += degrees
|
||||
|
||||
def forward(self, distance):
|
||||
new_x = self.x + distance * math.cos(math.radians(self.angle))
|
||||
new_y = self.y + distance * math.sin(math.radians(self.angle))
|
||||
canvas.line(self.x, self.y, new_x, new_y, self.color)
|
||||
self.x = new_x
|
||||
self.y = new_y
|
||||
|
||||
|
||||
pencil = Pencil("red")
|
||||
for _ in range(4):
|
||||
pencil.forward(100)
|
||||
pencil.turn(90)
|
||||
reward_sound: success_big
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"en": {
|
||||
"26cc48e9619ce42f": {
|
||||
"text": "Last level: a real little project that brings everything together. Your pencil will remember its moves. You will save them in a file in the data/ folder, then reload them to redraw the same picture, even after closing the page. Three ingredients: a class, files, and functions.",
|
||||
"voice": "en_US-ljspeech-high"
|
||||
},
|
||||
"b7a3b7e04d0225be": {
|
||||
"text": "To reload, we do the opposite: read each line, cut it in two with split, and convert the value to a number with int. The function returns the list of moves, ready to be replayed on a new pencil.",
|
||||
"voice": "en_US-ljspeech-high"
|
||||
},
|
||||
"df6e85defae7c570": {
|
||||
"text": "To save, we write one move per line in a text file, for example forward 100 then turn 90. Remember: only the data/ folder is kept when you close the page. A function that receives the list and the file path makes the code reusable.",
|
||||
"voice": "en_US-ljspeech-high"
|
||||
}
|
||||
},
|
||||
"fr": {
|
||||
"4177d99641662c78": {
|
||||
"text": "Pour recharger, on fait l'inverse : on lit chaque ligne, on la coupe en deux avec split, et on convertit la valeur en nombre avec int. La fonction renvoie la liste des mouvements, prête à être rejouée sur un crayon neuf.",
|
||||
"voice": "fr_FR-siwis-medium"
|
||||
},
|
||||
"6d7e943c94209ae3": {
|
||||
"text": "Dernier niveau : un vrai petit projet qui réunit tout. Ton crayon va se souvenir de ses mouvements. Tu les enregistreras dans un fichier du dossier data/, puis tu les rechargeras pour refaire le même dessin, même après avoir fermé la page. Trois ingrédients : une classe, des fichiers, et des fonctions.",
|
||||
"voice": "fr_FR-siwis-medium"
|
||||
},
|
||||
"d11efca07a83cd02": {
|
||||
"text": "Pour sauvegarder, on écrit un mouvement par ligne dans un fichier texte, par exemple forward 100 puis turn 90. Souviens-toi : seul le dossier data/ est conservé quand tu fermes la page. Une fonction qui reçoit la liste et le chemin du fichier rend le code réutilisable.",
|
||||
"voice": "fr_FR-siwis-medium"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
id: 14-project
|
||||
title:
|
||||
fr: Projet - mes dessins sauvegardés
|
||||
en: Project - my saved drawings
|
||||
difficulty: 6
|
||||
xp: 150
|
||||
requires:
|
||||
- 13-classes
|
||||
steps:
|
||||
- type: explain
|
||||
voice: true
|
||||
text:
|
||||
fr: "Dernier niveau : un vrai petit projet qui réunit tout. Ton crayon va se souvenir de ses mouvements. Tu les enregistreras dans un fichier du dossier `data/`, puis tu les rechargeras pour refaire le même dessin, même après avoir fermé la page. Trois ingrédients : une classe, des fichiers, et des fonctions."
|
||||
en: "Last level: a real little project that brings everything together. Your pencil will remember its moves. You will save them in a file in the `data/` folder, then reload them to redraw the same picture, even after closing the page. Three ingredients: a class, files, and functions."
|
||||
- type: code
|
||||
starter: |
|
||||
import math
|
||||
import canvas
|
||||
|
||||
|
||||
class Pencil:
|
||||
def __init__(self):
|
||||
self.x = 0
|
||||
self.y = 0
|
||||
self.angle = 0
|
||||
self.moves = []
|
||||
|
||||
def turn(self, degrees):
|
||||
self.angle += degrees
|
||||
# À compléter : mémorise ("turn", degrees) dans self.moves
|
||||
|
||||
def forward(self, distance):
|
||||
new_x = self.x + distance * math.cos(math.radians(self.angle))
|
||||
new_y = self.y + distance * math.sin(math.radians(self.angle))
|
||||
canvas.line(self.x, self.y, new_x, new_y)
|
||||
self.x = new_x
|
||||
self.y = new_y
|
||||
# À compléter : mémorise ("forward", distance) dans self.moves
|
||||
|
||||
|
||||
pencil = Pencil()
|
||||
pencil.forward(100)
|
||||
pencil.turn(90)
|
||||
pencil.forward(50)
|
||||
print(pencil.moves)
|
||||
instruction:
|
||||
fr: "Dans `turn` et `forward`, ajoute chaque mouvement à `self.moves` sous forme de tuple. Le programme doit afficher la liste des trois mouvements."
|
||||
en: "In `turn` and `forward`, add each move to `self.moves` as a tuple. The program must show the list of the three moves."
|
||||
tests:
|
||||
- kind: stdout_equals
|
||||
value: "[('forward', 100), ('turn', 90), ('forward', 50)]\n"
|
||||
message:
|
||||
fr: "La liste doit être [('forward', 100), ('turn', 90), ('forward', 50)]."
|
||||
en: "The list must be [('forward', 100), ('turn', 90), ('forward', 50)]."
|
||||
- kind: drawing_segments
|
||||
value: "2"
|
||||
message:
|
||||
fr: "Le crayon doit toujours dessiner ses deux traits."
|
||||
en: "The pencil must still draw its two lines."
|
||||
hints:
|
||||
fr:
|
||||
- "Une liste se complète avec `append`. Le mouvement est un tuple : `(\"turn\", degrees)`."
|
||||
- "Dans `turn` : `self.moves.append((\"turn\", degrees))` ; dans `forward` : `self.moves.append((\"forward\", distance))`."
|
||||
en:
|
||||
- "A list grows with `append`. The move is a tuple: `(\"turn\", degrees)`."
|
||||
- "In `turn`: `self.moves.append((\"turn\", degrees))`; in `forward`: `self.moves.append((\"forward\", distance))`."
|
||||
solution: |
|
||||
import math
|
||||
import canvas
|
||||
|
||||
|
||||
class Pencil:
|
||||
def __init__(self):
|
||||
self.x = 0
|
||||
self.y = 0
|
||||
self.angle = 0
|
||||
self.moves = []
|
||||
|
||||
def turn(self, degrees):
|
||||
self.angle += degrees
|
||||
self.moves.append(("turn", degrees))
|
||||
|
||||
def forward(self, distance):
|
||||
new_x = self.x + distance * math.cos(math.radians(self.angle))
|
||||
new_y = self.y + distance * math.sin(math.radians(self.angle))
|
||||
canvas.line(self.x, self.y, new_x, new_y)
|
||||
self.x = new_x
|
||||
self.y = new_y
|
||||
self.moves.append(("forward", distance))
|
||||
|
||||
|
||||
pencil = Pencil()
|
||||
pencil.forward(100)
|
||||
pencil.turn(90)
|
||||
pencil.forward(50)
|
||||
print(pencil.moves)
|
||||
- type: explain
|
||||
voice: true
|
||||
text:
|
||||
fr: "Pour sauvegarder, on écrit un mouvement par ligne dans un fichier texte, par exemple `forward 100` puis `turn 90`. Souviens-toi : seul le dossier `data/` est conservé quand tu fermes la page. Une fonction qui reçoit la liste et le chemin du fichier rend le code réutilisable."
|
||||
en: "To save, we write one move per line in a text file, for example `forward 100` then `turn 90`. Remember: only the `data/` folder is kept when you close the page. A function that receives the list and the file path makes the code reusable."
|
||||
- type: code
|
||||
starter: |
|
||||
moves = [("forward", 100), ("turn", 90), ("forward", 50)]
|
||||
|
||||
|
||||
def save_moves(moves, path):
|
||||
# Écris un mouvement par ligne : « forward 100 », « turn 90 »…
|
||||
pass
|
||||
|
||||
|
||||
save_moves(moves, "data/pattern.txt")
|
||||
with open("data/pattern.txt") as file:
|
||||
print(file.read(), end="")
|
||||
instruction:
|
||||
fr: "Complète `save_moves` : elle écrit chaque mouvement sous la forme `nom valeur` sur sa propre ligne."
|
||||
en: "Complete `save_moves`: it writes each move as `name value` on its own line."
|
||||
tests:
|
||||
- kind: stdout_equals
|
||||
value: "forward 100\nturn 90\nforward 50\n"
|
||||
message:
|
||||
fr: "Le fichier doit contenir forward 100, turn 90 et forward 50, un par ligne."
|
||||
en: "The file must contain forward 100, turn 90 and forward 50, one per line."
|
||||
hints:
|
||||
fr:
|
||||
- "Ouvre le fichier en écriture avec `with open(path, \"w\") as file:` puis parcours `moves`."
|
||||
- "Pour chaque `name, value` de `moves`, écris `file.write(f\"{name} {value}\\n\")`."
|
||||
en:
|
||||
- "Open the file for writing with `with open(path, \"w\") as file:` then loop over `moves`."
|
||||
- "For each `name, value` in `moves`, write `file.write(f\"{name} {value}\\n\")`."
|
||||
solution: |
|
||||
moves = [("forward", 100), ("turn", 90), ("forward", 50)]
|
||||
|
||||
|
||||
def save_moves(moves, path):
|
||||
with open(path, "w") as file:
|
||||
for name, value in moves:
|
||||
file.write(f"{name} {value}\n")
|
||||
|
||||
|
||||
save_moves(moves, "data/pattern.txt")
|
||||
with open("data/pattern.txt") as file:
|
||||
print(file.read(), end="")
|
||||
- type: explain
|
||||
voice: true
|
||||
text:
|
||||
fr: "Pour recharger, on fait l'inverse : on lit chaque ligne, on la coupe en deux avec `split`, et on convertit la valeur en nombre avec `int`. La fonction renvoie la liste des mouvements, prête à être rejouée sur un crayon neuf."
|
||||
en: "To reload, we do the opposite: read each line, cut it in two with `split`, and convert the value to a number with `int`. The function returns the list of moves, ready to be replayed on a new pencil."
|
||||
- type: code
|
||||
starter: |
|
||||
def load_moves(path):
|
||||
# Lis le fichier et renvoie une liste de tuples (nom, valeur),
|
||||
# comme [("forward", 100), ("turn", 90)]
|
||||
pass
|
||||
|
||||
|
||||
with open("data/pattern.txt", "w") as file:
|
||||
file.write("forward 100\nturn 90\nforward 50\n")
|
||||
|
||||
print(load_moves("data/pattern.txt"))
|
||||
instruction:
|
||||
fr: "Complète `load_moves` : chaque ligne `nom valeur` devient un tuple `(nom, valeur)` avec la valeur convertie en entier."
|
||||
en: "Complete `load_moves`: each `name value` line becomes a `(name, value)` tuple with the value converted to an integer."
|
||||
tests:
|
||||
- kind: stdout_equals
|
||||
value: "[('forward', 100), ('turn', 90), ('forward', 50)]\n"
|
||||
message:
|
||||
fr: "La fonction doit renvoyer [('forward', 100), ('turn', 90), ('forward', 50)]."
|
||||
en: "The function must return [('forward', 100), ('turn', 90), ('forward', 50)]."
|
||||
hints:
|
||||
fr:
|
||||
- "Commence par `moves = []`, parcours `for line in file:` et ajoute chaque tuple avec `append`."
|
||||
- "`name, value = line.split()` coupe la ligne ; ajoute `(name, int(value))`. N'oublie pas `return moves`."
|
||||
en:
|
||||
- "Start with `moves = []`, loop with `for line in file:` and add each tuple with `append`."
|
||||
- "`name, value = line.split()` cuts the line; add `(name, int(value))`. Don't forget `return moves`."
|
||||
solution: |
|
||||
def load_moves(path):
|
||||
moves = []
|
||||
with open(path) as file:
|
||||
for line in file:
|
||||
name, value = line.split()
|
||||
moves.append((name, int(value)))
|
||||
return moves
|
||||
|
||||
|
||||
with open("data/pattern.txt", "w") as file:
|
||||
file.write("forward 100\nturn 90\nforward 50\n")
|
||||
|
||||
print(load_moves("data/pattern.txt"))
|
||||
mission:
|
||||
title:
|
||||
fr: Le triangle qui revient
|
||||
en: The triangle that comes back
|
||||
goal:
|
||||
fr: "Termine le projet : écris `replay(moves, pencil)`, qui applique chaque mouvement de la liste au crayon (`forward` ou `turn`). Le programme dessine un triangle bleu, le sauvegarde, efface la feuille, recharge le fichier et le redessine. À la fin, affiche « 6 mouvements rechargés » (le nombre vient de `len`) et la feuille ne doit montrer que 3 traits."
|
||||
en: "Finish the project: write `replay(moves, pencil)`, which applies each move in the list to the pencil (`forward` or `turn`). The program draws a blue triangle, saves it, clears the sheet, reloads the file and draws it again. At the end, show \"6 mouvements rechargés\" (the number comes from `len`) and the sheet must show only 3 lines."
|
||||
starter: |
|
||||
import math
|
||||
import canvas
|
||||
|
||||
|
||||
class Pencil:
|
||||
def __init__(self, color="black"):
|
||||
self.x = 0
|
||||
self.y = 0
|
||||
self.angle = 0
|
||||
self.color = color
|
||||
self.moves = []
|
||||
|
||||
def turn(self, degrees):
|
||||
self.angle += degrees
|
||||
self.moves.append(("turn", degrees))
|
||||
|
||||
def forward(self, distance):
|
||||
new_x = self.x + distance * math.cos(math.radians(self.angle))
|
||||
new_y = self.y + distance * math.sin(math.radians(self.angle))
|
||||
canvas.line(self.x, self.y, new_x, new_y, self.color)
|
||||
self.x = new_x
|
||||
self.y = new_y
|
||||
self.moves.append(("forward", distance))
|
||||
|
||||
|
||||
def save_moves(moves, path):
|
||||
with open(path, "w") as file:
|
||||
for name, value in moves:
|
||||
file.write(f"{name} {value}\n")
|
||||
|
||||
|
||||
def load_moves(path):
|
||||
moves = []
|
||||
with open(path) as file:
|
||||
for line in file:
|
||||
name, value = line.split()
|
||||
moves.append((name, int(value)))
|
||||
return moves
|
||||
|
||||
|
||||
def replay(moves, pencil):
|
||||
# À compléter : pour chaque (name, value), appelle forward ou turn
|
||||
pass
|
||||
|
||||
|
||||
# 1. Dessine un triangle bleu et sauvegarde-le
|
||||
pencil = Pencil("blue")
|
||||
for _ in range(3):
|
||||
pencil.forward(100)
|
||||
pencil.turn(120)
|
||||
save_moves(pencil.moves, "data/triangle.txt")
|
||||
|
||||
# 2. Efface la feuille, recharge le fichier et redessine
|
||||
canvas.clear()
|
||||
moves = load_moves("data/triangle.txt")
|
||||
new_pencil = Pencil("blue")
|
||||
# À compléter : rejoue les mouvements, puis affiche le nombre rechargé
|
||||
tests:
|
||||
- kind: drawing_segments
|
||||
value: "3"
|
||||
message:
|
||||
fr: "La feuille doit montrer exactement 3 traits : efface-la avant de redessiner (canvas.clear) et rejoue les mouvements."
|
||||
en: "The sheet must show exactly 3 lines: clear it before redrawing (canvas.clear) and replay the moves."
|
||||
- kind: drawing_has_line
|
||||
value: "0,0 100,0 blue"
|
||||
message:
|
||||
fr: "Le premier côté du triangle bleu doit être redessiné de (0, 0) à (100, 0)."
|
||||
en: "The first side of the blue triangle must be redrawn from (0, 0) to (100, 0)."
|
||||
- kind: drawing_has_line
|
||||
value: "100,0 50,86.6 blue"
|
||||
- kind: drawing_has_line
|
||||
value: "50,86.6 0,0 blue"
|
||||
message:
|
||||
fr: "Le triangle doit se refermer sur le point de départ."
|
||||
en: "The triangle must close back on the starting point."
|
||||
- kind: stdout_equals
|
||||
value: "6 mouvements rechargés\n"
|
||||
message:
|
||||
fr: "Il faut afficher exactement 6 mouvements rechargés."
|
||||
en: "It must show exactly 6 mouvements rechargés."
|
||||
- kind: code_contains
|
||||
value: len(moves)
|
||||
message:
|
||||
fr: "Compte les mouvements avec len(moves)."
|
||||
en: "Count the moves with len(moves)."
|
||||
solution: |
|
||||
import math
|
||||
import canvas
|
||||
|
||||
|
||||
class Pencil:
|
||||
def __init__(self, color="black"):
|
||||
self.x = 0
|
||||
self.y = 0
|
||||
self.angle = 0
|
||||
self.color = color
|
||||
self.moves = []
|
||||
|
||||
def turn(self, degrees):
|
||||
self.angle += degrees
|
||||
self.moves.append(("turn", degrees))
|
||||
|
||||
def forward(self, distance):
|
||||
new_x = self.x + distance * math.cos(math.radians(self.angle))
|
||||
new_y = self.y + distance * math.sin(math.radians(self.angle))
|
||||
canvas.line(self.x, self.y, new_x, new_y, self.color)
|
||||
self.x = new_x
|
||||
self.y = new_y
|
||||
self.moves.append(("forward", distance))
|
||||
|
||||
|
||||
def save_moves(moves, path):
|
||||
with open(path, "w") as file:
|
||||
for name, value in moves:
|
||||
file.write(f"{name} {value}\n")
|
||||
|
||||
|
||||
def load_moves(path):
|
||||
moves = []
|
||||
with open(path) as file:
|
||||
for line in file:
|
||||
name, value = line.split()
|
||||
moves.append((name, int(value)))
|
||||
return moves
|
||||
|
||||
|
||||
def replay(moves, pencil):
|
||||
for name, value in moves:
|
||||
if name == "forward":
|
||||
pencil.forward(value)
|
||||
else:
|
||||
pencil.turn(value)
|
||||
|
||||
|
||||
pencil = Pencil("blue")
|
||||
for _ in range(3):
|
||||
pencil.forward(100)
|
||||
pencil.turn(120)
|
||||
save_moves(pencil.moves, "data/triangle.txt")
|
||||
|
||||
canvas.clear()
|
||||
moves = load_moves("data/triangle.txt")
|
||||
new_pencil = Pencil("blue")
|
||||
replay(moves, new_pencil)
|
||||
print(len(moves), "mouvements rechargés")
|
||||
reward_sound: level_unlocked
|
||||
@@ -13,6 +13,8 @@
|
||||
{ "id": "09-dicts", "requires": ["08-functions"] },
|
||||
{ "id": "10-files", "requires": ["09-dicts"] },
|
||||
{ "id": "11-libraries", "requires": ["10-files"] },
|
||||
{ "id": "12-errors", "requires": ["11-libraries"] }
|
||||
{ "id": "12-errors", "requires": ["11-libraries"] },
|
||||
{ "id": "13-classes", "requires": ["12-errors"] },
|
||||
{ "id": "14-project", "requires": ["13-classes"] }
|
||||
]
|
||||
}
|
||||
|
||||
@@ -118,12 +118,15 @@
|
||||
"var_equals",
|
||||
"var_type_is",
|
||||
"code_contains",
|
||||
"drawing_segments",
|
||||
"drawing_has_line",
|
||||
"drawing_colors",
|
||||
"function_called_with",
|
||||
"no_syntax_error"
|
||||
]
|
||||
},
|
||||
"value": {
|
||||
"description": "Valeur attendue, dont la forme dépend de 'kind' (string, regex, nom de variable + valeur...)."
|
||||
"description": "Valeur attendue, dont la forme dépend de 'kind' (string, regex, nom de variable + valeur...). Dessin (canvas.line) : drawing_segments '4' (exactement) ou '4+' (au moins) ; drawing_has_line '0,0 100,0' ou '0,0 100,0 red' (sens libre, tolérance 0,5) ; drawing_colors 'red,blue'."
|
||||
},
|
||||
"message": {
|
||||
"$ref": "#/$defs/i18nString",
|
||||
|
||||
Reference in New Issue
Block a user