SNT

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

lvl1.html (9470B)


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