SNT

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

lvl3.html (10159B)


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