-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpythoncopy.js
More file actions
5974 lines (5220 loc) · 220 KB
/
Copy pathpythoncopy.js
File metadata and controls
5974 lines (5220 loc) · 220 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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
window.pythonCopyVersion = 15;
let currentURL = '';
let executionCancelled = false;
let hasUnsavedChanges = false;
let savedEditorCode = '';
let pasteCount = 0;
let inputResolver = null;
let pyodideReadyPromise = null;
let pyodideInstance = null;
window.currentAppMode = 'edit';
let currentQuizMetadata = {
testCases: [],
nextUrl: null,
isEnd: false,
courseTitle: "Python Algorithms",
links: []
};
let loadedMetadataLinks = [];
// Shared blockly state is declared on window by pythoncopyblocks.js
if (typeof window.updateBlocksButtonState !== 'function') {
window.updateBlocksButtonState = function() {};
}
function wrapPythonComment(comment, maxLength = 75) {
if (!comment) return '';
let text = comment;
let prefix = '# instructions: ';
if (comment.toLowerCase().startsWith('# instructions:')) {
text = comment.slice(15).trim();
} else if (comment.startsWith('# ')) {
text = comment.slice(2).trim();
prefix = '# ';
}
const words = text.split(/\s+/);
const lines = [];
let currentLine = prefix;
for (const word of words) {
if (currentLine.length + word.length + 1 > maxLength && currentLine !== prefix && currentLine !== '# ') {
lines.push(currentLine);
currentLine = '# ' + word;
} else {
if (currentLine === prefix || currentLine === '# ') {
currentLine += word;
} else {
currentLine += ' ' + word;
}
}
}
if (currentLine) {
lines.push(currentLine);
}
return lines.join('\n');
}
function getChallengeDescription(comment) {
return String(comment || '')
.split(/\n#\s*(?:input|output|end)\b/i)[0]
.replace(/^#\s*instructions:\s*/i, '')
.trim();
}
window.parseBlocklyXmlText = function(xmlText) {
if (typeof Blockly === 'undefined') {
throw new Error('Blockly is not loaded.');
}
if (typeof xmlText === 'string') {
xmlText = xmlText.replace(/^\ufeff/, '').trim();
}
if (!xmlText) {
throw new Error('Empty Blockly XML.');
}
if (Blockly.Xml.textToDom) {
return Blockly.Xml.textToDom(xmlText);
}
if (Blockly.utils && Blockly.utils.xml && Blockly.utils.xml.textToDom) {
return Blockly.utils.xml.textToDom(xmlText);
}
const parsed = new DOMParser().parseFromString(xmlText, 'text/xml');
const errorNode = parsed.querySelector('parsererror');
if (errorNode) {
throw new Error(errorNode.textContent || 'Invalid Blockly XML.');
}
return parsed.documentElement;
};
let displayTraceLog = [];
let displayInputHistory = [];
let displayTraceStatus = 'ready'; // ready, tracing, waiting_input, finished, error
let displayPendingPrompt = '';
let displayFinalOutput = '';
let displayCurrentStep = 0;
let displayMaxRevealedStep = -1;
let displayTimeout = null;
let btnPlayStatus = 'idle';
let isTracing = false;
let isAwaitingDisplayInput = false;
let copyButtonTimeout = null;
// --- Editor Session Playback State ---
let playbackHistory = [];
let playbackIndex = -1;
let playbackInterval = null;
let isPlaybackPlaying = false;
let originalCodeBeforePlayback = '';
let saveHistoryTimeout = null;
// --- Turtle Graphics JS State & Bridge ---
let turtleCommands = [];
let turtleX = 0;
let turtleY = 0;
let turtleHeading = 0;
let turtleVisible = true;
let turtleBgColor = '#ffffff';
let drawPending = false;
function queueDraw() {
if (!drawPending) {
drawPending = true;
requestAnimationFrame(() => {
drawEverything();
drawPending = false;
});
}
}
window.addTurtleLine = function (x1, y1, x2, y2, color, width) {
turtleCommands.push({ type: 'line', x1, y1, x2, y2, color, width });
queueDraw();
};
window.addTurtleFill = function (pathJson, color) {
try {
const path = JSON.parse(pathJson);
turtleCommands.push({ type: 'fill', path, color });
queueDraw();
} catch (e) {
console.error('Error parsing fill path:', e);
}
};
window.addTurtleWrite = function (text, x, y, color, align, font) {
turtleCommands.push({ type: 'write', text, x, y, color, align, font });
queueDraw();
};
window.addTurtleDot = function (x, y, radius, color) {
turtleCommands.push({ type: 'dot', x, y, radius, color });
queueDraw();
};
window.updateTurtleState = function (x, y, heading, visible) {
turtleX = x;
turtleY = y;
turtleHeading = heading;
turtleVisible = visible;
queueDraw();
};
window.clearTurtleCanvas = function () {
turtleCommands = [];
queueDraw();
};
window.setTurtleBgColor = function (color) {
turtleBgColor = color;
queueDraw();
};
window.setupTurtleCanvas = function (width, height) {
const canvas = document.getElementById('turtleCanvas');
if (canvas) {
canvas.width = width || 400;
canvas.height = height || 400;
drawEverything();
}
};
let turtleShape = 'classic'; // classic, turtle, circle, square, triangle
window.setTurtleShape = function (shapeName) {
turtleShape = shapeName || 'classic';
queueDraw();
};
window.getTurtleShape = function () {
return turtleShape;
};
window.resetTurtleCanvas = function () {
turtleCommands = [];
turtleX = 0;
turtleY = 0;
turtleHeading = 0;
turtleVisible = true;
turtleBgColor = '#ffffff';
turtleShape = 'classic';
queueDraw();
};
window.getTurtleSnapshot = function () {
return JSON.stringify({
commands: turtleCommands,
x: turtleX,
y: turtleY,
heading: turtleHeading,
visible: turtleVisible,
bgColor: turtleBgColor,
shape: turtleShape
});
};
window.downloadCanvasImage = function () {
if (drawPending) {
drawEverything();
}
const canvas = document.getElementById('turtleCanvas');
if (!canvas) return;
const link = document.createElement('a');
link.download = 'turtle_drawing.png';
link.href = canvas.toDataURL();
link.click();
};
function drawEverything() {
const canvas = document.getElementById('turtleCanvas');
if (!canvas) return;
const ctx = canvas.getContext('2d');
const cx = canvas.width / 2;
const cy = canvas.height / 2;
// Clear and fill background
ctx.fillStyle = turtleBgColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Coordinate translators
function tx(x) { return cx + x; }
function ty(y) { return cy - y; } // mathematical Y goes up, canvas Y goes down
// Draw all commands
for (const cmd of turtleCommands) {
if (cmd.type === 'line') {
ctx.beginPath();
ctx.moveTo(tx(cmd.x1), ty(cmd.y1));
ctx.lineTo(tx(cmd.x2), ty(cmd.y2));
ctx.strokeStyle = cmd.color;
ctx.lineWidth = cmd.width;
ctx.lineCap = 'round';
ctx.stroke();
} else if (cmd.type === 'fill') {
ctx.beginPath();
const path = cmd.path;
if (path.length > 0) {
ctx.moveTo(tx(path[0][0]), ty(path[0][1]));
for (let i = 1; i < path.length; i++) {
ctx.lineTo(tx(path[i][0]), ty(path[i][1]));
}
ctx.closePath();
ctx.fillStyle = cmd.color;
ctx.fill();
}
} else if (cmd.type === 'write') {
ctx.fillStyle = cmd.color;
ctx.font = cmd.font;
ctx.textAlign = cmd.align === 'left' ? 'left' : (cmd.align === 'right' ? 'right' : 'center');
ctx.fillText(cmd.text, tx(cmd.x), ty(cmd.y));
} else if (cmd.type === 'dot') {
ctx.beginPath();
ctx.arc(tx(cmd.x), ty(cmd.y), cmd.radius, 0, 2 * Math.PI);
ctx.fillStyle = cmd.color;
ctx.fill();
}
}
// Draw turtle cursor
if (turtleVisible) {
if (turtleShape === 'turtle') {
ctx.save();
ctx.translate(tx(turtleX), ty(turtleY));
ctx.rotate(-turtleHeading * Math.PI / 180);
// Draw legs
ctx.fillStyle = '#34d399';
ctx.strokeStyle = '#047857';
ctx.lineWidth = 1;
// Front-left leg
ctx.beginPath();
ctx.ellipse(5, -5, 3, 1.5, Math.PI / 4, 0, 2 * Math.PI);
ctx.fill(); ctx.stroke();
// Front-right leg
ctx.beginPath();
ctx.ellipse(5, 5, 3, 1.5, -Math.PI / 4, 0, 2 * Math.PI);
ctx.fill(); ctx.stroke();
// Back-left leg
ctx.beginPath();
ctx.ellipse(-4, -4, 2.5, 1.2, -Math.PI / 4, 0, 2 * Math.PI);
ctx.fill(); ctx.stroke();
// Back-right leg
ctx.beginPath();
ctx.ellipse(-4, 4, 2.5, 1.2, Math.PI / 4, 0, 2 * Math.PI);
ctx.fill(); ctx.stroke();
// Tail
ctx.beginPath();
ctx.moveTo(-7, 0);
ctx.lineTo(-10, 0);
ctx.strokeStyle = '#34d399';
ctx.lineWidth = 1.5;
ctx.stroke();
// Shell/body
ctx.beginPath();
ctx.ellipse(0, 0, 7, 5, 0, 0, 2 * Math.PI);
ctx.fillStyle = '#10b981';
ctx.strokeStyle = '#047857';
ctx.lineWidth = 1;
ctx.fill(); ctx.stroke();
// Head
ctx.beginPath();
ctx.arc(9, 0, 2.5, 0, 2 * Math.PI);
ctx.fillStyle = '#34d399';
ctx.fill(); ctx.stroke();
ctx.restore();
} else if (turtleShape === 'circle') {
ctx.save();
ctx.translate(tx(turtleX), ty(turtleY));
ctx.beginPath();
ctx.arc(0, 0, 6, 0, 2 * Math.PI);
ctx.fillStyle = '#ec4899';
ctx.fill();
ctx.strokeStyle = '#1e293b';
ctx.lineWidth = 1.5;
ctx.stroke();
ctx.restore();
} else if (turtleShape === 'square') {
ctx.save();
ctx.translate(tx(turtleX), ty(turtleY));
ctx.rotate(-turtleHeading * Math.PI / 180);
ctx.beginPath();
ctx.rect(-5, -5, 10, 10);
ctx.fillStyle = '#ec4899';
ctx.fill();
ctx.strokeStyle = '#1e293b';
ctx.lineWidth = 1.5;
ctx.stroke();
ctx.restore();
} else if (turtleShape === 'triangle') {
ctx.save();
ctx.translate(tx(turtleX), ty(turtleY));
ctx.rotate(-turtleHeading * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(8, 0);
ctx.lineTo(-6, -6);
ctx.lineTo(-6, 6);
ctx.closePath();
ctx.fillStyle = '#ec4899';
ctx.fill();
ctx.strokeStyle = '#1e293b';
ctx.lineWidth = 1.5;
ctx.stroke();
ctx.restore();
} else { // classic or arrow
ctx.save();
ctx.translate(tx(turtleX), ty(turtleY));
ctx.rotate(-turtleHeading * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(10, 0);
ctx.lineTo(-6, -6);
ctx.lineTo(-3, 0);
ctx.lineTo(-6, 6);
ctx.closePath();
ctx.fillStyle = '#ec4899'; // nice modern pink/magenta color
ctx.fill();
ctx.strokeStyle = '#1e293b';
ctx.lineWidth = 1.5;
ctx.stroke();
ctx.restore();
}
}
}
const turtleShimPythonCode = `
import js
import json
import math
class Turtle:
def __init__(self):
self._x = 0.0
self._y = 0.0
self._heading = 0.0
self._is_down = True
self._pencolor = "black"
self._fillcolor = "black"
self._width = 1.0
self._visible = True
self._is_filling = False
self._fill_path = []
self._update_js_state()
def _update_js_state(self):
js.updateTurtleState(self._x, self._y, self._heading, self._visible)
def forward(self, distance):
rad = math.radians(self._heading)
new_x = self._x + distance * math.cos(rad)
new_y = self._y + distance * math.sin(rad)
if self._is_down:
js.addTurtleLine(self._x, self._y, new_x, new_y, self._pencolor, self._width)
self._x = new_x
self._y = new_y
if self._is_filling:
self._fill_path.append((self._x, self._y))
self._update_js_state()
fd = forward
def backward(self, distance):
self.forward(-distance)
bk = backward
back = backward
def right(self, angle):
self._heading = (self._heading - angle) % 360
self._update_js_state()
rt = right
def left(self, angle):
self._heading = (self._heading + angle) % 360
self._update_js_state()
lt = left
def penup(self):
self._is_down = False
pu = penup
up = penup
def pendown(self):
self._is_down = True
pd = pendown
down = pendown
def isdown(self):
return self._is_down
def goto(self, x, y=None):
if y is None:
if isinstance(x, (tuple, list)):
target_x, target_y = x[0], x[1]
else:
target_x, target_y = x.xcor(), x.ycor()
else:
target_x, target_y = x, y
if self._is_down:
js.addTurtleLine(self._x, self._y, target_x, target_y, self._pencolor, self._width)
self._x = target_x
self._y = target_y
if self._is_filling:
self._fill_path.append((self._x, self._y))
self._update_js_state()
setpos = goto
setposition = goto
def setheading(self, to_angle):
self._heading = to_angle % 360
self._update_js_state()
seth = setheading
def home(self):
self.goto(0.0, 0.0)
self.setheading(0.0)
def xcor(self):
return self._x
def ycor(self):
return self._y
def pos(self):
return (self._x, self._y)
position = pos
def heading(self):
return self._heading
def pencolor(self, color=None):
if color is None:
return self._pencolor
self._pencolor = color
def fillcolor(self, color=None):
if color is None:
return self._fillcolor
self._fillcolor = color
def color(self, color1=None, color2=None):
if color1 is None:
return (self._pencolor, self._fillcolor)
if color2 is None:
self._pencolor = color1
self._fillcolor = color1
else:
self._pencolor = color1
self._fillcolor = color2
def pensize(self, width=None):
if width is None:
return self._width
self._width = float(width)
width = pensize
def hideturtle(self):
self._visible = False
self._update_js_state()
ht = hideturtle
def showturtle(self):
self._visible = True
self._update_js_state()
st = showturtle
def isvisible(self):
return self._visible
def begin_fill(self):
self._is_filling = True
self._fill_path = [(self._x, self._y)]
def end_fill(self):
if self._is_filling:
self._is_filling = False
if len(self._fill_path) > 2:
js.addTurtleFill(json.dumps(self._fill_path), self._fillcolor)
self._update_js_state()
def circle(self, radius, extent=None, steps=None):
if extent is None:
extent = 360.0
if steps is None:
steps = int(min(abs(radius) * 2 + 10, 120))
steps = max(steps, 24)
start_heading_rad = math.radians(self._heading)
dir_factor = 1.0 if radius >= 0 else -1.0
center_angle_rad = start_heading_rad + (math.pi / 2.0)
abs_r = abs(radius)
cx = self._x + radius * math.cos(center_angle_rad)
cy = self._y + radius * math.sin(center_angle_rad)
start_angle = center_angle_rad + (math.pi if radius >= 0 else 0.0)
total_rot = math.radians(extent)
for i in range(1, steps + 1):
t = float(i) / steps
current_rot = dir_factor * total_rot * t
angle = start_angle + current_rot
next_x = cx + abs_r * math.cos(angle)
next_y = cy + abs_r * math.sin(angle)
self.goto(next_x, next_y)
self.setheading(self._heading + dir_factor * extent)
def write(self, arg, move=False, align="left", font=("Arial", 8, "normal")):
font_str = f"{font[2]} {font[1]}pt {font[0]}" if len(font) >= 3 else f"{font[1]}pt {font[0]}"
js.addTurtleWrite(str(arg), self._x, self._y, self._pencolor, align, font_str)
def dot(self, size=None, *color):
if size is not None and not isinstance(size, (int, float)):
color = (size,) + color
size = None
if size is None:
dot_size = max(self._width + 4, self._width * 2)
else:
dot_size = float(size)
dot_color = self._pencolor
if len(color) > 0:
if len(color) == 1:
c = color[0]
if isinstance(c, (list, tuple)) and len(c) == 3:
r = int(c[0]*255) if isinstance(c[0], float) and c[0] <= 1.0 else int(c[0])
g = int(c[1]*255) if isinstance(c[1], float) and c[1] <= 1.0 else int(c[1])
b = int(c[2]*255) if isinstance(c[2], float) and c[2] <= 1.0 else int(c[2])
dot_color = f"rgb({r},{g},{b})"
else:
dot_color = str(c)
elif len(color) == 3:
r = int(color[0]*255) if isinstance(color[0], float) and color[0] <= 1.0 else int(color[0])
g = int(color[1]*255) if isinstance(color[1], float) and color[1] <= 1.0 else int(color[1])
b = int(color[2]*255) if isinstance(color[2], float) and color[2] <= 1.0 else int(color[2])
dot_color = f"rgb({r},{g},{b})"
else:
dot_color = str(color[0])
if isinstance(dot_color, (list, tuple)) and len(dot_color) == 3:
r = int(dot_color[0]*255) if isinstance(dot_color[0], float) and dot_color[0] <= 1.0 else int(dot_color[0])
g = int(dot_color[1]*255) if isinstance(dot_color[1], float) and dot_color[1] <= 1.0 else int(dot_color[1])
b = int(dot_color[2]*255) if isinstance(dot_color[2], float) and dot_color[2] <= 1.0 else int(dot_color[2])
dot_color = f"rgb({r},{g},{b})"
else:
dot_color = str(dot_color)
js.addTurtleDot(self._x, self._y, dot_size / 2.0, dot_color)
self._update_js_state()
def speed(self, speed=None):
return 0
def shape(self, name=None):
if name is None:
return js.getTurtleShape()
js.setTurtleShape(name)
def clear(self):
js.clearTurtleCanvas()
def reset(self):
self.home()
self.clear()
self.pendown()
self.showturtle()
self._pencolor = "black"
self._fillcolor = "black"
self._width = 1.0
_default_turtle = Turtle()
class Screen:
def bgcolor(self, color):
js.setTurtleBgColor(color)
def setup(self, width=None, height=None, *args, **kwargs):
js.setupTurtleCanvas(width, height)
def title(self, titletext):
pass
def clear(self):
js.clearTurtleCanvas()
def reset(self):
js.resetTurtleCanvas()
def done(self):
pass
def mainloop(self):
pass
def exitonclick(self):
pass
_default_screen = Screen()
def Screen():
return _default_screen
def forward(distance): _default_turtle.forward(distance)
fd = forward
def backward(distance): _default_turtle.backward(distance)
bk = backward
back = backward
def right(angle): _default_turtle.right(angle)
rt = right
def left(angle): _default_turtle.left(angle)
lt = left
def penup(): _default_turtle.penup()
pu = penup
up = penup
def pendown(): _default_turtle.pendown()
pd = pendown
down = pendown
def isdown(): return _default_turtle.isdown()
def goto(x, y=None): _default_turtle.goto(x, y)
setpos = goto
setposition = goto
def setheading(to_angle): _default_turtle.setheading(to_angle)
seth = setheading
def home(): _default_turtle.home()
def xcor(): return _default_turtle.xcor()
def ycor(): return _default_turtle.ycor()
def pos(): return _default_turtle.pos()
position = pos
def heading(): return _default_turtle.heading()
def pencolor(color=None): return _default_turtle.pencolor(color)
def fillcolor(color=None): return _default_turtle.fillcolor(color)
def color(color1=None, color2=None): return _default_turtle.color(color1, color2)
def pensize(width=None): return _default_turtle.pensize(width)
width = pensize
def hideturtle(): _default_turtle.hideturtle()
ht = hideturtle
def showturtle(): _default_turtle.showturtle()
st = showturtle
def isvisible(): return _default_turtle.isvisible()
def begin_fill(): _default_turtle.begin_fill()
def end_fill(): _default_turtle.end_fill()
def circle(radius, extent=None, steps=None): _default_turtle.circle(radius, extent, steps)
def write(arg, move=False, align="left", font=("Arial", 8, "normal")): _default_turtle.write(arg, move, align, font)
def dot(size=None, *color): _default_turtle.dot(size, *color)
def speed(speed=None): return _default_turtle.speed(speed)
def shape(name=None): return _default_turtle.shape(name)
def clear(): _default_turtle.clear()
def reset(): _default_turtle.reset()
def bgcolor(color): _default_screen.bgcolor(color)
def setup(width=None, height=None, *args, **kwargs): _default_screen.setup(width, height, *args, **kwargs)
def title(titletext): pass
def done(): pass
mainloop = done
exitonclick = done
`;
// Global Error Handler for debugging
window.onerror = function (msg, url, lineNo, columnNo, error) {
console.error('Window Error:', msg, lineNo, columnNo, error);
// Only show alert for real script errors
if (msg.toLowerCase().indexOf('script error') === -1) {
setRunnerStatus('JS Error: ' + msg + ' (Line ' + lineNo + ')');
}
return false;
};
// Pyodide initialization
if (typeof loadPyodide !== "undefined") {
pyodideReadyPromise = loadPyodide({
stdout: (text) => {
if (currentAppMode !== 'display') {
outputEl.appendChild(document.createTextNode(text + '\n'));
outputEl.scrollTop = outputEl.scrollHeight;
}
},
stderr: (text) => {
if (currentAppMode !== 'display') {
outputEl.appendChild(document.createTextNode(text + '\n'));
outputEl.scrollTop = outputEl.scrollHeight;
}
}
}).then(p => {
pyodideInstance = p;
p.runPython(`
import sys, builtins
# Initialization complete
`);
// Write custom virtual turtle module to VFS
p.FS.writeFile('/home/pyodide/turtle.py', turtleShimPythonCode);
return p;
});
}
const editor = document.getElementById('editor');
const lineNumbers = document.getElementById('lineNumbers');
const outputEl = document.getElementById('output');
const runnerMessage = document.getElementById('runnerMessage');
const runnerStatus = document.getElementById('runnerStatus');
const pasteCounter = document.getElementById('pasteCounter');
const detectionLabel = document.getElementById('detectionLabel');
const runnerLayout = document.getElementById('runnerLayout');
const runnerToggle = document.getElementById('runnerToggle');
const fullscreenButton = document.getElementById('fullscreenButton');
const openNewTabButton = document.getElementById('openNewTabButton');
const undoEditorButton = document.getElementById('undoEditorButton');
const redoEditorButton = document.getElementById('redoEditorButton');
const revertEditorButton = document.getElementById('revertEditorButton');
const btnEditMode = document.getElementById('btnEditMode');
const btnDisplayMode = document.getElementById('btnDisplayMode');
const btnTurtleMode = document.getElementById('btnTurtleMode');
const btnBlocksMode = document.getElementById('btnBlocksMode');
const teacherControlsRow = document.getElementById('teacherControlsRow');
const teachControlsRow = document.getElementById('teachControlsRow');
const callTracePanel = document.getElementById('callTracePanel');
const callTraceList = document.getElementById('callTraceList');
const variablePanel = document.getElementById('variablePanel');
const variableList = document.getElementById('variableList');
const highlightLayer = document.getElementById('highlightLayer');
const editorBg = document.getElementById('editorBg');
const displayEditor = document.getElementById('displayEditor');
const displayCode = document.getElementById('displayCode');
const blocksCodePreview = document.getElementById('blocksCodePreview');
const blocksCodePreviewText = document.getElementById('blocksCodePreviewText');
const blocksCodePreviewCode = document.getElementById('blocksCodePreviewCode');
const blocksPreviewTextColors = document.getElementById('blocksPreviewTextColors');
const blocksPreviewBlockColors = document.getElementById('blocksPreviewBlockColors');
function updateBlocksCodePreview(code) {
if (!blocksCodePreviewCode) return;
const generatedCode = code !== undefined
? code
: (typeof getWorkspacePythonCode === 'function' ? getWorkspacePythonCode() : '');
blocksCodePreviewCode.dataset.rawCode = generatedCode.trim() ? generatedCode : '# Build blocks to generate Python here.';
applyBlocksPreviewColorMode();
}
window.updateBlocksCodePreview = updateBlocksCodePreview;
function markCurrentEditorCodeSaved(code) {
savedEditorCode = code !== undefined ? code : editor.value;
hasUnsavedChanges = false;
updateEditorActionButtons();
}
function refreshEditorAfterProgrammaticChange(statusMessage) {
updateLineNumbers();
analyseCodeAndUpdateMessage(true);
updateBlocksButtonState();
if (currentAppMode === 'blocks') {
updateBlocksCodePreview(editor.value);
}
if (statusMessage) {
setRunnerStatus(statusMessage);
}
updateEditorActionButtons();
}
function updateEditorActionButtons() {
if (revertEditorButton) {
revertEditorButton.disabled = editor.value === savedEditorCode;
}
if (currentAppMode === 'blocks' && window.blocklyWorkspace) {
if (undoEditorButton) {
undoEditorButton.disabled = !window.blocklyWorkspace.undoStack_ || window.blocklyWorkspace.undoStack_.length === 0;
}
if (redoEditorButton) {
redoEditorButton.disabled = !window.blocklyWorkspace.redoStack_ || window.blocklyWorkspace.redoStack_.length === 0;
}
} else {
if (undoEditorButton) undoEditorButton.disabled = false;
if (redoEditorButton) redoEditorButton.disabled = false;
}
const flowchartBtn = document.getElementById('createFlowchartButton');
if (flowchartBtn) {
const codeText = editor.value || '';
const lineCount = codeText.split('\n').length;
if (codeText.trim() !== '' && lineCount <= 30) {
flowchartBtn.style.display = 'inline-block';
} else {
flowchartBtn.style.display = 'none';
}
}
}
function updatePasteCounter() {
if (pasteCounter) {
pasteCounter.textContent = String(pasteCount);
}
}
function incrementPasteCounter() {
pasteCount += 1;
updatePasteCounter();
}
function runEditorHistoryCommand(command) {
if (currentAppMode === 'blocks') {
if (window.blocklyWorkspace) {
const before = editor.value;
if (command === 'undo') {
window.blocklyWorkspace.undo(false);
} else if (command === 'redo') {
window.blocklyWorkspace.undo(true);
}
window.setTimeout(() => {
if (editor.value !== before) {
hasUnsavedChanges = editor.value !== savedEditorCode;
refreshEditorAfterProgrammaticChange(command === 'undo' ? 'Undo applied.' : 'Redo applied.');
} else {
updateEditorActionButtons();
}
}, 0);
}
return;
}
if (!editor) return;
const before = editor.value;
editor.focus();
document.execCommand(command);
window.setTimeout(() => {
if (editor.value !== before) {
hasUnsavedChanges = editor.value !== savedEditorCode;
refreshEditorAfterProgrammaticChange(command === 'undo' ? 'Undo applied.' : 'Redo applied.');
} else {
updateEditorActionButtons();
}
}, 0);
}
function revertEditorToSavedFile() {
if (document.getElementById('playbackControlsBar') && document.getElementById('playbackControlsBar').style.display !== 'none') {
exitPlaybackMode(true);
}
if (editor.value === savedEditorCode) {
setRunnerStatus('Already matches the saved file.');
updateEditorActionButtons();
return;
}
if (hasUnsavedChanges && !confirm('Revert to the last loaded or downloaded file? Unsaved edits will be lost.')) {
return;
}
editor.value = savedEditorCode;
hasUnsavedChanges = false;
if (currentAppMode === 'blocks' && blocklyWorkspace && typeof convertPythonToWorkspace === 'function') {
isUpdatingBlocklyFromText = true;
if (typeof Blockly !== 'undefined' && Blockly.Events) Blockly.Events.disable();
try {
blocklyWorkspace.clear();
convertPythonToWorkspace(editor.value, blocklyWorkspace);
lastGeneratedBlocklyPython = typeof getWorkspacePythonCode === 'function' ? getWorkspacePythonCode() : editor.value;
resizeBlocklyWorkspaceSoon();
} catch (err) {
console.warn('Could not sync reverted code to Blocks:', err);
} finally {
if (typeof Blockly !== 'undefined' && Blockly.Events) Blockly.Events.enable();
isUpdatingBlocklyFromText = false;
}
}
clearRunner();
refreshEditorAfterProgrammaticChange('Reverted to saved file.');
editor.focus();
}
function refreshEditorAfterEdit() {
hasUnsavedChanges = editor.value !== savedEditorCode;
updateLineNumbers();
analyseCodeAndUpdateMessage(true);
updateBlocksButtonState();
updateEditorActionButtons();
}
function handleProgrammaticEdit(reason = 'Typing') {
const highlightLayer = document.getElementById('highlightLayer');
if (highlightLayer) highlightLayer.innerHTML = '';
refreshEditorAfterEdit();
recordPlaybackSnapshot(reason, false);
}
function handleEditorTabKey(event) {
if (event.key !== 'Tab') return;
event.preventDefault();
const indent = ' ';
const value = editor.value;
const start = editor.selectionStart;
const end = editor.selectionEnd;
const lineStart = value.lastIndexOf('\n', start - 1) + 1;
const lineEnd = end > start
? (value.indexOf('\n', end) === -1 ? value.length : value.indexOf('\n', end))
: end;
if (!event.shiftKey) {
if (start === end) {
editor.setRangeText(indent, start, end, 'end');
} else {
const selectedBlock = value.slice(lineStart, lineEnd);
const indentedBlock = selectedBlock.replace(/^/gm, indent);
editor.setRangeText(indentedBlock, lineStart, lineEnd, 'select');
editor.selectionStart = start + indent.length;
editor.selectionEnd = end + (indentedBlock.length - selectedBlock.length);
}
handleProgrammaticEdit('Typing');
return;
}
if (start === end) {
const beforeCursor = value.slice(lineStart, start);
const spacesToRemove = Math.min(4, beforeCursor.match(/ *$/)[0].length);
if (spacesToRemove > 0) {
editor.setRangeText('', start - spacesToRemove, start, 'end');
}
handleProgrammaticEdit('Typing');
return;
}
const selectedBlock = value.slice(lineStart, lineEnd);
let removedBeforeSelection = 0;
let totalRemoved = 0;
const outdentedBlock = selectedBlock.replace(/^( {1,4}|\t)/gm, (match, removed, offset) => {
const removeLength = removed.length;
totalRemoved += removeLength;
if (lineStart + offset < start) {
removedBeforeSelection += removeLength;