-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorial.html
More file actions
816 lines (778 loc) · 47.4 KB
/
Copy pathtutorial.html
File metadata and controls
816 lines (778 loc) · 47.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Emoji Coder — Tutorial</title>
<script src="https://unpkg.com/blockly/blockly_compressed.js"></script>
<script src="https://unpkg.com/blockly/blocks_compressed.js"></script>
<script src="https://unpkg.com/blockly/javascript_compressed.js"></script>
<script src="https://unpkg.com/blockly/msg/pt-br.js"></script>
<script src="https://unpkg.com/@blockly/field-colour/dist/index.js"></script>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; -webkit-tap-highlight-color: transparent; }
body { font-family: 'Segoe UI', system-ui, Tahoma, sans-serif; background: #f0f2f5; color: #111827; height: 100vh; display: flex; flex-direction: column; overflow: hidden; touch-action: none; }
#header { background: #fff; padding: 0 20px; height: 54px; display: flex; align-items: center; gap: 12px; border-bottom: 1px solid #e5e7eb; flex-shrink: 0; z-index: 10; box-shadow: 0 1px 4px rgba(0,0,0,0.06); }
#header h1 { font-size: 1.15rem; font-weight: 800; color: #111827; letter-spacing: -0.02em; }
#header .subtitle { font-size: 0.68rem; color: #9ca3af; margin-top: 2px; }
#header-right { margin-left: auto; display: flex; align-items: center; gap: 12px; }
#autosave-indicator { font-size: 0.7rem; color: #9ca3af; display: flex; align-items: center; gap: 4px; opacity: 0; transition: opacity 0.3s; }
#autosave-indicator.visible { opacity: 1; }
#autosave-indicator.saving { color: #2563eb; }
#autosave-indicator.saved { color: #16a34a; }
#challenge-nav { display: flex; align-items: center; gap: 8px; }
.btn-nav { font-size: 0.78rem; font-weight: 600; color: #6b7280; padding: 8px 12px; border-radius: 8px; border: 1px solid #e5e7eb; background: #f8f9fb; transition: all 0.15s; cursor: pointer; min-height: 36px; }
.btn-nav:hover:not(:disabled) { background: #e5e7eb; color: #374151; }
.btn-nav:disabled { opacity: 0.3; cursor: not-allowed; }
#progress-label { font-size: 0.72rem; font-weight: 700; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.08em; }
.btn-back { font-size: 0.78rem; font-weight: 600; color: #6b7280; text-decoration: none; padding: 6px 12px; border-radius: 8px; border: 1px solid #e5e7eb; background: #f8f9fb; transition: all 0.15s; }
.btn-back:hover { background: #e5e7eb; }
#main { display: flex; flex: 1; overflow: hidden; }
#workspace-container { flex: 1; position: relative; min-width: 0; }
#blocklyDiv { position: absolute; top: 0; left: 0; right: 0; bottom: 0; }
#right-panel { width: 377px; flex-shrink: 0; background: #fff; display: flex; flex-direction: column; align-items: stretch; padding: 14px; gap: 10px; border-left: 1px solid #e5e7eb; overflow-y: auto; box-shadow: -2px 0 10px rgba(0,0,0,0.04); }
.r-section { background: #f8f9fb; border-radius: 12px; padding: 12px; border: 1px solid #e5e7eb; display: flex; flex-direction: column; gap: 8px; }
.panel-label { font-size: 0.62rem; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 700; }
#turtle-canvas { display: block; border: 1px solid #e5e7eb; border-radius: 8px; background: #fafafa; width: 100%; height: auto; box-shadow: inset 0 1px 3px rgba(0,0,0,0.04); }
#controls { display: flex; gap: 6px; width: 100%; }
.btn { flex: 1; padding: 12px 6px; border: none; border-radius: 10px; font-size: 0.82rem; font-weight: 700; cursor: pointer; transition: all 0.15s ease; letter-spacing: 0.02em; box-shadow: 0 2px 5px rgba(0,0,0,0.12); min-height: 44px; }
.btn:hover:not(:disabled) { filter: brightness(1.08); transform: translateY(-1px); box-shadow: 0 4px 10px rgba(0,0,0,0.15); }
.btn:active:not(:disabled) { transform: translateY(0); box-shadow: 0 1px 3px rgba(0,0,0,0.1); filter: brightness(0.95); }
.btn:disabled { opacity: 0.35; cursor: not-allowed; box-shadow: none; }
#btn-executar { background: #16a34a; color: #fff; }
#btn-passo { background: #2563eb; color: #fff; }
#btn-parar { background: #dc2626; color: #fff; }
#speed-row { display: flex; align-items: center; gap: 8px; width: 100%; }
#speed-row span { font-size: 0.95rem; flex-shrink: 0; }
#speed-slider { flex: 1; accent-color: #16a34a; cursor: pointer; height: 4px; }
#status-box { background: #f8f9fb; border-radius: 12px; padding: 11px 14px; min-height: 52px; border: 1px solid #e5e7eb; }
#status-title { font-size: 0.6rem; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 700; margin-bottom: 5px; }
#status-text { font-size: 0.85rem; color: #111827; font-weight: 500; }
#project-row { display: flex; gap: 8px; width: 100%; }
.btn-project { background: #f0f2f5; color: #374151; font-size: 0.76rem; border: 1px solid #e5e7eb; font-weight: 600; box-shadow: none; }
.btn-project:hover:not(:disabled) { background: #e5e7eb; transform: none; box-shadow: none; filter: none; }
.blocklyFlyout .blocklyScrollbarKnob { fill-opacity: 0.55 !important; }
.blocklyFlyout .blocklyScrollbarBackground { fill-opacity: 0.18 !important; }
.blocklyFlyout { min-width: 200px !important; }
.blocklyFlyout .blocklyBlockCanvas { min-width: 180px !important; }
/* Emojis menores para caber nos blocos */
.blocklyText { font-size: 14px !important; }
/* Centralizar TODOS os textos do Blockly verticalmente */
#blocklyDiv text { transform: translateY(3px) !important; }
.blocklyFlyout text { transform: translateY(3px) !important; }
#modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.45); display: flex; align-items: center; justify-content: center; z-index: 1000; padding: 20px; }
#modal-overlay.hidden { display: none; }
#modal-card { background: #fff; border-radius: 20px; padding: 36px 32px 28px; max-width: 480px; width: 100%; box-shadow: 0 24px 64px rgba(0,0,0,0.18); display: flex; flex-direction: column; gap: 14px; animation: modalIn 0.25s ease; }
@keyframes modalIn { from{opacity:0;transform:scale(0.94) translateY(12px);}to{opacity:1;transform:scale(1) translateY(0);} }
#modal-progress { font-size: 0.65rem; font-weight: 700; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.1em; }
#modal-dots { display: flex; gap: 6px; margin-top: 4px; }
.modal-dot { width: 8px; height: 8px; border-radius: 50%; background: #e5e7eb; }
.modal-dot.active { background: #16a34a; }
.modal-dot.done { background: #bbf7d0; }
#modal-title { font-size: 1.55rem; font-weight: 800; color: #111827; letter-spacing: -0.02em; line-height: 1.2; }
#modal-description { font-size: 0.95rem; color: #374151; line-height: 1.65; }
#modal-tip { font-size: 0.85rem; color: #4b5563; background: #f0f9ff; border-radius: 10px; padding: 12px 14px; border-left: 3px solid #2563eb; line-height: 1.55; }
#modal-tip:empty { display: none; }
#modal-footer { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-top: 6px; flex-wrap: wrap; }
.modal-btn-primary { padding: 13px 26px; background: #16a34a; color: #fff; border: none; border-radius: 10px; font-size: 0.9rem; font-weight: 700; cursor: pointer; transition: all 0.15s; min-height: 44px; }
.modal-btn-primary:hover { filter: brightness(1.08); transform: translateY(-1px); }
.modal-btn-secondary { padding: 13px 20px; background: #f0f2f5; color: #374151; border: 1px solid #e5e7eb; border-radius: 10px; font-size: 0.9rem; font-weight: 600; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; transition: all 0.15s; min-height: 44px; }
.modal-btn-secondary:hover { background: #e5e7eb; }
.modal-footer-left { display: flex; gap: 10px; }
.modal-footer-right { display: flex; gap: 10px; }
</style>
</head>
<body>
<div id="header">
<svg width="120" height="24" viewBox="0 0 160 30" version="1.1" xmlns="http://www.w3.org/2000/svg" style="flex-shrink:0;">
<rect x="0" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="5" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="10" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="15" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="20" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="0" y="5" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="0" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="5" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="10" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="15" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="0" y="15" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="0" y="20" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="0" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="5" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="10" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="15" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="20" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="28" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="47" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="28" y="5" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="33" y="5" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="42" y="5" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="47" y="5" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="28" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="38" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="47" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="28" y="15" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="47" y="15" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="28" y="20" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="47" y="20" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="28" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="47" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="55" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="60" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="65" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="70" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="75" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="55" y="5" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="75" y="5" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="55" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="75" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="55" y="15" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="75" y="15" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="55" y="20" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="75" y="20" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="55" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="60" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="65" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="70" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="75" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="83" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="88" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="93" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="98" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="103" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="98" y="5" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="98" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="98" y="15" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="83" y="20" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="98" y="20" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="88" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="93" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="98" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="111" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="116" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="121" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="126" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="131" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="111" y="5" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="111" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="116" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="121" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="126" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="111" y="15" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="111" y="20" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="111" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="116" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="121" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="126" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="131" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="139" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="144" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="149" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="154" y="0" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="139" y="5" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="154" y="5" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="139" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="144" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="149" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="154" y="10" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="139" y="15" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="144" y="15" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="139" y="20" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="149" y="20" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="139" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
<rect x="154" y="25" width="4" height="4" rx="0.5" fill="#4c97ff"/>
</svg>
<div id="header-right">
<span id="autosave-indicator"><span id="autosave-icon">💾</span> <span id="autosave-text">Salvo</span></span>
<div id="challenge-nav">
<button class="btn-nav" id="btn-prev" title="Desafio anterior">←</button>
<span id="progress-label">Desafio 1 / 8</span>
<button class="btn-nav" id="btn-next" title="Próximo desafio">→</button>
</div>
<a href="index.html" class="btn-back">Início</a>
</div>
</div>
<div id="main">
<div id="workspace-container">
<div id="blocklyDiv"></div>
</div>
<div id="right-panel">
<div class="r-section">
<div class="panel-label">Tela da Tartaruga</div>
<canvas id="turtle-canvas" width="320" height="320"></canvas>
</div>
<div class="r-section">
<div id="controls">
<button class="btn" id="btn-executar">▶ Executar</button>
<button class="btn" id="btn-passo" disabled>⏭ Passo</button>
<button class="btn" id="btn-parar" disabled>■ Parar</button>
</div>
<div id="speed-row">
<span>🐢</span>
<input type="range" id="speed-slider" min="1" max="10" value="5">
<span>⚡</span>
</div>
</div>
<div id="status-box">
<div id="status-title">Status</div>
<div id="status-text">Pronto</div>
</div>
<div class="r-section">
<div class="panel-label">Projeto</div>
<div id="project-row">
<button class="btn btn-project" id="btn-baixar">⬇ Baixar</button>
<button class="btn btn-project" id="btn-carregar">⬆ Carregar</button>
<input type="file" id="file-input" accept=".json" style="display:none">
</div>
<button class="btn btn-project" id="btn-limpar" style="background: #dc2626; color: #fff; margin-top: 8px;">🗑️ Limpar Tudo</button>
</div>
</div>
</div>
<div id="modal-overlay" class="hidden">
<div id="modal-card">
<div>
<div id="modal-progress"></div>
<div id="modal-dots"></div>
</div>
<h2 id="modal-title"></h2>
<p id="modal-description"></p>
<p id="modal-tip"></p>
<div id="modal-footer"></div>
</div>
</div>
<script>
// ── Block Definitions + Code Generators ────────────────────
if (typeof registerFieldColour === 'function') registerFieldColour();
Blockly.defineBlocksWithJsonArray([
{
type: 'ao_iniciar',
message0: 'Ao iniciar',
nextStatement: null,
colour: '#16a34a',
tooltip: 'Ponto de início — conecte os blocos aqui'
},
{
type: 'logo_frente',
message0: 'Frente',
previousStatement: null, nextStatement: null,
colour: '#CC9900',
tooltip: 'Move 1 passo para frente'
},
{
type: 'logo_tras',
message0: 'Trás',
previousStatement: null, nextStatement: null,
colour: '#CC9900',
tooltip: 'Move 1 passo para trás'
},
{
type: 'logo_mover_direita',
message0: '→ Direita',
previousStatement: null, nextStatement: null,
colour: '#CC9900',
tooltip: 'Move 1 passo para a direita'
},
{
type: 'logo_mover_esquerda',
message0: '← Esquerda',
previousStatement: null, nextStatement: null,
colour: '#CC9900',
tooltip: 'Move 1 passo para a esquerda'
},
{
type: 'logo_mover_cima',
message0: '↑ Cima',
previousStatement: null, nextStatement: null,
colour: '#CC9900',
tooltip: 'Move 1 passo para cima'
},
{
type: 'logo_mover_baixo',
message0: '↓ Baixo',
previousStatement: null, nextStatement: null,
colour: '#CC9900',
tooltip: 'Move 1 passo para baixo'
},
{
type: 'logo_esquerda',
message0: '↶ Girar esquerda',
previousStatement: null, nextStatement: null,
colour: '#CC9900',
tooltip: 'Gira 90° para a esquerda'
},
{
type: 'logo_direita',
message0: '↷ Girar direita',
previousStatement: null, nextStatement: null,
colour: '#CC9900',
tooltip: 'Gira 90° para a direita'
},
{
type: 'logo_cor',
message0: 'Pintar %1',
args0: [{ type: 'field_colour', name: 'COR', colour: '#4361ee' }],
inputsInline: true,
previousStatement: null, nextStatement: null,
colour: '#E91E63',
tooltip: 'Pinta a célula com a cor escolhida'
},
{
type: 'logo_cor_azul',
message0: 'Pintar 🔵',
previousStatement: null, nextStatement: null,
colour: '#E91E63',
tooltip: 'Pinta a célula com azul'
},
{
type: 'func_definir',
message0: 'Definir %1',
args0: [{ type: 'field_input', name: 'NOME', text: 'minha_funcao' }],
message1: '%1',
args1: [{ type: 'input_statement', name: 'CORPO' }],
colour: '#9C27B0',
tooltip: 'Define uma função reutilizável'
},
{
type: 'func_chamar',
message0: 'Chamar %1',
args0: [{ type: 'field_input', name: 'NOME', text: 'minha_funcao' }],
inputsInline: true,
previousStatement: null, nextStatement: null,
colour: '#9C27B0',
tooltip: 'Executa uma função pelo nome'
}
]);
(function () {
const _orig = Blockly.Blocks['controls_repeat_ext'].init;
Blockly.Blocks['controls_repeat_ext'].init = function () {
_orig.call(this);
this.setColour('#2563eb');
};
})();
// ── Code Generators ─────────────────────────────────────────
const gen = Blockly.JavaScript;
const Order = javascript.Order;
gen.forBlock['ao_iniciar'] = function () { return ''; };
gen.forBlock['logo_frente'] = function (block, g) {
return `commands.push({t:'f',n:1});\n`;
};
gen.forBlock['logo_tras'] = function (block, g) {
return `commands.push({t:'b',n:1});\n`;
};
gen.forBlock['logo_mover_direita'] = function (block, g) {
return `commands.push({t:'rd',n:1});\n`;
};
gen.forBlock['logo_mover_esquerda'] = function (block, g) {
return `commands.push({t:'ld',n:1});\n`;
};
gen.forBlock['logo_mover_cima'] = function (block, g) {
return `commands.push({t:'ud',n:1});\n`;
};
gen.forBlock['logo_mover_baixo'] = function (block, g) {
return `commands.push({t:'dd',n:1});\n`;
};
gen.forBlock['logo_esquerda'] = function () { return `commands.push({t:'l',n:90});\n`; };
gen.forBlock['logo_direita'] = function () { return `commands.push({t:'r',n:90});\n`; };
gen.forBlock['logo_cor'] = function (block) {
const cor = block.getFieldValue('COR');
return `commands.push({t:'cor',cor:'${cor}'});\n`;
};
gen.forBlock['logo_cor_azul'] = function () {
return `commands.push({t:'cor',cor:'#2563eb'});\n`;
};
gen.forBlock['func_definir'] = function (block, g) {
const nome = JSON.stringify(block.getFieldValue('NOME') || 'funcao');
const corpo = g.statementToCode(block, 'CORPO');
return `funcoes[${nome}] = function() {\n${corpo}};\n`;
};
gen.forBlock['func_chamar'] = function (block) {
const nome = JSON.stringify(block.getFieldValue('NOME') || 'funcao');
return `if(funcoes[${nome}]) funcoes[${nome}]();\n`;
};
// ── Turtle Engine ────────────────────────────────────────────
const CELL=40;
let GRID_COLS=8,GRID_ROWS=8,CANVAS_W=320,CANVAS_H=320;
let GRID_MIN_X=20,GRID_MAX_X=300,GRID_MIN_Y=20,GRID_MAX_Y=300;
let preDrawnCells={};
function initGrid(cols,rows){
GRID_COLS=cols;GRID_ROWS=rows;CANVAS_W=cols*CELL;CANVAS_H=rows*CELL;
GRID_MIN_X=CELL/2;GRID_MAX_X=(cols-1)*CELL+CELL/2;
GRID_MIN_Y=CELL/2;GRID_MAX_Y=(rows-1)*CELL+CELL/2;
const cv=document.getElementById('turtle-canvas');if(cv){cv.width=CANVAS_W;cv.height=CANVAS_H;}
}
function setPreDrawn(cells){preDrawnCells=cells||{};}
function cellKey(cx,cy){return Math.round((cy-CELL/2)/CELL)+','+Math.round((cx-CELL/2)/CELL);}
function makeTurtle(r=0,c=0){return{x:c*CELL+CELL/2,y:r*CELL+CELL/2,angle:90,penColor:'#e74c3c',painted:{}};}
let turtle=makeTurtle();
function paintCurrentCell(){turtle.painted[cellKey(turtle.x,turtle.y)]=turtle.penColor;}
function render(){
const cv=document.getElementById('turtle-canvas');if(!cv)return;
const ctx=cv.getContext('2d');ctx.clearRect(0,0,CANVAS_W,CANVAS_H);
for(let r=0;r<GRID_ROWS;r++)for(let c=0;c<GRID_COLS;c++){ctx.fillStyle=(r+c)%2===0?'#f8f9fb':'#fff';ctx.fillRect(c*CELL,r*CELL,CELL,CELL);}
for(const[k,col]of Object.entries(preDrawnCells)){const[r,c]=k.split(',').map(Number);ctx.fillStyle=col;ctx.fillRect(c*CELL,r*CELL,CELL,CELL);}
for(const[k,col]of Object.entries(turtle.painted)){const[r,c]=k.split(',').map(Number);ctx.fillStyle=col;ctx.fillRect(c*CELL,r*CELL,CELL,CELL);}
ctx.save();ctx.strokeStyle='rgba(0,0,0,0.12)';ctx.lineWidth=1;
for(let i=0;i<=GRID_COLS;i++){ctx.beginPath();ctx.moveTo(i*CELL,0);ctx.lineTo(i*CELL,CANVAS_H);ctx.stroke();}
for(let i=0;i<=GRID_ROWS;i++){ctx.beginPath();ctx.moveTo(0,i*CELL);ctx.lineTo(CANVAS_W,i*CELL);ctx.stroke();}
ctx.restore();
const rad=turtle.angle*Math.PI/180;ctx.save();ctx.translate(turtle.x,turtle.y);ctx.rotate(rad);
ctx.shadowColor='rgba(0,0,0,0.22)';ctx.shadowBlur=5;ctx.shadowOffsetY=2;
ctx.fillStyle='#3cb371';ctx.strokeStyle='#2d8653';ctx.lineWidth=1.5;
ctx.beginPath();ctx.ellipse(0,2,10,8,0,0,Math.PI*2);ctx.fill();ctx.stroke();
ctx.shadowColor='transparent';ctx.shadowBlur=0;ctx.shadowOffsetY=0;
ctx.strokeStyle='rgba(0,0,0,0.15)';ctx.lineWidth=0.8;
[[-5,-1,5,-1],[-7,4,7,4],[0,-4,0,10],[-5,-1,-7,4],[5,-1,7,4]].forEach(([x1,y1,x2,y2])=>{ctx.beginPath();ctx.moveTo(x1,y1);ctx.lineTo(x2,y2);ctx.stroke();});
ctx.fillStyle='#2d8653';ctx.strokeStyle='#1e6640';ctx.lineWidth=1;
ctx.beginPath();ctx.ellipse(0,-13,5,5,0,0,Math.PI*2);ctx.fill();ctx.stroke();
ctx.fillStyle='#fff';ctx.beginPath();ctx.arc(2,-14,2.2,0,Math.PI*2);ctx.fill();
ctx.fillStyle='#111';ctx.beginPath();ctx.arc(2.5,-14,1.1,0,Math.PI*2);ctx.fill();
ctx.fillStyle='#1e6640';ctx.beginPath();ctx.arc(0,-18,2,0,Math.PI*2);ctx.fill();
ctx.restore();
}
function clampTurtle(){turtle.x=Math.max(GRID_MIN_X,Math.min(GRID_MAX_X,turtle.x));turtle.y=Math.max(GRID_MIN_Y,Math.min(GRID_MAX_Y,turtle.y));}
function applyCmd(cmd){
const rad=turtle.angle*Math.PI/180,dx=Math.sin(rad),dy=-Math.cos(rad);
switch(cmd.t){
case'f':turtle.x+=dx*cmd.n*CELL;turtle.y+=dy*cmd.n*CELL;clampTurtle();break;
case'b':turtle.x-=dx*cmd.n*CELL;turtle.y-=dy*cmd.n*CELL;clampTurtle();break;
case'l':turtle.angle=(turtle.angle-cmd.n%360+360)%360;break;
case'r':turtle.angle=(turtle.angle+cmd.n)%360;break;
case'rd':turtle.angle=90;turtle.x+=cmd.n*CELL;clampTurtle();break;
case'ld':turtle.angle=270;turtle.x-=cmd.n*CELL;clampTurtle();break;
case'ud':turtle.angle=0;turtle.y-=cmd.n*CELL;clampTurtle();break;
case'dd':turtle.angle=180;turtle.y+=cmd.n*CELL;clampTurtle();break;
case'cor':turtle.penColor=cmd.cor;paintCurrentCell();break;
}
render();
}
// ── Execution Engine ─────────────────────────────────────────
const SPEED_DELAYS=[900,500,280,150,80,40,18,8,2,0];
function getDelay(){return SPEED_DELAYS[(parseInt(document.getElementById('speed-slider').value,10)||5)-1]??0;}
let _commands=[],_cmdIndex=0,_mode='idle',_timer=null,_startR=0,_startC=0,_onComplete=null;
function setStatus(t){const e=document.getElementById('status-text');if(e)e.textContent=t;}
function syncButtons(){
const e=document.getElementById('btn-executar'),p=document.getElementById('btn-passo'),s=document.getElementById('btn-parar');
if(e){
if(_mode==='running'){
e.innerHTML='⏸ Pausar';
e.disabled=false;
}else if(_mode==='paused'){
e.innerHTML='▶ Retomar';
e.disabled=false;
}else{
e.innerHTML='▶ Executar';
e.disabled=false;
}
}
if(p)p.disabled=_mode==='running';
if(s)s.disabled=_mode==='idle';
}
function buildCommands(ws){
const start=ws.getTopBlocks(true).find(b=>b.type==='ao_iniciar');
if(!start){setStatus('Conecte blocos ao "Ao iniciar"');return[];}
gen.init(ws);
let fc='';ws.getBlocksByType('func_definir').forEach(b=>{const c=gen.blockToCode(b);fc+=typeof c==='string'?c:'';});
const mc=gen.blockToCode(start);
const full=gen.finish('var funcoes={};\nvar vars={};\n'+fc+(typeof mc==='string'?mc:''));
const cmds=[];try{new Function('commands',full)(cmds);}catch(e){setStatus('Erro: '+e.message);console.error(e);}
return cmds;
}
function _done(msg){console.log('_done chamado com msg:', msg, '_onComplete:', !!_onComplete);clearTimeout(_timer);_mode='idle';_commands=[];_cmdIndex=0;syncButtons();setStatus(msg);if(_onComplete&&msg.startsWith('Concluído')){console.log('Chamando _onComplete');_onComplete();}}
function _tick(ws){if(_mode!=='running')return;applyCmd(_commands[_cmdIndex]);_cmdIndex++;setStatus('Executando… '+_cmdIndex+' / '+_commands.length);if(_cmdIndex<_commands.length){_timer=setTimeout(()=>_tick(ws),getDelay());}else{_done('Concluído ('+_commands.length+' passos)');}}
function doRun(ws){
if(_mode==='paused'){
// Retomar execução
_mode='running';
syncButtons();
setStatus('Executando… '+_cmdIndex+' / '+_commands.length);
_tick(ws);
}else{
// Iniciar nova execução
turtle=makeTurtle(_startR,_startC);
render();
_commands=buildCommands(ws);
if(!_commands.length)return;
_cmdIndex=0;
_mode='running';
syncButtons();
setStatus('Executando… 0 / '+_commands.length);
_tick(ws);
}
}
function doPause(){
if(_mode==='running'){
clearTimeout(_timer);
_mode='paused';
syncButtons();
setStatus('Pausado no passo '+_cmdIndex+' / '+_commands.length);
}
}
function doStep(ws){
if(_mode==='idle'){
turtle=makeTurtle(_startR,_startC);
render();
_commands=buildCommands(ws);
if(!_commands.length)return;
_cmdIndex=0;
_mode='stepping';
syncButtons();
}else if(_mode==='paused'){
// Permitir usar passo quando pausado
_mode='stepping';
syncButtons();
}
if(_cmdIndex>=_commands.length){_done('Concluído');return;}
applyCmd(_commands[_cmdIndex]);
_cmdIndex++;
setStatus('Passo '+_cmdIndex+' / '+_commands.length);
if(_cmdIndex>=_commands.length)_done('Concluído ('+_commands.length+' passos)');
}
function doStop(){clearTimeout(_timer);_done('Parado no passo '+_cmdIndex);}
// ── Challenges ───────────────────────────────────────────────
const CHALLENGES=[
{id:1,title:'Chegue ao objetivo!',description:'A tartaruga precisa chegar até o bloco verde no final da linha. Use o bloco Frente para avançar!',tip:'Cada Frente avança 1 passo. Quantos passos até o bloco verde?',grid:{cols:8,rows:1},startPos:{row:0,col:0},blocks:['logo_frente'],preDrawn:{'0,7':'#22c55e'},validate(){return cellKey(turtle.x,turtle.y)==='0,7';},successMsg:'Você chegou ao objetivo! Aprendeu a mover a tartaruga com precisão.'},
{id:2,title:'Pinte a linha!',description:'Pinte todos os 8 blocos da linha de azul. Use Pintar para colorir a célula e Frente para avançar.',tip:'Pinte a célula atual, avance, pinte a próxima... repita para todos os 8 blocos!',grid:{cols:8,rows:1},startPos:{row:0,col:0},blocks:['logo_frente','logo_cor_azul'],preDrawn:{},validate(){console.log('Validando desafio 2, turtle.painted:', turtle.painted);for(let c=0;c<8;c++){if(!turtle.painted['0,'+c]){console.log('Falta pintar coluna:', c);return false;}}console.log('Desafio 2 completo!');return true;},successMsg:'Incrível! Você pintou a linha inteira — mas foi bem trabalhoso, né? Há uma forma melhor...'},
{id:3,title:'Use o Repita!',description:'Pinte a linha de azul novamente — mas desta vez use o bloco Repita para simplificar o código.',tip:'Coloque Pintar + Frente dentro do Repita. Quantas vezes você precisa repetir?',grid:{cols:8,rows:1},startPos:{row:0,col:0},blocks:['logo_frente','logo_cor_azul','controls_repeat_ext'],preDrawn:{},validate(){for(let c=0;c<8;c++)if(!turtle.painted['0,'+c])return false;return true;},successMsg:'Perfeito! O bloco Repita deixou o código muito menor e mais elegante!'},
{id:4,title:'Crie uma função!',description:'Pinte as duas linhas do grid. Defina uma função que pinte uma linha inteira e chame-a duas vezes — uma por linha!',tip:'Defina uma função com Repita 4×(Pintar + Frente). Depois navegue até a próxima linha e chame a função de novo.',grid:{cols:4,rows:2},startPos:{row:0,col:0},blocks:['logo_frente','logo_esquerda','logo_direita','logo_cor_azul','func_definir','func_chamar','controls_repeat_ext'],preDrawn:{},validate(){for(let r=0;r<2;r++)for(let c=0;c<4;c++)if(!turtle.painted[r+','+c])return false;return true;},successMsg:'Excelente! Funções permitem reutilizar código — defina uma vez, use quantas quiser!'},
{id:5,title:'Desenhe um quadrado!',description:'Pinte o perímetro do quadrado marcado na malha. Use Frente, Girar e Repita para traçar os 4 lados.',tip:'Tente: Repita 4 vezes — Repita 2×(Pintar + Frente), depois Girar direita.',grid:{cols:8,rows:8},startPos:{row:2,col:2},blocks:['logo_frente','logo_esquerda','logo_direita','logo_cor','func_definir','func_chamar','controls_repeat_ext'],preDrawn:{'2,2':'#e0e0e0','2,3':'#e0e0e0','2,4':'#e0e0e0','3,4':'#e0e0e0','4,4':'#e0e0e0','4,3':'#e0e0e0','4,2':'#e0e0e0','3,2':'#e0e0e0'},validate(){return['2,2','2,3','2,4','3,4','4,4','4,3','4,2','3,2'].every(k=>turtle.painted[k]);},successMsg:'Fantástico! Você desenhou um quadrado usando código. Você é um(a) programador(a)!'},
{id:6,title:'Moldura!',description:'Pinte apenas as bordas da tela - o perímetro completo do grid 8×8.',tip:'Use Repita para cada lado. Depois de pintar um lado, gire para o próximo!',grid:{cols:8,rows:8},startPos:{row:0,col:0},blocks:['logo_frente','logo_esquerda','logo_direita','logo_cor','func_definir','func_chamar','controls_repeat_ext'],preDrawn:{},validate(){const bordas=['0,0','0,1','0,2','0,3','0,4','0,5','0,6','0,7','1,7','2,7','3,7','4,7','5,7','6,7','7,7','7,6','7,5','7,4','7,3','7,2','7,1','7,0','6,0','5,0','4,0','3,0','2,0','1,0'];return bordas.every(k=>turtle.painted[k]);},successMsg:'Excelente! Você criou uma moldura perfeita ao redor da tela!'},
{id:7,title:'Mude os olhos!',description:'O personagem tem olhos pretos. Mude os 2 blocos pretos para azul!',tip:'Navegue até cada olho preto e pinte de azul. Use os blocos de movimento e girar para chegar lá!',grid:{cols:8,rows:9},startPos:{row:0,col:0},blocks:['logo_frente','logo_tras','logo_mover_direita','logo_mover_esquerda','logo_mover_cima','logo_mover_baixo','logo_esquerda','logo_direita','logo_cor','controls_repeat_ext'],preDrawn:{'1,2':'#dc2626','1,3':'#dc2626','1,4':'#dc2626','1,5':'#dc2626','2,2':'#dc2626','2,3':'#dc2626','2,4':'#dc2626','2,6':'#dc2626','3,2':'#fef08a','3,3':'#000000','3,4':'#fef08a','3,5':'#000000','4,2':'#fef08a','4,3':'#fef08a','4,4':'#fef08a','4,5':'#fef08a','5,1':'#dc2626','5,2':'#2563eb','5,3':'#dc2626','5,4':'#dc2626','5,5':'#2563eb','5,6':'#dc2626','6,1':'#fef08a','6,2':'#2563eb','6,3':'#2563eb','6,4':'#2563eb','6,5':'#2563eb','6,6':'#fef08a','7,2':'#2563eb','7,3':'#2563eb','7,4':'#2563eb','7,5':'#2563eb','8,2':'#9B4D24','8,5':'#9B4D24'},validate(){console.log('Validando desafio 7, turtle.painted:', turtle.painted);return turtle.painted['3,3']&&turtle.painted['3,5'];},successMsg:'Perfeito! Você mudou os olhos de preto para azul! Usou bem os comandos de navegação!'},
{id:8,title:'Pinte a letra E!',description:'A letra E está desenhada em cinza. Pinte toda a letra com a cor que você quiser!',tip:'Navegue por cada linha da letra E e pinte todos os blocos. Use loops e funções para simplificar! Cuidado: pinte APENAS a letra, sem blocos extras!',grid:{cols:8,rows:8},startPos:{row:0,col:0},blocks:['logo_frente','logo_tras','logo_mover_direita','logo_mover_cima','logo_esquerda','logo_direita','logo_cor','func_definir','func_chamar','controls_repeat_ext'],preDrawn:{'1,2':'#d1d5db','1,3':'#d1d5db','1,4':'#d1d5db','1,5':'#d1d5db','2,2':'#d1d5db','3,2':'#d1d5db','3,3':'#d1d5db','3,4':'#d1d5db','3,5':'#d1d5db','4,2':'#d1d5db','5,2':'#d1d5db','5,3':'#d1d5db','5,4':'#d1d5db','5,5':'#d1d5db'},validate(){const letraE=['1,2','1,3','1,4','1,5','2,2','3,2','3,3','3,4','3,5','4,2','5,2','5,3','5,4','5,5'];if(!letraE.every(k=>turtle.painted[k]))return false;const painted=Object.keys(turtle.painted);return painted.length===letraE.length&&painted.every(k=>letraE.includes(k));},successMsg:'Incrível! Você coloriu a letra E completamente! Ótimo trabalho navegando pela forma!'}
];
// ── Toolbox builder ──────────────────────────────────────────
const BLOCK_XML={
logo_frente:`<block type="logo_frente"></block>`,
logo_mover_esquerda:`<block type="logo_mover_esquerda"></block>`,
logo_mover_baixo:`<block type="logo_mover_baixo"></block>`,
logo_esquerda:`<block type="logo_esquerda"></block>`,
logo_direita:`<block type="logo_direita"></block>`,
logo_cor:`<block type="logo_cor"></block>`,
logo_cor_azul:`<block type="logo_cor_azul"></block>`,
controls_repeat_ext:`<block type="controls_repeat_ext"><value name="TIMES"><block type="math_number"><field name="NUM">4</field></block></value></block>`,
func_definir:`<block type="func_definir"></block>`,
func_chamar:`<block type="func_chamar"></block>`,
};
function buildToolboxXml(blocks){return'<xml xmlns="https://developers.google.com/blockly/xml">\n'+blocks.map(t=>BLOCK_XML[t]?' '+BLOCK_XML[t]:'').filter(Boolean).join('\n')+'\n <sep gap="300"></sep>\n</xml>';}
// ── Flyout freeze ────────────────────────────────────────────
function freezeFlyoutScale(ws){
const orig=ws.setScale;
ws.setScale=function(s){orig.call(this,s);const fly=this.getFlyout&&this.getFlyout(),fw=fly&&(fly.getWorkspace?fly.getWorkspace():fly.workspace_);if(!fw||fw.scale===1)return;fw.scale=1;const cv=fw.svgBlockCanvas_;if(cv){const t=cv.getAttribute('transform')||'';cv.setAttribute('transform',t.replace(/scale\s*\([^)]+\)/g,'').trim());}};
requestAnimationFrame(()=>requestAnimationFrame(()=>{
const fly=ws.getFlyout(),flyEl=document.querySelector('.blocklyFlyout'),cv=flyEl&&flyEl.querySelector('.blocklyBlockCanvas');
if(fly){const grp=fly.svgGroup_,baseW=Math.max(200,(typeof fly.width_==='number'&&fly.width_>0)?fly.width_:(grp&&parseFloat(grp.getAttribute('width')))||0);if(baseW>0){try{Object.defineProperty(fly,'width_',{get:()=>baseW,set:()=>{},configurable:true});}catch(e){}}}
if(!cv)return;let busy=false;new MutationObserver(()=>{if(busy)return;const t=cv.getAttribute('transform')||'',f=t.replace(/scale\s*\([^)]+\)/g,'').trim();if(f!==t){busy=true;cv.setAttribute('transform',f);busy=false;}}).observe(cv,{attributes:true,attributeFilter:['transform']});
}));
}
// ── Modal ────────────────────────────────────────────────────
function showModal({progress,title,description,tip,primaryLabel,primaryAction,secondaryLabel,secondaryHref,reviewButton}){
console.log('showModal chamado:', {progress, title, primaryLabel});
document.getElementById('modal-progress').textContent=progress;
document.getElementById('modal-title').textContent=title;
document.getElementById('modal-description').textContent=description;
document.getElementById('modal-tip').textContent=tip||'';
const dots=document.getElementById('modal-dots');
dots.innerHTML=CHALLENGES.map((_,i)=>`<div class="modal-dot ${i<currentIdx?'done':i===currentIdx?'active':''}"></div>`).join('');
const footer=document.getElementById('modal-footer');footer.innerHTML='';
// Botões da esquerda (secundários)
const leftDiv=document.createElement('div');
leftDiv.className='modal-footer-left';
if(secondaryLabel&&secondaryHref){
const a=document.createElement('a');
a.href=secondaryHref;
a.className='modal-btn-secondary';
a.textContent=secondaryLabel;
leftDiv.appendChild(a);
}
if(reviewButton){
const reviewBtn=document.createElement('button');
reviewBtn.className='modal-btn-secondary';
reviewBtn.textContent='👁️ Rever código';
reviewBtn.onclick=closeModal;
leftDiv.appendChild(reviewBtn);
}
footer.appendChild(leftDiv);
// Botões da direita (primário)
const rightDiv=document.createElement('div');
rightDiv.className='modal-footer-right';
const btn=document.createElement('button');
btn.className='modal-btn-primary';
btn.textContent=primaryLabel;
btn.onclick=primaryAction;
rightDiv.appendChild(btn);
footer.appendChild(rightDiv);
document.getElementById('modal-overlay').classList.remove('hidden');
}
function closeModal(){document.getElementById('modal-overlay').classList.add('hidden');}
// ── Challenge loader ─────────────────────────────────────────
let currentIdx=0,ws;
function updateNavButtons(){
document.getElementById('btn-prev').disabled=currentIdx<=0;
document.getElementById('btn-next').disabled=currentIdx>=CHALLENGES.length-1;
}
function loadChallenge(idx){
console.log('loadChallenge chamado com índice:', idx);
currentIdx=idx;
const ch=CHALLENGES[idx];
console.log('Carregando desafio:', ch.title);
document.getElementById('progress-label').textContent='Desafio '+(idx+1)+' / '+CHALLENGES.length;
updateNavButtons();
initGrid(ch.grid.cols,ch.grid.rows);
setPreDrawn(ch.preDrawn);
_startR=ch.startPos.row;_startC=ch.startPos.col;
turtle=makeTurtle(_startR,_startC);render();
_onComplete=()=>{if(ch.validate())showSuccessModal(ch);};
const xml=buildToolboxXml(ch.blocks);
if(ws){
ws.updateToolbox(xml);
ws.getAllBlocks().filter(b=>b.type!=='ao_iniciar').forEach(b=>b.dispose());
requestAnimationFrame(()=>{Blockly.svgResize(ws);ws.updateToolbox(xml);});
}
// Salvar desafio atual
saveCurrentChallenge();
// Tentar carregar progresso salvo deste desafio
loadChallengeProgress(idx);
showModal({progress:'Desafio '+(idx+1)+' de '+CHALLENGES.length,title:ch.title,description:ch.description,tip:ch.tip,primaryLabel:idx===0?'Vamos lá! 🚀':'Começar desafio!',primaryAction:closeModal,secondaryLabel:'Início',secondaryHref:'index.html'});
}
function showSuccessModal(ch){
console.log('showSuccessModal chamado para desafio:', currentIdx+1);
const completedIdx=currentIdx; // Captura o índice do desafio que acabou de completar
const nextIdx=completedIdx+1; // Próximo desafio
const isLast=completedIdx>=CHALLENGES.length-1;
showModal({progress:'Desafio '+(completedIdx+1)+' de '+CHALLENGES.length,title:'🎉 Parabéns!',description:ch.successMsg,tip:'',primaryLabel:isLast?'🏁 Voltar ao início':'Próximo desafio →',primaryAction:isLast?()=>{window.location.href='index.html';}:()=>{console.log('Clicou em Próximo, indo para índice:', nextIdx);loadChallenge(nextIdx);},secondaryLabel:'← Início',secondaryHref:'index.html',reviewButton:true});
}
// ── Auto-save ────────────────────────────────────────────────
const AUTOSAVE_CHALLENGE_KEY='emoji-coder-tutorial-challenge';
const AUTOSAVE_PROGRESS_PREFIX='emoji-coder-tutorial-progress-';
let autoSaveTimer=null;
const indicator=document.getElementById('autosave-indicator');
const indicatorText=document.getElementById('autosave-text');
function showSaveIndicator(state){
indicator.classList.remove('saving','saved');
indicator.classList.add('visible',state);
indicatorText.textContent=state==='saving'?'Salvando...':'Salvo';
if(state==='saved'){
setTimeout(()=>indicator.classList.remove('visible'),2000);
}
}
function saveCurrentChallenge(){
try{
localStorage.setItem(AUTOSAVE_CHALLENGE_KEY,currentIdx.toString());
}catch(e){console.error('Erro ao salvar desafio atual:',e);}
}
function loadLastChallenge(){
try{
const saved=localStorage.getItem(AUTOSAVE_CHALLENGE_KEY);
if(saved!==null){
const idx=parseInt(saved,10);
if(!isNaN(idx)&&idx>=0&&idx<CHALLENGES.length)return idx;
}
}catch(e){console.error('Erro ao carregar desafio:',e);}
return 0;
}
function saveChallengeProgress(){
try{
showSaveIndicator('saving');
const state=Blockly.serialization.workspaces.save(ws);
const key=AUTOSAVE_PROGRESS_PREFIX+currentIdx;
localStorage.setItem(key,JSON.stringify({state,timestamp:Date.now()}));
setTimeout(()=>showSaveIndicator('saved'),300);
}catch(e){console.error('Erro ao salvar progresso:',e);}
}
function loadChallengeProgress(idx){
try{
const key=AUTOSAVE_PROGRESS_PREFIX+idx;
const saved=localStorage.getItem(key);
if(!saved)return false;
const data=JSON.parse(saved);
if(data.state){
// Aguarda um frame para garantir que o workspace está pronto
requestAnimationFrame(()=>{
Blockly.serialization.workspaces.load(data.state,ws);
showSaveIndicator('saved');
});
return true;
}
}catch(e){console.error('Erro ao carregar progresso:',e);}
return false;
}
function scheduleAutoSave(){
clearTimeout(autoSaveTimer);
autoSaveTimer=setTimeout(()=>{
saveChallengeProgress();
saveCurrentChallenge();
},1000);
}
// ── Init ─────────────────────────────────────────────────────
const startIdx=loadLastChallenge(); // Carrega último desafio visitado
initGrid(CHALLENGES[startIdx].grid.cols,CHALLENGES[startIdx].grid.rows);
ws=Blockly.inject('blocklyDiv',{
toolbox:buildToolboxXml(CHALLENGES[startIdx].blocks),scrollbars:true,trashcan:true,
zoom:{controls:true,wheel:false,startScale:1.0,maxScale:3,minScale:0.3},
grid:{spacing:24,length:6,colour:'#e0e0e0',snap:false}
});
ws.registerButtonCallback('noop',()=>{});
Blockly.Xml.domToWorkspace(Blockly.utils.xml.textToDom('<xml><block type="ao_iniciar" x="40" y="40" deletable="false"></block></xml>'),ws);
freezeFlyoutScale(ws);
// Ativar auto-save quando workspace muda
ws.addChangeListener(scheduleAutoSave);
window.addEventListener('wheel',function(e){
const fl=document.querySelector('.blocklyFlyout');if(!fl)return;
const r=fl.getBoundingClientRect();if(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)return;
e.preventDefault();e.stopImmediatePropagation();
const fly=ws.getFlyout();if(!fly)return;
const fw=fly.getWorkspace?fly.getWorkspace():fly.workspace_,cv=fw&&fw.svgBlockCanvas_;if(!cv)return;
const t=cv.getAttribute('transform')||'',m=t.match(/translate\s*\(\s*([-\d.]+)\s*,\s*([-\d.]+)\s*\)/);
cv.setAttribute('transform',`translate(${m?parseFloat(m[1]):0},${Math.min(0,(m?parseFloat(m[2]):0)-e.deltaY)})`);
},{capture:true,passive:false});
document.getElementById('blocklyDiv').addEventListener('wheel',function(e){
const fl=document.querySelector('.blocklyFlyout');
if(fl){const r=fl.getBoundingClientRect();if(e.clientX>=r.left&&e.clientX<=r.right&&e.clientY>=r.top&&e.clientY<=r.bottom)return;}
const svg=ws.getParentSvg(),pt=svg.createSVGPoint();pt.x=e.clientX;pt.y=e.clientY;
const ctm=svg.getScreenCTM();if(ctm){const sp=pt.matrixTransform(ctm.inverse());ws.zoom(sp.x,sp.y,e.deltaY<0?1:-1);}
e.preventDefault();
},{passive:false});
function resize(){const area=document.getElementById('workspace-container'),div=document.getElementById('blocklyDiv');div.style.left='0';div.style.top='0';div.style.width=area.offsetWidth+'px';div.style.height=area.offsetHeight+'px';Blockly.svgResize(ws);}
window.addEventListener('resize',resize);resize();
requestAnimationFrame(()=>{
resize();
Blockly.svgResize(ws);
ws.updateToolbox(buildToolboxXml(CHALLENGES[startIdx].blocks));
// Aguarda mais um frame para garantir que tudo foi renderizado
requestAnimationFrame(()=>{
loadChallenge(startIdx);
});
});
document.getElementById('btn-executar').addEventListener('click',()=>{
if(_mode==='running'){
doPause();
}else{
doRun(ws);
}
});
document.getElementById('btn-passo').addEventListener('click',()=>doStep(ws));
document.getElementById('btn-parar').addEventListener('click',doStop);
document.getElementById('btn-prev').addEventListener('click',()=>{
if(currentIdx>0)loadChallenge(currentIdx-1);
});
document.getElementById('btn-next').addEventListener('click',()=>{
if(currentIdx<CHALLENGES.length-1)loadChallenge(currentIdx+1);
});
document.getElementById('btn-baixar').addEventListener('click',()=>{
const blob=new Blob([JSON.stringify(Blockly.serialization.workspaces.save(ws),null,2)],{type:'application/json'});
const url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='desafio.json';a.click();URL.revokeObjectURL(url);
});
const fi=document.getElementById('file-input');
document.getElementById('btn-carregar').addEventListener('click',()=>fi.click());
fi.addEventListener('change',function(){const f=this.files[0];if(!f)return;const r=new FileReader();r.onload=ev=>{try{Blockly.serialization.workspaces.load(JSON.parse(ev.target.result),ws);setStatus('Carregado!');}catch(e){setStatus('Erro ao carregar');}};r.readAsText(f);this.value='';});
document.getElementById('btn-limpar').addEventListener('click',()=>{
if(confirm('⚠️ Tem certeza que deseja apagar todos os blocos?\n\nEsta ação não pode ser desfeita.')){
ws.getAllBlocks().filter(b=>b.type!=='ao_iniciar').forEach(b=>b.dispose());
turtle=makeTurtle(_startR,_startC);
render();
setStatus('Blocos apagados');
setTimeout(()=>setStatus('Pronto'),2000);
}
});
</script>
</body>
</html>