SNT

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

lvl2.html (10192B)


      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/lvl2.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     tiles[1][0] = target_x;
    156     tiles[target_x+1][target_y+1] = 1;
    157 }
    158 
    159 function get_tile_at(x,y) {
    160     return tiles[x][y];
    161 }
    162 
    163 function reset_board() {
    164     movetime = 0;
    165     bot.x = tilesize * 1.5;
    166     bot.y = tilesize * 1.5;
    167     bot.angle = 0;
    168 
    169     for (move of delayed_moves){
    170         clearTimeout(move)
    171     }
    172 
    173     delayed_moves = []
    174 
    175     gen_tiles()
    176 }
    177 
    178 function move_left() {
    179     delayed_moves.push(
    180         setTimeout(
    181             function() {
    182                 bot.x -= tilesize;
    183                 bot.angle = 180;
    184             }, movetime)
    185         );
    186     movetime += delay;
    187 }
    188 
    189 function move_right() {
    190     delayed_moves.push(
    191         setTimeout(
    192             function() {
    193                 bot.x += tilesize;
    194                 bot.angle = 0;
    195             }, movetime)
    196         );
    197     movetime += delay;
    198 }
    199 
    200 function move_up() {
    201     delayed_moves.push(
    202         setTimeout(
    203             function() {
    204                 bot.y -= tilesize;
    205                 bot.angle = -90;
    206             }, movetime)
    207         );
    208     movetime += delay;
    209 }
    210 
    211 function move_down() {
    212     delayed_moves.push(
    213         setTimeout(
    214             function() {
    215                 bot.y += tilesize;
    216                 bot.angle = 90;
    217             }, movetime)
    218         );
    219     movetime += delay;
    220 }
    221 
    222 window.onload = function() {
    223     loadSCO();
    224     document.getElementById("code").textContent = code;
    225 
    226     game = new Phaser.Game(config);
    227     
    228     brython();
    229 }
    230 </script>
    231 
    232 <script type="text/python">
    233 # Requires Brython and Ace editor
    234 
    235 from browser import document, window, html
    236 from sys import stderr, stdout, settrace
    237 from traceback import print_exc, extract_stack, extract_tb
    238 
    239 def make_max_line_tracer(maxlines):
    240     lines = 0
    241     def tracer(frame, event, arg):
    242         nonlocal lines
    243         if event == 'line':
    244             lines += 1
    245             if lines >= maxlines:
    246                 raise TimeoutError
    247         return tracer
    248     return tracer
    249 
    250 def exec_code(editor, id):
    251     global x, y
    252     reset()
    253     #x = window.target_x
    254     y = window.target_y
    255     
    256     feedback("Le drapeau n'est pas encore atteint")
    257 
    258     code_lines = editor.session.getLength()
    259     if code_lines > max_code_lines:
    260         feedback("Trop de lignes utilisées ( " + str(code_lines) + "/" + str(max_code_lines) + ")")
    261         return
    262     
    263     console = document[id + "_console"]
    264     console.clear()
    265     stderr.write = lambda data : console_target(data, console, True)
    266     stdout.write = lambda data : console_target(data, console)
    267 
    268     code = editor.getValue()
    269     try:
    270         compiled = compile(code, "<" + id + ">", "exec")
    271     except SyntaxError:
    272         print_exc(limit=0)
    273         return
    274 
    275     settrace(make_max_line_tracer(10000)) # increase to allow longer execution
    276     try:
    277         exec(code)
    278     except TimeoutError:
    279         settrace(None)
    280         print("L'exécution prend trop de temps, abandon.", file=stderr)
    281     except Exception as e:
    282         settrace(None)
    283         tb_len = len(extract_tb(e.__traceback__)) - len(extract_stack())
    284         print_exc(limit=-tb_len)
    285     finally:
    286         settrace(None)
    287 
    288     window.code = code
    289     #window.score = check()
    290     window.sendSCO()
    291 
    292 def console_target(data, elt, err=False):
    293     elt <= html.PRE(data, Class="stderr" if err else "stdout")
    294     elt.scrollTop = elt.scrollHeight
    295 
    296 breditors = document.select(".breditor")
    297 
    298 max_code_lines = 10
    299 
    300 for ed_elt in breditors:
    301     editor = window.ace.edit(ed_elt.id)
    302     editor.session.setMode("ace/mode/python")
    303     #editor.setOption('fontSize', '14px')
    304     editor.setOption('maxLines', max_code_lines)
    305     editor.setOption('minLines', max_code_lines)
    306 
    307     console = html.DIV(Class="console", id=ed_elt.id + "_console")
    308 
    309     ed_elt.insertAdjacentElement('afterend', console)
    310 
    311     exec_button = html.BUTTON("Exécuter →")
    312     exec_button.bind("click", lambda ev : exec_code(editor, ed_elt.id))
    313     ed_elt.insertAdjacentElement('afterend', exec_button)
    314 
    315 def feedback(msg):
    316     document["feedback"].clear()
    317     document["feedback"] <= msg
    318 
    319 coords = [1,1]
    320 
    321 def reset():
    322     global coords
    323     window.reset_board()
    324     coords = [1,1]
    325 
    326 def gauche():
    327     if coords[0] >= 0:
    328         move_to(coords[0]-1, coords[1], -1, 0, window.move_left)
    329 
    330 def droite():
    331     if coords[0] < 10:
    332         move_to(coords[0]+1, coords[1], 1, 0, window.move_right)
    333 
    334 def haut():
    335     if coords[1] >= 0:
    336         move_to(coords[0], coords[1]-1, 0, -1, window.move_up)
    337 
    338 def bas():
    339     if coords[1] < 10:
    340         move_to(coords[0], coords[1]+1, 0 , 1, window.move_down)
    341 
    342 def move_to(x, y, dx, dy, move):
    343     tile = window.get_tile_at(x, y)
    344     if tile in (0,1,3):
    345         move()
    346         coords[0] += dx
    347         coords[1] += dy
    348         if tile == 1:
    349             win()
    350         elif tile == 3:
    351             fall()
    352         else:
    353             feedback("Le robot n'est pas sur un drapeau")
    354             window.score = 0
    355     
    356 
    357 def voir_gauche():
    358     if coords[0] == 0:
    359         return 3
    360     else:
    361         return voir(coords[0]-1, coords[1])
    362 
    363 def voir_droite():
    364     if coords[0] == 10:
    365         return 3
    366     else:
    367         return voir(coords[0]+1, coords[1])
    368 
    369 def voir_haut():
    370     if coords[1] == 0:
    371         return 3
    372     else:
    373         return voir(coords[0], coords[1]-1)
    374 
    375 def voir_bas():
    376     if coords[1] == 10:
    377         return 3
    378     else:
    379         return voir(coords[0], coords[1]+1)
    380 
    381 def voir(x,y):
    382     return window.get_tile_at(x,y)
    383 
    384 def fall():
    385     feedback("Le robot est tombé dans le vide !")
    386     raise Exception("Le robot est tombé dans le vide")
    387     
    388 
    389 def win():
    390     window.score = 100
    391     feedback("Bravo ! (exécutez plusieurs fois avant de continuer)")
    392     document["feedback"] <= html.BUTTON("Passer à la suite", onclick="nextSCO();")
    393     
    394 
    395 </script>
    396 
    397 </head>
    398 
    399 <body>
    400 
    401 <h1>Niveau 2</h1>
    402 
    403 <p>
    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 </p>
    411 
    412 <p>
    413 Le drapeau est caché parmis ces points d'interrogation,
    414 mais cette fois-ci vous n'avez plus la variable
    415 <code>x</code>
    416 (la variable
    417 <code>y</code>
    418 est encore là).
    419 </p>
    420 
    421 <p>
    422 Les cases
    423 <code><i>i</i></code>
    424 contiennent un nombre qu'on peut voir en regardant leur contenu avec
    425 les fonctions
    426 <code>voir_droite()</code>,
    427 <code>voir_gauche()</code>,
    428 <code>voir_haut()</code>, ou
    429 <code>voir_bas()</code>.
    430 </p>
    431 
    432 <p>
    433 Dans ce cas vous devrez créer votre propre variable qui contiendra le
    434 nombre donné par la case 
    435 <code><i>i</i></code>,
    436 qui correspond à l'ancienne variable
    437 <code>x</code>
    438 (le nombre de fois que le robot doit aller à droite).
    439 </p>
    440 
    441 <p>
    442 Exemples avec des variables :
    443 <pre><code># on crée des variables
    444 lol = 42
    445 lul = "truc"
    446 lel = lol + 2
    447 
    448 # on modifie des variables
    449 lol = 4
    450 lel = lel - 2
    451 
    452 # on utilise des variables
    453 print(lul)
    454 
    455 for i in range(lol):
    456     print("salut")
    457 
    458 if lel == 42:
    459    print("ok")
    460 </code></pre>
    461 </p>
    462 
    463 
    464 <div id="edcontainer">
    465     <div class="edcolumn">
    466         Code python :
    467         <pre id="code" class="breditor"></pre>
    468         <div id="feedback"></div>
    469     </div>
    470     <div class="edcolumn">
    471         Plateau :
    472         <div id="game"></div>
    473     </div>
    474 </div>
    475 
    476 </body>
    477 </html>