Skip to content
This repository was archived by the owner on Nov 7, 2026. It is now read-only.

Commit 6268170

Browse files
Web: Code live auch in Python (#71)
Dritter Umschalter Python: leere Anweisung = pass, leere Blöcke = pass # Dein Code, if Bedingung:, unvollständige Zählschleife als for … in range(Start, Ende):. Claude-Session: https://claude.ai/code/session_01Ej8WiXwHqbpcLApU1GzAn2 Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6ff0794 commit 6268170

47 files changed

Lines changed: 822 additions & 701 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎web/src/core/codeGenerator.ts‎

Lines changed: 49 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -912,8 +912,8 @@ function forcedCaseComment(name: string, target: CodeTarget): string {
912912
function emitInstructionLike(textLines: string[], target: CodeTarget, options: CodeOptions, indent: number, sink: Sink) {
913913
const body = textLines.map((l) => l.trim())
914914
if (body.every((l) => l === '')) {
915-
// Neue, noch leere Anweisung: in Java eine leere Anweisung.
916-
if (options.live) sink.out += sp(indent) + ';\n'
915+
// Neue, noch leere Anweisung: eine leere Anweisung (Python: `pass`).
916+
if (options.live) sink.out += sp(indent) + (target === 'python' ? 'pass' : ';') + '\n'
917917
return
918918
}
919919
if (options.includeDiagramTextAsComments) {
@@ -1123,6 +1123,8 @@ function emitElement(element: VSElement, target: CodeTarget, options: CodeOption
11231123
for (const el of element.loopBody ?? []) emit(el, target, options, indent + step, sink)
11241124
sink.out += sp(indent + step) + pythonStatementLine(loop.increment, ints) + '\n'
11251125
return
1126+
} else if (options.live) {
1127+
sink.out += sp(indent) + livePythonForLoopHeaderText(element.textLines, options.live.labels, ints) + '\n'
11261128
} else {
11271129
header('for ', ':\n')
11281130
}
@@ -1153,7 +1155,8 @@ function emitElement(element: VSElement, target: CodeTarget, options: CodeOption
11531155
const bodyStart = indent + step
11541156
body(element.loopBody ?? [], bodyStart)
11551157
commentIfWanted(bodyStart)
1156-
sink.out += sp(bodyStart) + 'if not (' + pythonExpression(cond, options.jsIntVariables ?? new Set()) + '):\n'
1158+
const expression = cond.includes(livePlaceholderStart) ? cond : pythonExpression(cond, options.jsIntVariables ?? new Set())
1159+
sink.out += sp(bodyStart) + 'if not (' + expression + '):\n'
11571160
sink.out += sp(bodyStart + step) + 'break\n'
11581161
} else {
11591162
sink.out += sp(indent) + 'do {\n'
@@ -1190,6 +1193,8 @@ export interface LiveLabels {
11901193
code: string
11911194
start: string
11921195
step: string
1196+
/** Obergrenze von `range(…)` in Python. */
1197+
end: string
11931198
}
11941199

11951200
/** Zeilen eines Elements im erzeugten Code (ab 0, `to` einschließlich). */
@@ -1206,13 +1211,16 @@ export interface LiveCode {
12061211
}
12071212

12081213
interface LiveContext {
1214+
target: LiveTarget
12091215
labels: LiveLabels
12101216
paths: Map<VSElement, number[]>
12111217
spans: LiveSpan[]
12121218
}
12131219

12141220
const livePlaceholderText = (label: string) => livePlaceholderStart + label + livePlaceholderEnd
1215-
const livePlaceholderLine = (indent: number, live: LiveContext) => sp(indent) + livePlaceholderText('// ' + live.labels.code) + '\n'
1221+
/** Leerer Block: `// Dein Code`; Python braucht dort eine Anweisung, also `pass # Dein Code`. */
1222+
const livePlaceholderLine = (indent: number, live: LiveContext) =>
1223+
sp(indent) + livePlaceholderText(live.target === 'python' ? `pass # ${live.labels.code}` : `// ${live.labels.code}`) + '\n'
12161224
const isBlank = (lines: string[]) => lines.every((l) => l.trim() === '')
12171225

12181226
/** `for (Startwert; Bedingung; Schritt)`: leere Felder werden zu Platzhaltern. */
@@ -1237,6 +1245,26 @@ function liveJavaScriptForLoopHeaderText(lines: string[], labels: LiveLabels): s
12371245
return parts.join(';')
12381246
}
12391247

1248+
/**
1249+
* Unvollständige Zählschleife in Python: `for i in range(Start, Ende):`, fehlende Teile als Platzhalter.
1250+
* (Vollständige Köpfe übersetzt `pythonForLoop`.)
1251+
*/
1252+
function livePythonForLoopHeaderText(lines: string[], labels: LiveLabels, intVariables: Set<string>): string {
1253+
const [initS = '', condS = '', stepS = ''] = lines.length === 3 ? lines.map((l) => stripTrailingSemicolon(l)) : []
1254+
const init = groups(/^\s*(?:integer|int|long|short|byte|double|float)?\s*([a-zA-Z_]\w*)\s*=\s*(.+)$/i, initS)
1255+
const name = init?.[1] ?? groups(/^\s*([a-zA-Z_]\w*)\s*(?:<=|<|>=|>)/, condS)?.[1]
1256+
const start = init ? pythonExpression(init[2], intVariables) : livePlaceholderText(labels.start)
1257+
const cond = groups(/^\s*(\w+)\s*(<=|<)\s*(.+)$/, condS)
1258+
let stop = livePlaceholderText(labels.end)
1259+
if (cond && (name === undefined || cond[1] === name)) {
1260+
stop = pythonExpression(cond[3], intVariables)
1261+
if (cond[2] === '<=') stop = shiftedBound(stop, 1)
1262+
}
1263+
const step = name === undefined ? undefined : forLoopStepSize(stepS, name)
1264+
const args = [start, stop, ...(step !== undefined && step !== 1 ? [String(step)] : [])]
1265+
return `for ${name ?? livePlaceholderText(labels.selector)} in range(${args.join(', ')}):`
1266+
}
1267+
12401268
/** Pfade wie in `editing.ts`: `[i, Zweig, j, …]`, Schleifenrumpf = Zweig 0. */
12411269
function elementPaths(elements: VSElement[], prefix: number[] = [], out = new Map<VSElement, number[]>()) {
12421270
elements.forEach((e, i) => {
@@ -1256,31 +1284,41 @@ function recordLiveSpan(options: CodeOptions, element: VSElement, sink: Sink, st
12561284
live.spans.push({ path, from: lineAt(start), to: lineAt(sink.out.length - 1) })
12571285
}
12581286

1259-
/** Zielsprachen der Ansicht „Code live“ (Python folgt). */
1260-
export type LiveTarget = 'java' | 'javascript'
1287+
/** Zielsprachen der Ansicht „Code live“. */
1288+
export type LiveTarget = 'java' | 'javascript' | 'python'
12611289

12621290
/**
12631291
* Code für die Ansicht „Code live“: wie das Code-Snippet, aber für Anfänger lesbar, solange noch etwas fehlt
12641292
* (leere Anweisung `;`, `if (Bedingung)`, `// Dein Code` in leeren Blöcken), und mit den Zeilen jedes Elements.
12651293
*/
12661294
export function generateLiveCode(document: VSDocument, target: LiveTarget, labels: LiveLabels): LiveCode {
1267-
const live: LiveContext = { labels, paths: elementPaths(document.elements), spans: [] }
1295+
const live: LiveContext = { target, labels, paths: elementPaths(document.elements), spans: [] }
12681296
const opts = documentOptions(document, target, { includeEmptyElseBranch: true, live })
12691297
const header = parseSubprogramHeader(document.caption)
12701298
let prelude = ''
12711299
if (target === 'java') {
12721300
if (documentContainsJavaInput(document)) prelude += '// import java.util.Scanner;\nScanner scanner = new Scanner(System.in);\n\n'
12731301
if (header) prelude += javaMethodHeader(header) + '\n'
12741302
} else {
1275-
prelude += '"use strict";\n\n'
12761303
if (header) {
1277-
for (const p of header.params) if (!p.dims && p.type === 'int') opts.jsIntVariables!.add(p.name)
1278-
prelude += `function ${header.name}(${header.params.map((p) => p.name).join(', ')}) {\n`
1304+
for (const p of header.params) {
1305+
if (p.dims) continue
1306+
if (p.type === 'int') opts.jsIntVariables!.add(p.name)
1307+
if (p.type === 'string') opts.stringVariables!.add(p.name)
1308+
}
1309+
}
1310+
const names = header?.params.map((p) => p.name).join(', ')
1311+
if (target === 'javascript') {
1312+
prelude += '"use strict";\n\n'
1313+
if (header) prelude += `function ${header.name}(${names}) {\n`
1314+
} else {
1315+
if (documentContainsJavaMathRandom(document)) prelude += 'import random\n\n'
1316+
if (header) prelude += `def ${header.name}(${names}):\n`
12791317
}
12801318
}
12811319
const sink = { out: '' }
12821320
emitBlockBody(document.elements, target, opts, header ? opts.indentPerLevel : 0, sink)
1283-
if (header) sink.out += '}\n'
1321+
if (header && target !== 'python') sink.out += '}\n'
12841322
const offset = prelude.split('\n').length - 1
12851323
return {
12861324
text: postProcessLengthSyntax((prelude + sink.out).replace(/\n+$/, ''), target),

‎web/src/i18n/ar.strings‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,4 @@
5656
"web_live_hint" = "تنمو الشيفرة مع مخططك. الرمادي = عنصر نائب: اكتب في المفتش ليظهر نصك هنا. انقر على سطر لتحديد عنصره.";
5757
"web_live_ph_selector" = "المتغير";
5858
"web_live_ph_code" = "شيفرتك";
59+
"web_live_ph_end" = "النهاية";

‎web/src/i18n/da.strings‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,4 @@
5656
"web_live_hint" = "Koden vokser med dit diagram. Gråt = pladsholder: skriv i inspektøren, så vises teksten her. Klik på en linje for at vælge elementet.";
5757
"web_live_ph_selector" = "variabel";
5858
"web_live_ph_code" = "Din kode";
59+
"web_live_ph_end" = "slut";

‎web/src/i18n/de.strings‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,3 +114,4 @@
114114
"web_live_hint" = "Der Code wächst mit deinem Struktogramm. Grau = Platzhalter: Schreib im Objektinspektor, dann steht dort dein Text. Klick auf eine Zeile markiert das Element.";
115115
"web_live_ph_selector" = "Variable";
116116
"web_live_ph_code" = "Dein Code";
117+
"web_live_ph_end" = "Ende";

‎web/src/i18n/el.strings‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,4 @@
5656
"web_live_hint" = "Ο κώδικας μεγαλώνει μαζί με το διάγραμμα. Γκρι = σύμβολο κράτησης: γράψε στον επιθεωρητή και το κείμενό σου εμφανίζεται εδώ. Κάνε κλικ σε μια γραμμή για να επιλέξεις το στοιχείο.";
5757
"web_live_ph_selector" = "μεταβλητή";
5858
"web_live_ph_code" = "Ο κώδικάς σου";
59+
"web_live_ph_end" = "τέλος";

‎web/src/i18n/en.strings‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,3 +114,4 @@
114114
"web_live_hint" = "The code grows with your diagram. Grey = placeholder: type in the object inspector and your text appears there. Click a line to select its element.";
115115
"web_live_ph_selector" = "variable";
116116
"web_live_ph_code" = "Your code";
117+
"web_live_ph_end" = "end";

‎web/src/i18n/es.strings‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,4 @@
5656
"web_live_hint" = "El código crece con tu diagrama. Gris = marcador: escribe en el inspector y tu texto aparecerá ahí. Haz clic en una línea para seleccionar su elemento.";
5757
"web_live_ph_selector" = "variable";
5858
"web_live_ph_code" = "Tu código";
59+
"web_live_ph_end" = "fin";

‎web/src/i18n/fr.strings‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,4 @@
5656
"web_live_hint" = "Le code évolue avec ton diagramme. Gris = espace réservé : écris dans l’inspecteur et ton texte apparaît ici. Clique sur une ligne pour sélectionner son élément.";
5757
"web_live_ph_selector" = "variable";
5858
"web_live_ph_code" = "Ton code";
59+
"web_live_ph_end" = "fin";

‎web/src/i18n/he.strings‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,4 @@
5656
"web_live_hint" = "הקוד גדל יחד עם התרשים. אפור = ממלא מקום: כתבו במפקח והטקסט יופיע כאן. לחצו על שורה כדי לבחור את הרכיב.";
5757
"web_live_ph_selector" = "משתנה";
5858
"web_live_ph_code" = "הקוד שלך";
59+
"web_live_ph_end" = "סוף";

‎web/src/i18n/it.strings‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,4 @@
5656
"web_live_hint" = "Il codice cresce con il tuo diagramma. Grigio = segnaposto: scrivi nell’ispettore e il tuo testo appare qui. Clicca su una riga per selezionarne l’elemento.";
5757
"web_live_ph_selector" = "variabile";
5858
"web_live_ph_code" = "Il tuo codice";
59+
"web_live_ph_end" = "fine";

0 commit comments

Comments
 (0)