SNT

Cours de SNT
git clone git://git.vgx.fr/SNT
Log | Files | Refs

lvl2.html (10054B)


      1 <head>
      2 
      3 <meta charset="utf-8"/>
      4 
      5 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"/>
      6 
      7 <style>
      8 h1,h2 {
      9     font-family: Sans;
     10 }
     11 
     12 .stderr {
     13     background-color: #fee;
     14     color: #900;
     15 }
     16 
     17 .stderr, .stdout {
     18     /* display: contents; */ /* uncomment to make print( end='') work */
     19     margin: 0px;
     20     padding: 0px 0.3em;
     21 }
     22 
     23 .console {
     24     max-height: 20em;
     25     overflow: auto;
     26     border: medium solid black;
     27 }
     28 
     29 .console:empty {
     30     display: none;
     31 }
     32 
     33 #feedback {
     34     border: solid #aaa;
     35     background-color: #eee;
     36 }
     37 
     38 #feedback:empty {
     39     display: none;
     40 }
     41 
     42 #edcontainer {
     43     display: flex;
     44 }
     45 .edcolumn {
     46     flex: 50%;
     47 }
     48 #breditor {
     49     width: 100%;
     50 }
     51 
     52 
     53 </style>
     54 
     55 <script src="https://cdn.jsdelivr.net/npm/phaser@3.55.0/dist/phaser.min.js"></script>
     56 <script src="https://unpkg.com/brython@3.9.3/brython.js"></script>
     57 <script src="https://unpkg.com/brython@3.9.3/brython_stdlib.js"></script>
     58 <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.min.js"></script>
     59 <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/mode-python.min.js"></script>
     60 
     61 <script type="text/javascript">
     62 
     63 code = "# Écrivez votre code python ici :\nprint(\"Bonjour !\")";
     64 
     65 score = 0;
     66 
     67 API = window.API || window.parent.API;
     68 
     69 function loadSCO() {
     70     if (API) {
     71         API.LMSInitialize("");
     72 
     73         suspend_data = API.LMSGetValue("cmi.suspend_data");
     74 
     75         if (suspend_data) {
     76             code = suspend_data;
     77         }
     78     }
     79 }
     80 
     81 function sendSCO() {
     82     if (API) {
     83         API.LMSSetValue("cmi.core.score.raw", score);
     84         API.LMSSetValue("cmi.suspend_data", code);
     85         API.LMSSetValue("cmi.core.score.lesson_status", "completed");
     86 
     87         API.LMSCommit("");
     88     }
     89 }
     90 
     91 function nextSCO() {
     92     if (API) {
     93         API.LMSSetValue("nav.event","continue"); // Probably Moodle specific
     94         API.LMSFinish("");
     95     }
     96 }
     97 
     98 // Phaser stuff
     99 
    100 var tilesize = 32;
    101 var delay = 250;
    102 
    103 var tiles = [];
    104 
    105 var movetime = 0;
    106 var delayed_moves = [];
    107 
    108 var config = {
    109     type: Phaser.AUTO,
    110     width: tilesize*10,
    111     height: tilesize*10,
    112     parent: "game",
    113     scene: {
    114         preload: preload,
    115         create: create
    116     }
    117 };
    118 
    119 function preload() {
    120     this.load.image("tilemap", "img/tilemap.png")
    121     this.load.image("bot", "img/bot.png")
    122     this.load.tilemapCSV('map', 'lvl/lvl2.csv');
    123 }
    124 
    125 function create() {
    126     map = this.make.tilemap({ key: 'map', tileWidth: 32, tileHeight: 32 });
    127     var tileset = map.addTilesetImage('tilemap');
    128     layer = map.createLayer(0, tileset, 0, 0);
    129     
    130     bot = this.add.image(tilesize * 1.5, tilesize * 1.5, "bot");
    131 }
    132 
    133 function gen_tiles() {
    134     for (var i = 0 ; i < 10 ; i++) {
    135         tiles[i] = [];
    136         for (var j = 0 ; j < 10 ; j++) {
    137             var id = map.getTileAt(i,j).index;
    138             if (id == 4)
    139                 id = 0;
    140             tiles[i][j] = id;
    141         }
    142     }
    143 
    144     if (Math.random() < 0.5)
    145         tiles[1][2] = 3;
    146     else
    147         tiles[2][1] = 3;
    148 }
    149 
    150 function get_tile_at(x,y) {
    151     return tiles[x][y];
    152 }
    153 
    154 function reset_board() {
    155     movetime = 0;
    156     bot.x = tilesize * 1.5;
    157     bot.y = tilesize * 1.5;
    158     bot.angle = 0;
    159 
    160     for (move of delayed_moves){
    161         clearTimeout(move)
    162     }
    163 
    164     delayed_moves = []
    165 
    166     gen_tiles()
    167 }
    168 
    169 function move_left() {
    170     delayed_moves.push(
    171         setTimeout(
    172             function() {
    173                 bot.x -= tilesize;
    174                 bot.angle = 180;
    175             }, movetime)
    176         );
    177     movetime += delay;
    178 }
    179 
    180 function move_right() {
    181     delayed_moves.push(
    182         setTimeout(
    183             function() {
    184                 bot.x += tilesize;
    185                 bot.angle = 0;
    186             }, movetime)
    187         );
    188     movetime += delay;
    189 }
    190 
    191 function move_up() {
    192     delayed_moves.push(
    193         setTimeout(
    194             function() {
    195                 bot.y -= tilesize;
    196                 bot.angle = -90;
    197             }, movetime)
    198         );
    199     movetime += delay;
    200 }
    201 
    202 function move_down() {
    203     delayed_moves.push(
    204         setTimeout(
    205             function() {
    206                 bot.y += tilesize;
    207                 bot.angle = 90;
    208             }, movetime)
    209         );
    210     movetime += delay;
    211 }
    212 
    213 window.onload = function() {
    214     loadSCO();
    215     document.getElementById("code").textContent = code;
    216 
    217     game = new Phaser.Game(config);
    218     
    219     brython();
    220 }
    221 </script>
    222 
    223 <script type="text/python">
    224 # Requires Brython and Ace editor
    225 
    226 from browser import document, window, html
    227 from sys import stderr, stdout, settrace
    228 from traceback import print_exc, extract_stack, extract_tb
    229 
    230 def make_max_line_tracer(maxlines):
    231     lines = 0
    232     def tracer(frame, event, arg):
    233         nonlocal lines
    234         if event == 'line':
    235             lines += 1
    236             if lines >= maxlines:
    237                 raise TimeoutError
    238         return tracer
    239     return tracer
    240 
    241 def exec_code(editor, id):
    242     reset()
    243     feedback("Le drapeau n'est pas encore atteint")
    244 
    245     code_lines = editor.session.getLength()
    246     if code_lines > max_code_lines:
    247         feedback("Trop de lignes utilisées ( " + str(code_lines) + "/" + str(max_code_lines) + ")")
    248         return
    249     
    250     console = document[id + "_console"]
    251     console.clear()
    252     stderr.write = lambda data : console_target(data, console, True)
    253     stdout.write = lambda data : console_target(data, console)
    254 
    255     code = editor.getValue()
    256     try:
    257         compiled = compile(code, "<" + id + ">", "exec")
    258     except SyntaxError:
    259         print_exc(limit=0)
    260         return
    261 
    262     settrace(make_max_line_tracer(10000)) # increase to allow longer execution
    263     try:
    264         exec(code)
    265     except TimeoutError:
    266         settrace(None)
    267         print("L'exécution prend trop de temps, abandon.", file=stderr)
    268     except Exception as e:
    269         settrace(None)
    270         tb_len = len(extract_tb(e.__traceback__)) - len(extract_stack())
    271         print_exc(limit=-tb_len)
    272     finally:
    273         settrace(None)
    274 
    275     window.code = code
    276     #window.score = check()
    277     window.sendSCO()
    278 
    279 def console_target(data, elt, err=False):
    280     elt <= html.PRE(data, Class="stderr" if err else "stdout")
    281     elt.scrollTop = elt.scrollHeight
    282 
    283 breditors = document.select(".breditor")
    284 
    285 max_code_lines = 20
    286 
    287 for ed_elt in breditors:
    288     editor = window.ace.edit(ed_elt.id)
    289     editor.session.setMode("ace/mode/python")
    290     #editor.setOption('fontSize', '14px')
    291     editor.setOption('maxLines', max_code_lines)
    292     editor.setOption('minLines', max_code_lines)
    293 
    294     console = html.DIV(Class="console", id=ed_elt.id + "_console")
    295 
    296     ed_elt.insertAdjacentElement('afterend', console)
    297 
    298     exec_button = html.BUTTON("Exécuter →")
    299     exec_button.bind("click", lambda ev : exec_code(editor, ed_elt.id))
    300     ed_elt.insertAdjacentElement('afterend', exec_button)
    301 
    302 def feedback(msg):
    303     document["feedback"].clear()
    304     document["feedback"] <= msg
    305 
    306 coords = [1,1]
    307 
    308 def reset():
    309     global coords
    310     window.reset_board()
    311     coords = [1,1]
    312 
    313 def gauche():
    314     if coords[0] >= 0:
    315         tile = window.get_tile_at(coords[0]-1, coords[1])
    316         if tile in (0,1,3):
    317             window.move_left()
    318             coords[0] -= 1
    319             if tile == 1:
    320                 win()
    321             elif tile == 3:
    322                 fall()
    323 
    324 def droite():
    325     if coords[0] < 10:
    326         tile = window.get_tile_at(coords[0]+1, coords[1])
    327         if tile in (0,1,3):
    328             window.move_right()
    329             coords[0] += 1
    330             if tile == 1:
    331                 win()
    332             elif tile == 3:
    333                 fall()
    334 
    335 def haut():
    336     if coords[1] >= 0:
    337         tile = window.get_tile_at(coords[0], coords[1]-1)
    338         if tile in (0,1,3):
    339             window.move_up()
    340             coords[1] -= 1
    341             if tile == 1:
    342                 win()
    343             elif tile == 3:
    344                 fall()
    345 
    346 def bas():
    347     if coords[1] < 10:
    348         tile = window.get_tile_at(coords[0], coords[1]+1)
    349         if tile in (0,1,3):
    350             window.move_down()
    351             coords[1] += 1
    352             if tile == 1:
    353                 win()
    354             elif tile == 3:
    355                 fall()
    356 
    357 
    358 def voir_gauche():
    359     if coords[0] == 0:
    360         return 3
    361     else:
    362         return voir(coords[0]-1, coords[1])
    363 
    364 def voir_droite():
    365     if coords[0] == 10:
    366         return 3
    367     else:
    368         return voir(coords[0]+1, coords[1])
    369 
    370 def voir_haut():
    371     if coords[1] == 0:
    372         return 3
    373     else:
    374         return voir(coords[0], coords[1]-1)
    375 
    376 def voir_bas():
    377     if coords[1] == 10:
    378         return 3
    379     else:
    380         return voir(coords[0], coords[1]+1)
    381 
    382 def voir(x,y):
    383     return window.get_tile_at(x,y)
    384 
    385 def fall():
    386     feedback("Le robot est tombé dans le vide !")
    387     raise Exception("Le robot est tombé dans le vide")
    388     
    389 
    390 def win():
    391     window.score = 100
    392     feedback("Ça a l'air correct, mais exécutez plusieur fois pour voir si ça marche aussi dans d'autres cas.")
    393     document["feedback"] <= html.BUTTON("Passer à la suite", onclick="nextSCO();")
    394     
    395 
    396 </script>
    397 
    398 </head>
    399 
    400 <body>
    401 
    402 <h1>Niveau 2</h1>
    403 
    404 Vous disposez des fonctions
    405 <code>droite()</code>,
    406 <code>gauche()</code>,
    407 <code>haut()</code>, et
    408 <code>bas()</code>
    409 pour faire avancer le robot.
    410 
    411 </br>
    412 
    413 Vous pouvez aussi utiliser 
    414 <code>voir_droite()</code>,
    415 <code>voir_gauche()</code>,
    416 <code>voir_haut()</code>, et
    417 <code>voir_bas()</code>
    418 pour regarder les cases autour de vous,
    419 ces fonctions renvoient le type de la case :
    420 <ul>
    421     <li>0 pour un chemin</li>
    422     <li>1 pour une arrivée</li>
    423     <li>2 pour un mur</li>
    424     <li>3 pour du vide</li>
    425 </ul>
    426 
    427 <p>
    428 Les cases point d'interrogation ont un type caché qui est révélé
    429 losqu'on les regarde.
    430 </p>
    431 
    432 <p>
    433 Pour choisir le bon chemin il faudra utiliser le si..alors..sinon de Python, exemple :
    434 <pre><code># si la case du haut est un mur
    435 if voir_haut() == 2:
    436     # alors faire quelque chose:
    437     droite()
    438 else:
    439     # sinon faire autre chose ...
    440     haut()
    441 </code></pre>
    442 pour afficher son vrai type.
    443 </p>
    444 
    445 
    446 <div id="edcontainer">
    447     <div class="edcolumn">
    448         Code python :
    449         <pre id="code" class="breditor"></pre>
    450         <div id="feedback"></div>
    451     </div>
    452     <div class="edcolumn">
    453         Plateau :
    454         <div id="game"></div>
    455     </div>
    456 </div>
    457 
    458 
    459 
    460 
    461 
    462 
    463 </body>
    464 </html>