PyLogo Exemple de primitives logo imlémentées   - https://turing.cs.hbg.psu.edu/LOCAL/ucblogo/ucbl_7.htm   - https://fmslogo.sourceforge.io/manual/workspace-control.html   - https://www.calormen.com/jslogo/language.html The section numbers are per the Berkeley Logo Reference Manual in Brian Harvey's Computer Science Logo Style volume 2: Advanced Techniques for ease of comparison. Data Types and Syntax Data Structure Primitives Communication Arithmetic Logical Operations Graphics Workspace Management Control Structures Data Types and Syntax " word ' word number Word. (Quoted words are terminated by [](){} or whitespace, \ to escape.) show "hello show "hello\ logo show 12.34 : variable Input definition/variable reference show :name [ word ... ] List of words or lists, whitespace separated show [1 2 3] { word ... } { word ... }@ origin Array of words, whitespace separated show {1 2 3} ( expression ) Parenthesis can be used to group expressions show ( 1 + 2 ) * 3 procedure input ... Call procedure with default number of inputs show "hello ( procedure input ... ) Call procedure with an arbitrary number of inputs (show "hello :name) 2. Data Structure Primitives 2.1 Constructors word expr expr (word expr ... ) Concatenate two (or more) words into one word show (word "a "b "c) list thing1 thing2 (list thing1 thing2 ...) Create a new list from the inputs show (list 1+2 2+3 3+4) sentence thing1 thing2 (sentence thing1 thing2 ...) se thing1 thing2 (se thing1 thing2 ...) Create a new list from the inputs (if non-lists) or members of the inputs (if lists) show sentence [1 2 3] [and so on] fput thing list lput thing list Outputs list, but with thing added as a new first/last item; if list is a word, concatenates show fput 0 [ 1 2 3 ] show fput "a "bcd show lput 4 [ 1 2 3 ] show lput "e "bcd array size (array size origin ) Create a new array. The default origin is 1. show array 10 mdarray [ dimensions ...] (mdarray [ dimensions ...] origin ) Create a new multi-dimensional array. The default origin is 1. show mdarray [2 2] listtoarray list (listtoarray list origin ) Create a new array populated by members of a list show listtoarray [ 1 3 5 7 ] arraytolist array Create a new list populated by members of a array show arraytolist { 2 4 6 8 } combine thing1 thing2 If thing2 is a word, like word ; otherwise, like fput show combine "a [b c] reverse list Outputs a list with the items in reverse order; if input is a word, reverses characters show reverse [ 1 2 3 ] show reverse "abc gensym Outputs a unique string, e.g. G1 , G2 , etc. show gensym 2.2 Data Selectors first list last list Outputs the first or last item (or character) from the list (or word), respectively show first [ 1 2 3 ] show first "abc show last [ 1 2 3 ] show last "abc firsts listoflists Outputs a list of the first item (or character) of each sublist (or word) show firsts [ [1 2 3] [a b c] ] show firsts [ abc def ] butfirst list bf list butlast list bl list Outputs the list (or word), except for the first/last item (or character) show butfirst [ 1 2 3 ] show butfirst "abc show butlast [ 1 2 3 ] show butlast "abc butfirsts listoflists bfs listoflists Outputs a list of sublists (or words) without the first item (or characters) show butfirsts [ [ 1 2 3 ] [ a b c ] ] show butfirsts [ abc def ] item index thing Outputs the indexth item of the list or array or word show item 2 [ 1 2 3 ] show item 2 "abc mditem [ index ...] thing Outputs an item from a multi-dimensional array show mditem [2 1] {{a b} {c d}} pick list Outputs one item from a list (or word), at random show pick [ 1 2 3 ] show pick "abc remove thing list Outputs the list (or word) with any occurences of thing removed show remove "b [ a b c ] show remove "a "banana remdup list Outputs the list (or word) with duplicates removed show remdup [ 1 2 3 2 3 4 3 4 5 ] show remdup "banana quoted thing Outputs thing with " prepended if a word, or just thing otherwise. show quoted "abc split thing list Outputs the list split into a list of lists (or list of words) wherever thing appears. show split "a "banana show split 3 [1 2 3 4 1 2 3 4] 2.3 Data Mutators setitem index array value Sets the indexth item of the array to value (circular arrays prevented) make "a { 1 2 3 } setitem 2 :a "x show :a mdsetitem [ index ...] array value Sets an item in a multi-dimensional array to value (circular arrays prevented) make "a {{1 2} {3 4}} mdsetitem [2 1] :a "x show :a .setfirst list value Sets the first item of the list to value make "a [ 1 2 3 ] .setfirst :a "7 show :a .setbf list value Sets the 'butfirst' of the list to the items in value (a list) make "a [ 1 2 3 ] .setbf :a [ 4 9 ] show :a .setitem index array value Sets the indexth item of the array to value (circular arrays allowed) make "a { 1 2 3 } setitem 2 :a "x show :a push stackname thing pop stackname Push to/pop from a stack i.e. list variable. Stacks grow from the front. Works on words. make "s [ 2 1 ] push "s 3 show :s show pop "s make "s "ba push "s "c show :s show pop "s queue stackname thing dequeue stackname Add/remove from a queue i.e. list variable, Queues grow from the end. Works on words. make "q [ 1 2 ] queue "q 3 show :q show dequeue "q make "q "ab queue "q "c show :q show dequeue "q 2.4 Predicates Predicates return 1 (true) or 0 (false) wordp thing word? thing listp thing list? thing arrayp thing array? thing numberp thing number? thing Test if thing is a word, list, array, or number respectively. emptyp expr empty? expr Test if thing is an empty list or empty string. equalp expr expr equal? expr expr expr = expr notequalp expr expr notequal? expr expr expr <> expr Equality/inequality tests. Compares strings, numbers, or lists (equal if length and all members are equal). beforep thing1 thing2 before? thing1 thing2 Test string collation order. .eq thing1 thing2 Test if things have the same identity. memberp thing list member? thing list Test if thing is equal to any member of list. substringp thing1 thing2 substring? thing1 thing2 Test if thing1 is a substring of thing2. 2.5 Queries count thing Outputs length of a list or number of characters in a string show count [ 1 2 3 ] show count "hello ascii expr Outputs ASCII (actually, Unicode) code point for first character of string show ascii "abc char expr Outputs Unicode character at specified code point show char 97 member thing list Outputs the list (or word) from the first occurence of thing to the end, or empty list (or word) show member "a "banana show member 2 [1 2 3 4] uppercase expr lowercase expr Outputs string converted to upper/lowercase show uppercase "abc show lowercase "ABC standout expr Outputs string with alphanumeric characters in bold show standout "ABCabc123 parse word Outputs word parsed as a list. show parse "1+2 runparse word Outputs word parsed as instructions. show runparse "1+2 3. Communication 3.1 Transmitters print thing pr thing ( print thing1 thing2 ...) ( pr thing1 thing2 ...) Print inputs to the text screen, separated by spaces, and followed by a newline. Square brackets are only put around sublists. print "hello type thing ( type thing1 thing2 ...) Like print but with no trailing newline. type "hel type "lo show thing ( show thing1 thing2 ...) Like print but with square brackets around list inputs. show "hello 3.2 Receivers readlist (readlist promptstr ) Prompt the user for a line of input. The result is a list of words. show readlist make "colors (readlist [Type some colors:]) show :colors readword (readword promptstr ) Prompt the user for a line of input. The result (including spaces) is the single word output. show readword make "name (readword [What is your name?]) show :name 3.4 Terminal Access cleartext ct Clear the text screen. settextcolor color Change the text color. textcolor Output the current text color. increasefont decreasefont Increase/decrease the text size. settextsize height Change the text size (in pixels). textsize Output the current text size (in pixels). setfont name Change the text font. font Output the current text font. 4. Arithmetic 4.1 Numeric Operations Inputs are numbers or numeric expressions, output is a number. sum expr expr (sum expr ... ) expr + expr difference expr expr expr - expr product expr expr (product expr ... ) expr * expr quotient expr expr (quotient expr ) expr / expr power expr expr expr ^ expr Add, subtract, multiply, divide, and raise-to-the-power-of respectively. A single input to quotient returns the reciprocal. remainder expr expr expr % expr modulo expr expr Outputs the remainder (modulus). For remainder and % the result has the same sign as the first input; for modulo the result has the same sign as a the second input. minus expr - expr Unary minus sign must begin a top-level expression, follow an infix operator, or have a leading space and no trailing space. abs num Absolute value int num round num Truncate or round a number, respectively. sqrt expr exp expr log10 expr ln expr Square root, e to the power of, common logarithm, and natural logarithm, respectively. arctan expr (arctan x y ) sin expr cos expr tan expr The usual trig functions. Angles are in degrees. radarctan expr (radarctan x y ) radsin expr radcos expr radtan expr The usual trig functions. Angles are in radians. iseq first last Outputs a list with integers from first to last , inclusive show iseq 1 10 rseq first last count Outputs a list of count numbers from first to last , inclusive show rseq 1 9 5 4.2 Numeric Predicates lessp expr expr less? expr expr expr < expr greaterp expr expr greater? expr expr expr > expr lessequalp expr expr lessequal? expr expr expr <= expr greaterequalp expr expr greaterequal? expr expr expr >= expr Less than, greater than, less than or equal to, greater than or equal to, respectively. Inputs are numbers or numeric expressions, output is 1 (true) or 0 (false). 4.3 Random Numbers random expr (random start end ) Outputs a random number from 0 through one less than expr , or from start to end inclusive. show random 10 show (random 1 6) rerandom ( rerandom expr ) Reseeds the random number generator, either to a fixed value or the specified seed. 4.4 Print Formatting form expr width precision Outputs a formatted string with the result of a numeric expression with precision decimal places and padded on the left with spaces (if necessary) to be at least width characters long. show form 1/3 10 3 4.5 Bitwise Operations bitand expr expr (bitand expr ...) bitor expr expr (bitor expr ...) bitxor expr expr (bitxor expr ...) bitnot expr Bitwise and, or, exclusive-or, and not, respectively. ashift expr bitcount Arithmetic bit shift. If bitcount is negative, shifts to the right, preserving sign. lshift expr bitcount Logical bit shift. If bitcount is negative, shifts to the right, zero-filling. 5. Logical Operations true Outputs 1 false Outputs 0 and expr expr (and expr ... ) or expr expr (or expr ... ) xor expr expr (xor expr ... ) not expr Logical "and", "or", "exclusive-or", and "not", respectively. Inputs are numbers or numeric expressions, output is 1 (true) or 0 (false). 6. Graphics An introduction to Turtle Geometry . 6.1 Turtle Motion forward expr fd expr Move turtle forward expr pixels fd 100 back expr bk expr Move turtle backward expr pixels bk 100 left expr lt expr Rotate expr degrees counterclockwise lt 90 right expr rt expr Rotate expr degrees clockwise rt 90 setpos [ expr expr ] setxy expr expr setx expr sety expr Move turtle to the specified location setpos [ 100 -100 ] setxy -100 100 setheading expr seth expr Rotate the turtle to the specified heading setheading 45 home Moves the turtle to center, pointing upwards arc angle radius Without moving the turtle, draws an arc centered on the turtle, starting at the turtle's heading. arc 180 100 6.2 Turtle Motion Queries pos xcor ycor Outputs the current turtle position as [ x y ], x or y respectively show pos heading Outputs the current turtle heading show heading towards [ expr expr ] Outputs the heading towards the specified [ x y ] coordinates show towards [ 0 0 ] scrunch Outputs the current graphics scaling factors show scrunch bounds Outputs the current graphics screen bounds [ xmin xmax ymin ymax ] show bounds 6.3 Turtle and Window Control showturtle st Show the turtle hideturtle ht Hide the turtle clean Clear the drawing area clearscreen cs Same as clean and home together wrap If the turtle moves off the edge of the screen it will continue on the other side. (default) window The turtle can move past the edges of the screen, unbounded. fence If the turtle attempts to move past the edge of the screen it will stop. fill Does a paint bucket flood fill at the turtle's position. arc 360 100 fill filled fillcolor [ statements ... ] Execute statements without drawing but keeping track of turtle movements. When complete, fill the region traced by the turtle with fillcolor and outline the region with the current pen style. filled "red [ repeat 5 [ fd 100 rt 144 ] ] label expr Draw a word (same logic as print ) on the graphics display at the turtle location repeat 8 [ label "Logo rt 45 ] setlabelheight expr Set the height for text drawn by label , in pixels setlabelheight 100 label "Logo setlabelfont expr Set the font for text drawn by label setlabelfont "Times\ New\ Roman label "Logo setscrunch sx sy Set the graphics scaling factors setscrunch 1 2 arc 360 100 setturtle index Switch to the turtle numbered index (starting from 1 for the default turtle present at start). If the turtle has not been used yet, it will be created at the center, facing upwards, visible, with the pen down. setturtle 2 rt 90 fd 100 ask turtleindex [ statements ... ] Execute statements as turtle number turtleindex . ask 2 [ rt 90 fd 100 ] clearturtles Remove all turtles, keeping the current one as index 1. fd 50 setturtle 2 rt 90 fd 100 clearturtles 6.4 Turtle and Window Queries shownp shown? Outputs 1 if the turtle is shown, 0 if the turtle is hidden turtlemode Outputs WRAP , WINDOW or FENCE labelsize Outputs the height of text drawn by label , in pixels labelfont Outputs the name of the font drawn by label turtle Outputs the index of the currently-active turtle turtles Outputs the largest index that has been passed to setturtle 6.5 Pen and Background Control pendown pd Turtle resumes leaving a trail penup pu Turtle stops leaving a trail penpaint ppt penerase pe penreverse px Change the turtle drawing mode - paint (the default) leaves a colored trail, erase restores the background, reverse inverts the background. setpw 10 px repeat 5 [ fd 100 rt 144 ] setpencolor logocolor setpencolor csscolor setpencolor [ r g b ] Set pen/text color. Color can be a standard Logo color number (0-15), CSS color string ( CSS color names or #rrggbb ), or in the list version, r/g/b values in 0...99. The standard Logo colors are: 0 black 1 blue 2 green 3 cyan 4 red 5 magenta 6 yellow 7 white 8 brown 9 tan 10 green 11 aqua 12 salmon 13 purple 14 orange 15 gray setpencolor 4 setpencolor "red setpencolor "#ff0000 setpencolor [ 99 0 0 ] setpalette colornumber csscolor setpalette colornumber [ r g b ] Change one of the standard color entries (8 or above) to the given color. setpalette 8 "pink setbg 8 setpalette 8 "#ff4f00 setbg 8 setpalette 8 [ 99 31 0 ] setbg 8 setpensize expr Set pen width in pixels. If expr is a list, the first member is used. setbackground color setscreencolor color setsc color Set the background color; same options as setpencolor setbackground "red 6.6 Pen Queries pendownp pendown? Outputs 1 if the pen is down, 0 otherwise show pendown? penmode Outputs PAINT , ERASE or REVERSE show penmode pencolor pc Outputs the current pen color. This will be a CSS color string, not necessarily the value passed in. show pencolor palette colornumber Outputs the a palette entry. This will be a CSS color string, not necessarily the value passed in. show palette 8 pensize Outputs a two element list with the pen width and height (usually the same). show pensize background bg getscreencolor getsc Outputs the background color. This will be a CSS color string, not necessarily the value passed in. show background 6.7 Bitmap Operations bitcut width height Copy a bitmap, from the turtle's position width by height pixels. bitpaste Paste the previously copied bitmap at the current turtle position. repeat 4 [ rt 90 fd 40 ] bitcut 50 50 pu fd 100 bitpaste 6.8 Mouse/Touch Queries mousepos Outputs a list of the x, y coordinates of the last mouse position forever [setpos mousepos] clickpos Outputs a list of the x, y coordinates of the last mouse press forever [setpos clickpos] buttonp button? Outputs 1 if any mouse button is down, 0 otherwise. forever [ifelse button? [pd] [pu] setpos mousepos] button Outputs a number indicating the pressed mouse buttons ( 1 = left, 2 = right, etc) or 0 for none. touches Outputs a list of current touch coordinates forever [ifelse count touches [setpos first touches pendown] [penup]] 7. Workspace Management 7.1 Procedure Definition to procname inputs ... statements ... end Define a new named procedure. Inputs can be: Required: :a :b Optional (with default values): [:c 5] [:d 7] Rest (remaining inputs as a list): [:r] Default number of inputs: 3 to star :n repeat 5 [ fd :n rt 144 ] end define procname [[ inputs ...][ statements ...]] Define a new named procedure with optional inputs define "star [[n][repeat 5 [fd :n rt 144]]] def procname Outputs the definition of a named procedure as a string show def "star text procname Outputs the definition of a named procedure as a list, suitable for use with DEFINE show text "star copydef newname oldname Copy a procedure. If a procedure newname already existed it will be overridden. Primitive procedures can't be overridden unless REDEFP is TRUE . copydef "new "old 7.2 Variable Definition make varname expr Update a variable or define a new global variable. The variable name must be quoted make "myvar 5 name expr varname Like make but with the inputs reversed name 5 "myvar local varname (local varname ...) A subsequent make will create the variable(s) in the local scope instead of the global scope local "myvar localmake varname expr Define a variable in the local scope (shortcut for local then make localmake "myvar 5 thing varname Outputs the value of variable. :foo is a shortcut for thing "foo show thing "myvar global varname Reserve the variable at the global scope. This doesn't do anything useful. global "myvar 7.3 Property Lists pprop plistname propname value Set the property propname in the property list plistname to value value. gprop plistname propname Get the value of the property propname in the property list plistname , or the empty list if no such property. remprop plistname propname Remove the property propname in the property list plistname . plist plistname Return a list of properties in the property list plistname , alternating property name, property value. 7.4 Workspace Predicates Predicates return 1 (true) or 0 (false) procedurep name procedure? name Test if there is a procedure with the given name. primitivep name primitive? name Test if there is a built-in procedure with the given name. definedp name defined? name Test if there is a user-defined procedure with the given name. namep name name? name Test if there is a variable with the given name. plistp name plist? name Test if there is a property list with the given name. 7.5 Workspace Queries contents Outputs a list with three members. The first is a list of user-defined procedure names. The second is a list of defined variables. The third is a list of non-empty property list names. Only non-buried procedures, variables, and property lists are included. buried Outputs a list with three members. The first is a list of user-defined procedure names The second is a list of defined variables. The third is a list of non-empty property list names. Only buried procedures, variables, and property lists are included. procedures Outputs a list of user-defined non-buried procedure names. primitives Outputs a list of primitive non-buried procedure names. globals Outputs a list of defined non-buried global variables. names Outputs a list with two members. The first is an empty list. The second is a list of defined non-buried variables. plists Outputs a list with three members. The first is an empty list. The second is an empty list. The third is a list of non-empty non-buried property list names. namelist name namelist namelist Return a contents -style list with the given variable names. pllist plname pllist plnamelist Return a contents -style list with the given property lists. arity procname Return a list with the procedure's minimum, default, and maximum number of inputs; maximum is -1 if unlimited. 7.7 Workspace Control erase contentslist Takes a three member list, where the first is a list of user-defined procedure names to erase, the second is a list of defined variables to erase, the third is a list of property lists to erase. Primitive procedures can't be erased unless REDEFP is TRUE . erase [ [myproc] [myvar] [] ] erall Erase all non-buried user-defined procedures, variables and property lists. erps Erase all non-buried user-defined procedures. erns Erase all non-buried variables. erpls Erase all non-buried property lists. ern varname ern varnamelist Erase the named variable(s). epl plname epl plnamelist Erase the named property list(s). bury contentslist Takes a three member list, where the first is a list of user-defined procedure names to bury, the second is a list of defined variables to bury, the third is a list of property lists to bury. buryall Bury all user-defined procedures, variables, and property lists. buryname varname buryname varnamelist Bury the given variable (or list of variables). unbury contentslist Takes a three member list, where the first is a list of user-defined procedure names to unbury, the second is a list of defined variables to unbury, the third is a list of property lists to unbury. unburyall Unbury all user-defined procedures, variables, and property lists. unburyname varname unburyname varnamelist Unbury the given variable (or list of variables). buriedp contentslist buried? contentslist Return 1 if the first named user-defined procedure, variable, or property list exists and is buried, 0 otherwise. 8. Control Structures 8.1 Control run [ statements ... ] Run the specified statements once run [ fd 100 rt 90 ] runresult [ statements ... ] Run the specified statements once. If the statements return a value, the result is a list with the value as a single member. Otherwise, the result is an empty list. repeat expr [ statements ... ] Repeat statements expr times repeat 4 [ fd 100 rt 90 ] forever [ statements ... ] Repeat statements forever. Used inside a user-defined procedure that terminates with output , stop or bye forever [ make "n random 100 show :n if :n == 0 [ bye ] ] repcount # Outputs the current iteration number of the current repeat or forever repeat 10 [ show repcount ] repeat 10 [ show # ] if expr [ statements ... ] if [ expr ] [ statements ... ] Execute statements if the expression is non-zero if 2 > 1 [ show "yep ] ifelse expr [ statements ... ] [ statements ... ] ifelse [ expr ] [ statements ... ] [ statements ... ] Execute first set of statements if the expression is non-zero, otherwise execute the second set ifelse 1 > 2 [ show "yep ] [ show "nope ] test expr test [ expr ] Test the specified expression, save the result in the local scope for subsequent use by iftrue or iffalse iftrue [ statements ... ] ift [ statements ... ] iffalse [ statements ... ] iff [ statements ... ] Run the statements if the result of the last local test was non-zero (true) or zero (false) respectively. test 1 > 2 iftrue [ show "yep ] iffalse [ show "nope ] stop End the running procedure with no output value. output expr op expr End the running procedure and output the specified value. catch tag instructionlist Run instructions, but if an error with matching tag is thrown, return the thrown value (if any). Use "ERROR to catch errors from regular procedures. catch "t [ show "before throw "t show "after ] catch "error [ show 1 / 0 ] show error throw tag (throw tag value) Throw an error with the given tag which may be caught. An optional return value can be passed. show catch "t [ show "hello (throw "t "world) ] error Outputs a list describing the last error caught: an error number, an error message message, and the procedure name where the error occurred. catch "error [ show 1 / 0 ] show error wait time Pauses execution. time is in 60ths of a second. bye Terminate the program .maybeoutput expr Like output if expr returns a value, like stop otherwise ignore expr Evaluate and ignore results of the expression make "q [ 1 2 3 ] ignore dequeue "q ` list Outputs the list with substitutions: , instructionlist replaced by output ,@ instructionlist replaced by output list members ", instruction replaced by output prefixed with " ,@ instruction replaced by output prefixed with : show `[a b ,[bf [c d e]] f ,@[bf [g h i]]] make "v "x show `[",:v :,:v] for controllist [ statements ... ] Typical for loop. The controllist specifies three or four members: the local varname , start value, limit value, and optional step size. for [ a 1 10 ] [ show :a ] for [ a 0 20 2 ] [ show :a ] dotimes [ varname times ] [ statements ... Run the statements the specified number of times . The variable varname is set to the current iteration number. dotimes [ i 5 ] [ show :i * :i ] do.while [ statements ... ] expr do.while [ statements ... ] [ expr ] Runs the specified statements at least once, and repeats while the expression is non-zero (true). do.while [ make "a random 10 show :a ] :a < 8 while expr [ statements ... ] while [ expr ] [ statements ... ] Runs the specified statements only while the expression remains non-zero (true). while (random 2) = 0 [ show "zero ] show "one do.until [ statements ... ] expr do.until [ statements ... ] [ expr ] Runs the specified statements at least once, and repeats while the expression is zero (false). do.until [ make "a random 10 show :a ] :a < 8 until expr [ statements ... ] until [ expr ] [ statements ... ] Runs the specified statements only while the expression remains zero (false). until (random 2) = 0 [ show "one ] show "zero case value [ clauses ... ] For each clause in order: If the clause is of the form [ ELSE expr ] then expr is evaluated and returned. Otherwise, if the clause is of the form [ [ matches ] expr ] and value is a member of matches then expr is evaluated and returned. show case :var [ [ ["a] "AAA ] [ ["b] "BBB ] [ else "other ] ] cond [ clauses ... ] For each clause in order: If the clause is of the form [ ELSE expr ] then expr is evaluated and returned. Otherwise, if the clause is of the form [ [ expr1 ] expr2 ] and expr1 evaluates to non-zero (true) then expr2 is evaluated and returned. show cond [ [ [:var = 1] "one] [ [:var = 2] "two] [ else "other ] ] 8.2 Template-based Iteration These higher-level procedures support only the named procedure form of template. The first input is the name of a procedure to call. apply procname list Call procname with the members of list as inputs invoke procname input1 (invoke procname input1 ...) Call procname with the specified inputs as inputs invoke "show "hello foreach list procname call procname for each item in the list foreach [1 2 3] "show map procname list Outputs a list composed of the results of calling procname for each item in the list to double :n output :n * 2 end show map "double [1 2 3] filter procname list Outputs a list composed of the input list where procname called on the item returns non-zero (true) to oddp :n output bitand :n 1 end show filter "oddp [ 1 2 3 4 5 ] find procname list Outputs the first item in list for which calling procname on it returns non-zero (true). If not found, the empty list is returned. to oddp :n output bitand :n 1 end show find "oddp [ 2 8 4 7 10 9 ] reduce procname list (reduce procname list initial ) Call procname repeatedly with two inputs - the current value and the next list item. If initial is not specified, the first list element is used instead. show reduce "sum [ 1 2 3 4 5 ] crossmap procname listlist (crossmap procname list list ...) Call procname repeatedly with inputs from the lists, in all possible combinations. show crossmap "word [[a b] [x y]] show (crossmap "word [a b c] [1 2 3 4]) sortie discussions et commentaire avec Claude version 0.03   - https://turing.cs.hbg.psu.edu/LOCAL/ucblogo/ucbl_7.htm   - https://fmslogo.sourceforge.io/manual/workspace-control.html   - https://www.calormen.com/jslogo/language.html ● Le fichier PyLogo_0.03.py est créé et prêt. Voici le résumé :   Modifications apportées   1. En-tête de version (lignes 11-28)   Historique des versions ajouté en début de fichier.   2. Classe Workspace (lignes 447-639)   Nouvelle classe pour gérer les procédures :   - define() / get() / exists() / erase()   - bury() / unbury() / is_buried()   - list_visible() / list_buried() / list_all()   - get_source() - reconstruit le code source d'une procédure   - save() - sauvegarde dans un fichier .logo   3. Nouvelles commandes Logo   ┌──────────────────┬──────────────────┬─────────────────────────────────┐   │     Commande     │      Alias       │           Description           │   ├──────────────────┼──────────────────┼─────────────────────────────────┤   │ LISTEPROCEDURES  │ PROCEDURES, POCS │ Liste les procédures            │   ├──────────────────┼──────────────────┼─────────────────────────────────┤   │ MONTREPROCEDURE  │ PO, PRINTOUT     │ Affiche le code d'une procédure │   ├──────────────────┼──────────────────┼─────────────────────────────────┤   │ ENTERREPROCEDURE │ BURY             │ Protège une procédure           │   ├──────────────────┼──────────────────┼─────────────────────────────────┤   │ DETERREPROCEDURE │ UNBURY           │ Déprotège une procédure         │   ├──────────────────┼──────────────────┼─────────────────────────────────┤   │ SAUVEPROCEDURES  │ SAVE             │ Sauvegarde dans un fichier      │   ├──────────────────┼──────────────────┼─────────────────────────────────┤   │ CHARGEPROCEDURES │ LOAD             │ Charge depuis un fichier        │   └──────────────────┴──────────────────┴─────────────────────────────────┘   4. Intégration   - LogoInterpreter utilise maintenant self.workspace au lieu de self.procedures   - Méthode load_procedures() ajoutée pour charger les fichiers   La syntaxe est validée. Tu peux tester avec des commandes comme :   POUR CARRE :taille     REPETE 4 [AVANCE :taille DROITE 90]   FIN   SAUVEPROCEDURES "mes_dessins   LISTEPROCEDURES  Brewed for 7m 7s ❯ C'est un profond remaniement du code qui va permettre d'être plus solide et cohérent pour la suite.                                                                                                                                                                                                     Je testerais, mais la lecture du code généré est satisfaisante !                                                                                                                                                                                                                                         ● Merci. Effectivement, cette refactorisation apporte plusieurs avantages :   Architecture plus propre :   - Séparation des responsabilités : Workspace gère les procédures, LogoInterpreter exécute   - Encapsulation : toute la logique de gestion des procédures est centralisée   - Code plus testable unitairement   Préparation pour la suite :   - Ajout facile de nouvelles fonctionnalités (bibliothèques, modules)   - Base solide pour l'IDE enfants   - Le système BURY/UNBURY permet de protéger des procédures "système" que tu pourrais fournir   Points à tester en priorité :   1. POUR ... FIN → définition de procédure   2. LISTEPROCEDURES → vérifier qu'elle apparaît   3. SAUVEPROCEDURES "test → vérifier le fichier généré   4. CHARGEPROCEDURES "test → après un redémarrage   5. ENTERREPROCEDURE / DETERREPROCEDURE → protection   N'hésite pas à revenir si tu rencontres des soucis lors des tests ou pour continuer sur d'autres aspects du projet.   Interface à l'interpréteur Discussions préalables Discussion Mistral : Je comprends parfaitement ! À ce stade, il est crucial de clarifier les cas d’usage pour affiner l’architecture et éviter les choix techniques prématurés. Voici une synthèse des scénarios clés à valider, organisés par priorité et impact sur la conception. Ces cas d’usage serviront de base pour les décisions architecturales finales. 1. Cas d’Usage Principaux (Priorité Haute) A. Utilisation en Classe (Collaboratif) Scénario : 5 à 10 enfants travaillent simultanément sur leurs postes (tablettes/PC). Ils partagent des morceaux de code (ex. : une procédure POUR MAISON ) et voient les modifications en temps réel. L’enseignant peut projeté la tortue virtuelle sur un mur/écran pour que tous voient le résultat collectif. Questions clés : Partage de code : Les enfants peuvent-ils modifier le même code simultanément (comme un Google Doc) ? → Si oui : Nécessite un système de synchronisation fine (CRDT ou WebSockets + verrouillage). → Si non : Un système de "copier-coller partagé" suffit (plus simple). Faut-il un historique des modifications (pour revenir en arrière) ? Projection centrale : La tortue projetée doit-elle afficher qui a envoyé la dernière commande (ex. : "Alice a fait AVANCE 50") ? Faut-il un mode "présentation" où l’enseignant peut geler l’affichage pour expliquer un concept ? Rôle de l’enseignant : Peut-il bloquer l’envoi de commandes pendant une explication ? Peut-il sauvegarder les projets de tous les enfants en une fois ? B. Intégration avec la Tortue-Robot Scénario : La classe dispose d’ 1 ou 2 tortues-robot (MicroPython) qui se déplacent sur une feuille au sol. Les enfants envoient des commandes depuis leurs postes, et la tortue-robot exécute les mêmes mouvements que la tortue virtuelle projetée. Questions clés : Synchronisation virtuel/physique : La tortue-robot doit-elle suivre exactement la tortue virtuelle (même position, même vitesse) ? → Si oui : Nécessite un système de calibration précis (ex. : 1 pas virtuel = 1 cm physique). → Si non : La tortue-robot exécute les commandes indépendamment , avec ses propres contraintes (ex. : elle bute sur un obstacle). Feedback physique : Si la tortue-robot est bloquée, faut-il afficher un message d’erreur sur tous les écrans (ex. : "La tortue ne peut pas avancer !") ? Peut-on envoyer des commandes "spéciales" à la tortue-robot (ex. : allumer une LED, émettre un son) ? Logistique : Combien de tortues-robot seront utilisées simultanément ? Faut-il prévoir un système de réservation (ex. : "C’est au tour de Bob d’utiliser la tortue") ? C. Utilisation Individuelle (À la Maison) Scénario : Un enfant utilise l’interpréteur seul sur son poste , sans tortue-robot ni projection. Il peut sauvegarder ses projets et les retrouver en classe. Questions clés : Sauvegarde : Les projets sont-ils sauvegardés localement (fichier sur l’ordinateur) ou sur un serveur (compte utilisateur) ? Faut-il un système de synchronisation entre la maison et l’école ? Compatibilité : L’interface doit-elle fonctionner sur mobile/tablette (ex. : iPad) ? Faut-il une version hors ligne (pour les zones sans internet) ? 2. Cas d’Usage Secondaires (Priorité Moyenne) A. Collaboration À Distance Scénario : Deux classes (ou un enfant à la maison et un autre en classe) collaborent sur le même projet. Questions : Faut-il un système d’ invitation par lien (comme Google Docs) ? Comment gérer les décalages horaires ou les connexions instables ? B. Extensions Pédagogiques Scénario : L’enseignant veut créer des défis (ex. : "Dessine un hexagone") ou limiter les commandes disponibles pour les débutants. Questions : Faut-il un mode "défi" où certaines commandes sont désactivées ? Peut-on enregistrer des séquences pour les rejouer plus tard (ex. : pour montrer une solution) ? C. Accessibilité Scénario : Un enfant malvoyant ou avec des troubles dys utilise l’outil. Questions : Faut-il prévoir un mode haute contraste ou une saisie vocale ? Peut-on agrandir la taille du texte ou des boutons ? 3. Cas d’Usage Exclus (Priorité Basse) Intégration avec d’autres outils (ex. : exporter un dessin vers un logiciel de dessin). Compétitions entre classes (ex. : "Qui dessine le plus beau motif ?"). Utilisation par des adultes (ex. : pour des ateliers de programmation créative). 4. Synthèse des Impacts Architecturaux Cas d’Usage Impact Technique Principal Complexité Collaboratif en temps réel WebSockets + gestion des conflits de code Élevée Tortue-robot synchronisée Communication serveur/MicroPython + calibration Moyenne Projection centrale Séparation frontend/backend + mode lecture seule Faible Sauvegarde des projets Base de données (SQLite) ou fichiers locaux Faible Utilisation hors ligne Service Workers (pour le web) ou app desktop Moyenne 5. Prochaines Étapes pour Toi Valider les cas d’usage prioritaires avec les enseignants/élèves : Quels scénarios sont indispensables pour la rentrée 2026–2027 ? Quels sont optionnels (peuvent attendre une V2) ? Affiner les contraintes techniques : Exemple : Si la tortue-robot doit être synchronisée avec la virtuelle, il faudra un protocole de communication temps réel (WebSockets + MicroPython). Si le partage de code est collaboratif, il faudra choisir entre CRDT (complexe) ou verrouillage (plus simple). Prototypage léger : Une fois les cas d’usage validés, un prototype minimal (ex. : Flask + HTML basique) permettra de tester les flux principaux. 6. Exemple de Décisions Architecturales Découlant des Cas d’Usage Décision Si Cas d’Usage X est validé... Sinon... Technologie backend Flask + WebSockets (pour le temps réel) Flask seul (plus simple) Stockage des projets SQLite + système de versions (pour l’historique) Fichiers locaux (JSON) Frontend Vue.js léger (pour la réactivité) Vanilla JS (plus simple) Communication tortue-robot WebSockets + protocole custom USB sériel (pour un prototype) Question pour toi : Quels sont les 3 cas d’usage prioritaires que tu veux absolument voir implémentés pour la rentrée 2026–2027 ? Cela permettra de focaliser l’architecture sur l’essentiel. 😊 (Exemple de réponse : "1. Collaboratif en classe avec projection, 2. Tortue-robot synchronisée, 3. Sauvegarde locale des projets.")   1. Principes fondateurs de l’UI (version "puriste mais moderne") a. Minimalisme radical Pas de blocs prédéfinis (type Scratch) : L’enfant écrit toujours du code texte, mais avec des aides optionnelles et non intrusives . Pas de surcharge visuelle : L’écran est épuré, avec uniquement : Une zone de dessin (tortue + traces). Une console de commande (saisie texte). Une zone de procédures (pour sauvegarder/réutiliser du code écrit par l’enfant). b. Modernité discrète Design sobre mais actuel : Couleurs : Fond clair (blanc cassé ou bleu très pâle) pour éviter la fatigue oculaire, tortue et textes en noir ou couleurs vives uniquement pour le feedback (ex. : syntaxe correcte en vert, erreur en orange). Typographie : Police monospace (ex. Courier New ou Fira Code ) pour le code (lisibilité et alignement des commandes), et une police simple (ex. Open Sans ) pour les menus. Formes : Lignes épurées, pas de boutons superflus. Les éléments interactifs sont discrets mais identifiables (ex. : survol = léger soulignement). Feedback visuel intelligent : La tortue clignote brièvement quand une commande est exécutée (sans son, pour éviter la distraction). Les erreurs de syntaxe sont signalées par un soulignement rouge + message court en bas de l’écran (ex. : "Il manque un nombre après AVANCE" ). Pas d’animations inutiles : La tortue se déplace immédiatement (pas de "dance" ou d’effets de style). c. Personnalisation par l’enfant (sans assistance forcée) Boutons programmables : L’enfant peut créer ses propres boutons en glissant-déposant du code qu’il a écrit dans une zone dédiée (ex. : un bouton "CARRÉ" exécutant sa procédure POUR CARRE ... FIN ). Ces boutons sont des raccourcis , pas des commandes prédéfinies. Ils apparaissent comme des étiquettes textuelles simples (pas d’icônes imposées). Éditeur de procédures : Une zone latérale (ou un onglet) permet de lister les procédures définies par l’enfant , avec un bouton "Éditer" pour les modifier. Pas de "bibliothèque" prédéfinie : Tout doit être écrit par l’enfant ou importé depuis ses propres fichiers. d. Respect de la philosophie Logo Pas de gamification (badges, étoiles) : L’enfant est motivé par la création elle-même , pas par des récompenses externes. Pas de "mode découverte" guidé : L’interface ne propose jamais de défis ou de tutoriels intrusifs. En revanche, un bouton "?" peut ouvrir un manuel minimaliste avec des exemples de code (ex. : "Pour dessiner un carré : Répète 4 fois [AVANCE 100 TOURNE 90]" ). Accès direct au métalangage : L’enfant peut voir et modifier les primitives de base (ex. : redéfinir AVANCE s’il le souhaite, comme dans les versions historiques de Logo). On est encore en réflexion sur le sujet. J'ai aussi les idées suivante - permettre à plusieurs enfants de partager en temps réel des codes ou morceaux de code - pouvoir séparer de l'interface la zone d'exécution ou il y a la tortue : elle peut-être projetée par exemple sur un mur, et les enfants travaillent sur un/leur poste. - donc ou peut aussi envisager une architecture client/serveur ou un code python/flask sert l'interface ou plusieurs interfaces, dont la zone de projection tortue. - enfin, j'inscris ce projet dans un suite de projet ou les enfants peuvent utiliser une tortue-robot réelle, qui se déplace sur un feuille sur le sol de la classe. - ce projet sera porté par les enfants ados et la programmation de la tortue pourrait-être faite au travers de la bibliothèque micro-python PROPOSITION : 1. Architecture Globale Proposée Ton projet combine 4 dimensions : Interpréteur Logo collaboratif (partage de code en temps réel). Séparation interface/exécution (projection de la tortue sur un mur). Architecture client/serveur (pour gérer plusieurs interfaces et la projection). Intégration avec des tortues-robot physiques (via MicroPython). Voici une architecture technique cohérente pour répondre à ces besoins : +-------------------+       +-------------------+       +---------------------+ |   Client 1        |       |   Client 2        |       |   Projecteur/Écran  | | (Enfant A)         |------>| (Enfant B)         |------>| (Tortue virtuelle)  | | - Éditeur de code  |       | - Éditeur de code  |       | - Affichage seul    | | - Console          |       | - Console          |       | - Pas de saisie      | +-------------------+       +-------------------+       +---------------------+         \                                                                   /          \                                                                 /           +-------------------+       +-------------------------------+           |   Serveur          |       |   Tortue-Robot (MicroPython)  |           | (Python/Flask)     |<----->| - Reçoit les commandes        |           | - Gère les sessions|       | - Se déplace sur le sol       |           | - Synchronise     |       | - Envoie des feedbacks        |           |   le code          |       |   (position, erreurs)         |           +-------------------+       +-------------------------------+   Merci pour ces précisions passionnantes ! Ton projet prend une dimension collaborative, physique et pédagogique très riche, qui dépasse largement un simple interpréteur Logo classique. Voici une analyse structurée des enjeux et des solutions possibles, en gardant à l’esprit tes contraintes (fidélité à l’esprit Logo, modernité discrète, et intégration avec du matériel comme les tortues-robot). 2. Solutions Techniques par Dimension A. Collaboratif en temps réel Objectif : Permettre à plusieurs enfants de partager du code ou des morceaux de code. Solutions : CRDT (Conflict-free Replicated Data Type) : Utiliser une bibliothèque comme Yjs (pour le web) ou Automerge (pour une app desktop). Avantages : Synchronisation fluide, pas de conflits, historique des modifications. Exemple : Si un enfant écrit POUR CARRE , un autre peut voir la définition en temps réel et l’utiliser. WebSockets (pour une solution client/serveur) : Le serveur Flask diffuse les mises à jour de code à tous les clients connectés. Exemple avec Flask-SocketIO : from flask_socketio import SocketIO, emit @socketio.on('code_update') def handle_code_update(data): emit('code_update', data, broadcast=True) # Envoie à tous les clients Alternative simple : Un système de "copier-coller partagé" via le serveur (moins fluide, mais plus simple à implémenter). B. Séparation interface/exécution (projection) Objectif : La tortue s’affiche sur un écran/mur, tandis que les enfants codent sur leurs postes. Solutions : Mode "Projection" : Le serveur Flask génère une URL dédiée pour la projection (ex. : /projection ). Cette page n’a que la zone de dessin (tortue + traces), sans éditeur ni console. Les enfants envoient leurs commandes au serveur, qui les exécute et met à jour l’affichage pour tous. Technos : Frontend : HTML/Canvas pour la projection (même code que les clients, mais en mode "lecture seule"). Backend : Flask gère les états partagés (position de la tortue, couleurs, etc.). Exemple de flux : Un enfant tape AVANCE 50 sur son poste. Le code est envoyé au serveur via WebSocket. Le serveur met à jour l’état de la tortue et envoie la nouvelle position à tous les clients + la projection . C. Architecture Client/Serveur (Flask) Objectif : Centraliser la logique pour gérer plusieurs interfaces et la projection. Solutions : Flask + SocketIO : Avantages : Léger et facile à déployer (même sur un Raspberry Pi en classe). Permet de gérer les sessions, l’historique des commandes, et la synchronisation. Exemple de routes : @app.route('/') def index(): return render_template('editeur.html') # Interface complète pour les enfants @app.route('/projection') def projection(): return render_template('projection.html') # Zone de dessin seule Stockage des projets : Utiliser une base SQLite (légère, sans serveur) pour sauvegarder les procédures des enfants. Exemple de table : CREATE TABLE projets ( id INTEGER PRIMARY KEY, nom TEXT, code TEXT, date_modification DATETIME ); D. Intégration avec les tortues-robot (MicroPython) Objectif : Permettre aux enfants de contrôler une tortue physique via le même code Logo. Solutions : Protocole de communication : Le serveur Flask agit comme un pont entre les clients et la tortue-robot. Les commandes Logo sont traduites en instructions MicroPython (ex. : AVANCE 50 → robot.forward(50) ). Matériel : La tortue-robot est équipée d’un ESP32 ou Raspberry Pi Pico (compatible MicroPython). Elle se connecte au serveur via Wi-Fi (pour les ESP32) ou USB (pour un prototype simple). Exemple de code MicroPython (côté robot) : from machine import Pin, PWM import network import socket # Configuration Wi-Fi sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect('SSID', 'password') # Moteurs (exemple simplifié) def forward(steps): # Logique pour avancer print(f"Avance de {steps} pas") # Serveur TCP pour recevoir les commandes s = socket.socket() s.bind(('0.0.0.0', 8080)) s.listen(1) while True: conn, addr = s.accept() data = conn.recv(1024).decode() if data.startswith("AVANCE"): steps = int(data.split()[1]) forward(steps) conn.close() Côté serveur Flask : Quand un enfant envoie AVANCE 50 , le serveur transmet la commande à la tortue-robot via Wi-Fi/USB. 3. Points d’Attention Latence : Avec plusieurs enfants + une tortue physique, la latence peut devenir visible. Solution : Utiliser des WebSockets pour minimiser les délais, et prévoir un système de "file d’attente" pour les commandes. Sécurité : Si le serveur est accessible sur le réseau de l’école, sécuriser les connexions (mot de passe simple pour la classe). Pédagogie : Ne pas cacher la complexité : Les enfants doivent comprendre que la tortue physique et la tortue virtuelle suivent les mêmes règles. Feedback clair : Si la tortue-robot bute sur un obstacle, envoyer un message comme "Attention, la tortue est bloquée !" sur tous les écrans. 4. Exemple de Workflow Complet En classe : Les enfants ouvrent leur navigateur sur http:// . Ils voient l’éditeur Logo et la console. Le projecteur affiche http:///projection . Collaboration : Alice écrit POUR CARRE ... FIN . Bob peut voir la procédure et l’utiliser dans son propre code. Exécution : Quand un enfant exécute CARRE , la tortue virtuelle (projection) et la tortue-robot (si connectée) dessinent un carré. Feedback : Si la tortue-robot rencontre un problème, un message s’affiche sur tous les écrans. 5. Technologies Recommandées Composant Technologie Pourquoi Frontend HTML/CSS/JS (Vanilla ou Vue.js léger) Simple, portable, pas de compilation. Backend Python/Flask + Flask-SocketIO Léger, facile à déployer, compatible avec MicroPython. Base de données SQLite Sans serveur, idéale pour un usage en classe. Tortue-robot ESP32 + MicroPython Peu coûteux, programmable en Python, Wi-Fi intégré. Collaboration WebSockets (SocketIO) Temps réel, simple à implémenter avec Flask. 6. Prochaines Étapes Possibles Prototype minimal : Un serveur Flask basique + une page HTML avec un éditeur et un canvas. Test avec 2 clients et une projection. Intégration MicroPython : Connecter une tortue-robot (ESP32) au serveur et traduire les commandes Logo. Tests en classe : Observer comment les enfants interagissent avec l’outil (collaboration, compréhension des feedbacks). Question pour toi : Veux-tu que je te propose un exemple de code Flask + HTML/JS pour démarrer le prototype (avec la synchronisation basique et la projection) ? Ou préfères-tu approfondir un autre aspect (ex. : la communication avec la tortue-robot, ou la gestion des conflits de code) ?