-
Notifications
You must be signed in to change notification settings - Fork 10
/
charcoal.py
executable file
·5090 lines (4608 loc) · 174 KB
/
charcoal.py
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
#!/usr/bin/env python3
"""
Charcoal's main module.
Contains definitions for the Charcoal canvas object, \
the CLI, and various classes used by the Charcoal class.
"""
from direction import Direction, DirectionToString, Pivot
from charcoaltoken import CharcoalToken as CT, CharcoalTokenNames as CTNames
from charactertransformers import *
from directiondictionaries import *
from unicodegrammars import UnicodeGrammars
from verbosegrammars import VerboseGrammars
from astprocessor import ASTProcessor
from interpreterprocessor import InterpreterProcessor, iter_apply
from stringifierprocessor import StringifierProcessor
from codepage import (
UnicodeLookup, ReverseLookup, UnicodeCommands, InCodepage, sOperator,
rCommand
)
from compression import Decompressed, Escaped
from wolfram import *
from extras import *
from enum import Enum
from ast import literal_eval
from time import sleep, perf_counter as clock, time as now
from math import ceil, log2
import random
import re
import argparse
import os
import sys
import builtins
import types
import zlib
import base64
command_abbreviations = {}
for alias, builtin in [
("A", abs), ("B", bin), ("C", complex), ("D", dict), ("E", enumerate),
("F", format), ("G", range), ("H", hex), ("I", __import__), ("M", sum),
("N", min), ("O", oct), ("P", repr), ("R", reversed), ("S", sorted),
("V", eval), ("X", max), ("Z", zip)
]:
setattr(builtins, alias, builtin)
_H = H
def H(item):
if isinstance(item, int):
return hex(item)
if isinstance(item, float):
return item.hex()
if isinstance(item, String):
item = str(item)
if isinstance(item, str):
item = float(item) if "." in item else int(item)
return h(item)
if hasattr(item, "__iter__"):
if isinstance(item[0], Expression):
item = iter_apply(item, lambda o: o.run())
return iter_apply(item, H)
_B = B
def B(item):
if isinstance(item, float):
item = int(item)
if isinstance(item, int):
return bin(item)
if isinstance(item, String):
item = str(item)
if isinstance(item, str):
item = float(item) if "." in item else int(item)
return b(item)
if hasattr(item, "__iter__"):
if isinstance(item[0], Expression):
item = iter_apply(item, lambda o: o.run())
return iter_apply(item, B)
def warn(s):
sys.stderr.write(str(s) + "\n")
imports = {}
python_function_is_command = {}
if os.name == "nt":
import ansiterm # for colors/screen clear
else:
import readline # for arrow/Ctrl+A/Ctrl+E support
try:
# if python > 3.6 or back-compat module exists
import typing
def has_return_hint(function):
"""
has_return_hint(function)
Returns whether function has a return type hint.
"""
return "return" in typing.get_type_hints(function)
except:
def has_return_hint(function):
"""
has_return_hint(function)
Returns false since this Python installation has no typing module.
"""
return false
def CleanExecute(function, *args, **kwargs):
"""
CleanExecute(function, *args, **kwargs) -> Any
Executes the given function with the given arguments, \
exiting if an error occurs.
"""
try:
return function(*args, **kwargs)
except (KeyboardInterrupt, EOFError):
sys.exit()
def Cleanify(function):
"""
Cleanify(function) -> Function
Returns the function changed to that it exits without a stack trace \
if an error occurs.
"""
return lambda *args, **kwargs: CleanExecute(function, *args, **kwargs)
_open = open
def open(*args, **kwargs):
"""
Open(*args, **kwargs)
Returns a file object opened with UTF-8 encoding.
"""
kwargs["encoding"] = "utf-8"
return _open(*args, **kwargs)
def openl1(*args, **kwargs):
"""
Open(*args, **kwargs)
Returns a file object opened with UTF-8 encoding.
"""
kwargs["encoding"] = "latin1"
return _open(*args, **kwargs)
old_input = input
input = Cleanify(old_input)
sleep = Cleanify(sleep)
def Sign(number):
"""
Sign(number)
Return the mathematical sign of the given number.
"""
return number and (-1, 1)[number > 0]
def large_range(number):
"""
large_range(number)
Yields numbers from 0 to the given number.
Works for numbers that do not fit in a long integer.
"""
n = 0
while n < number:
yield n
n += 1
stringify_lookup = {
"e": "cdflmnosv"
}
def StringifyCode(code):
result = []
stack = []
length = len(code)
for i in range(length):
add = True
item = code[i]
if (
item[0] == "s" and
item[1][0] == "´" and
not rCommand.match(item[1][1])
):
item = ("s", item[1][1:])
if item[0] != "!":
if item[0] != "m":
j = i + 1
while j < length and code[j][0] == "!":
j += 1
if (
j < length and
code[j][0] == "s" and
code[j][1][0] == "´" and
not rCommand.match(code[j][1][1])
):
code[j] = ("s", code[j][1][1:])
if item[0] == "$" and item[1] == "M":
add = code[i + 1][0] != "a" or (
i > 1 and code[i - 1][0] == "m" or (
i + 2 < length and
code[i + 2][0] in stringify_lookup["e"]
)
)
while stack:
notter = stack[0]
if item[0] in stringify_lookup.get(notter[1], notter[1]):
result += [(";", "¦")]
stack = stack[1:]
stack = []
if add:
result += [item]
else:
stack += [item]
while len(result) and result[-1][0] == ">":
result.pop()
if len(result) and result[-1][0] == "c":
result[-1] = ("c", result[-1][1][:-1])
return "".join(b for _, b in result)
class Modifier(Enum):
maybe = 1
maybe_some = 2
some = 3
class Info(Enum):
prompt = 1
is_repl = 2
warn_ambiguities = 3
step_canvas = 4
dump_canvas = 5
class Whatever(object):
def __call__(self, *args, **kwargs):
if kwargs == {}:
if len(args) == 1:
return args[0]
if not len(args):
return self
return dict(enumerate(args), **kwargs)
def __add__(self, other):
return other
def __radd__(self, other):
return other
def __sub__(self, other):
return -other
def __rsub__(self, other):
return other
def __mul__(self, other):
return other
def __rmul__(self, other):
return other
def __truediv__(self, other):
return 1 / other
def __rtruediv__(self, other):
return other
def __floordiv__(self, other):
return 1 // other
def __rfloordiv__(self, other):
return other // 1
def __or__(self, other):
return other
def __ror__(self, other):
return other
def __and__(self, other):
return other
def __rand__(self, other):
return other
def __xor__(self, other):
return other
def __rxor__(self, other):
return other
def __mod__(self, other):
return other
def __rmod__(self, other):
return other
def __int__(self):
return 0
def __str__(self):
return ""
def __repr__(self):
return ""
whatever = Whatever()
class Coordinates(object):
__slots__ = ("top", "coordinates", "list")
def __init__(self):
self.top = 0
self.coordinates = [[]]
self.list = []
def FillLines(self, y):
if y > self.top + len(self.coordinates) - 1:
self.coordinates += [[] for _ in range(
y - self.top - len(self.coordinates) + 1
)]
elif y < self.top:
self.coordinates = [
[] for _ in range(self.top - y)
] + self.coordinates
self.top = y
def Add(self, x, y):
self.FillLines(y)
self.coordinates[y - self.top] += [x]
self.list += [(x, y)]
class Scope(object):
__slots__ = ("parent", "lookup")
def __init__(self, parent=None, lookup=None):
self.parent = parent or {}
self.lookup = lookup or {}
def __next__(self):
key = next(filter(
lambda character: character not in self,
"ικλμνξπρςστυφχψωαβγδεζηθ"
))
self.lookup[key] = None
return key
def __contains__(self, key):
return key in self.parent or key in self.lookup
def __getitem__(self, key):
if key in self.lookup:
return self.lookup[key]
else:
return self.parent[key]
def __setitem__(self, key, value):
if key in self.lookup:
self.lookup[key] = value
else:
self.parent[key] = value
def __delitem__(self, key):
if key in self.lookup:
del self.lookup[key]
else:
del self.parent[key]
def __repr__(self):
string = "{"
for key in self.lookup:
value = self.lookup[key]
string += "%s: %s, " % (key, repr(value))
string = string[:-2] + "}"
if string == "}":
string = "{}"
return (
string +
"\n" +
re.sub("^", " ", repr(self.parent))
)
def get(self, key, fallback):
return self[key] if key in self else fallback
def set(self, key, value):
self[key] = value
def delete(self, key):
del self[key]
def GetPythonFunction(name):
if isinstance(name, String):
name = str(name)
elif not isinstance(name, str):
return None
function, name, _name = None, name[:], name[:]
if "." in name:
try:
module, *parts = name.split(".")
if module not in imports:
imports[module] = __import__(module)
function = imports[module]
for part in parts:
function = getattr(function, part)
return function
except:
pass
if not function:
loc, glob = locals(), globals()
if "." not in name:
if name in loc:
function = loc[name]
elif name in glob:
function = glob[name]
elif hasattr(builtins, name):
function = getattr(builtins, name)
else:
return None
return function
else:
variable, *parts = name.split(".")
if variable in loc:
function = loc[variable]
elif variable in glob:
function = glob[variable]
elif hasattr(builtins, variable):
function = getattr(builtins, variable)
else:
return None
for part in parts:
function = function[part]
return function
class Cells(list):
__slots__ = ("xs", "ys", "charcoal")
def __init__(self, charcoal, value, xs=None, ys=None):
if isinstance(value, Cells):
result = charcoal
indices = xs
super().__init__(result)
if indices is None:
self.xs = value.xs
self.ys = value.ys
else:
self.xs = [value.xs[i] for i in indices]
self.ys = [value.ys[i] for i in indices]
self.charcoal = value.charcoal
return
super().__init__(value)
self.xs = xs
self.ys = ys
self.charcoal = charcoal
def __setitem__(self, i, value):
super().__setitem__(i, value)
if isinstance(i, slice):
start = i.start or 0
stop = len(self) if i.stop is None else i.stop
step = 1 if i.step is None else i.step
for i in range(start, stop, step):
self.charcoal.Put(self[i], self.xs[i], self.ys[i])
return
self.charcoal.Put(self[i], self.xs[i], self.ys[i])
def __getitem__(self, i):
if isinstance(i, slice):
start = i.start or 0
stop = len(self) if i.stop is None else i.stop
step = 1 if i.step is None else i.step
return Cells(
self.charcoal,
super().__getitem__(slice(start, stop, step)),
self.xs[start:stop:step],
self.ys[start:stop:step]
)
return super().__getitem__(i)
class Charcoal(object):
__slots__ = (
"x", "y", "top", "lines", "indices", "lengths", "right_indices",
"top_scope", "scope", "info", "original_input", "inputs",
"original_inputs", "direction", "background", "bg_lines",
"bg_line_number", "bg_line_length", "timeout_end", "dump_timeout_end",
"trim", "print_at_end", "canvas_step",
"last_printed", "charcoal"
)
secret = {}
for key in dir(builtins):
if key[0] != "_":
secret[key] = getattr(builtins, key)
globs = globals()
for key in globs:
if key[0] != "_":
secret[key] = globs[key]
wolfram = vars(__import__("wolfram"))
for key in wolfram:
if len(key) == 1 or key[1] != "_":
if key[:2] == "_p":
secret[key[2:]] = wolfram[key]
elif key[0] == "_":
secret[key[1:]] = wolfram[key]
secret[key] = wolfram[key]
extras = vars(__import__("extras"))
for key in extras:
if key[0] != "_":
secret[key] = extras[key]
def __init__(
self,
inputs=[],
info=set(),
canvas_step=500,
original_input="",
trim=False
):
"""
Charcoal(inputs=[], info=set(), canvas_step=500, original_input="") \
-> Charcoal
Creates a Charcoal canvas, \
an object on which all canvas drawing methods exist.
"""
self.x = self.y = self.top = 0
self.lines = [""]
self.indices = [0]
self.lengths = [0]
self.right_indices = [0]
self.info = info
self.original_input = original_input
self.inputs = inputs
self.original_inputs = inputs[:]
self.top_scope = self.scope = Scope(lookup={
"γ": " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\
[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",
"β": "abcdefghijklmnopqrstuvwxyz",
"α": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"ω": "",
"ψ": "\000",
"χ": 10,
"φ": 1000,
"υ": []
})
self.direction = Direction.right
self.background = " "
self.bg_lines = [" "]
self.bg_line_number = self.bg_line_length = 1
self.timeout_end = self.dump_timeout_end = 0
self.trim = trim
self.print_at_end = True
self.canvas_step = canvas_step
self.last_printed = None
self.charcoal = None
if Info.step_canvas in self.info:
print("\033[2J")
def __str__(self):
"""Returns the current state of the canvas."""
left = min(self.indices)
right = max(self.right_indices)
string = ""
if not self.background:
for i in range(len(self.lines)):
top = self.top + i
index = self.indices[i]
line = self.lines[i]
bg_start = None
j = 0
if "\000" in line:
for character in line:
if character == "\000":
if bg_start is None:
bg_start = j
elif bg_start is not None:
line = (
line[:bg_start] +
self.BackgroundString(
top, index + bg_start, index + j
) +
line[j:]
)
bg_start = None
j += 1
if bg_start is not None:
line = (
line[:bg_start] +
self.BackgroundString(
top, index + bg_start, index + j
)
)
string += (
self.BackgroundString(
self.top + i, left, self.indices[i]
) +
line +
("" if self.trim else self.BackgroundString(
self.top + i, self.right_indices[i], right
)) +
"\n"
)
return string[:-1]
else:
for line, index, right_index in zip(
self.lines, self.indices, self.right_indices
):
string += (
self.background * (index - left) +
(
re.sub("\000", self.background, line)
if "\000" in line else line
) +
(
"" if self.trim else
self.background * (right - right_index)
) +
"\n"
)
return string[:-1]
def __getattribute__(self, attr):
method = object.__getattribute__(self, attr)
if isinstance(method, types.MethodType):
self.last_printed = None
return method
def BackgroundString(self, y, start, end):
"""
BackgroundString(y, start, end) -> str
Returns the background for row at the specified y-coordinate,
from the x-coordinates start to end.
"""
bg_line = self.bg_lines[y % self.bg_line_number]
index = start % self.bg_line_length
bg_line = bg_line[index:] + bg_line[:index]
length = end - start
return (bg_line * (length // self.bg_line_length + 1))[:length]
def AddInputs(self, inputs):
"""
AddInputs(inputs)
Adds given inputs to the inputs of the canvas.
"""
self.original_inputs += inputs
self.inputs += inputs
def ClearInputs(self):
"""
ClearInputs()
Removes all inputs from canvas.
"""
self.inputs = []
self.original_inputs = []
def Trim(self):
"""
Trim()
Deletes empty cells on all four sides of the canvas.
"""
to_delete = 0
while re.match("^\000*$", self.lines[to_delete]):
to_delete += 1
to_delete -= 1
if to_delete > 0:
self.lines = self.lines[to_delete:]
self.top += to_delete
to_delete = -1
while re.match("^\000*$", self.lines[to_delete]):
to_delete -= 1
to_delete += 1
if to_delete < 0:
self.lines = self.lines[:to_delete]
for i in range(len(self.lines)):
line = self.lines[i]
match = re.match("^\000*", line)
match_length = len(match.group(0)) if match else 0
self.indices[i] += match_length
self.lengths[i] -= match_length
match_2 = re.match("\000*$", line)
match_2_length = len(match_2.group(0)) if match_2 else 0
self.right_indices[i] -= match_2_length
self.lengths[i] -= match_2_length
line = line[match_length:]
if match_2_length > 0:
line = line[:-match_2_length]
self.lines[i] = line
def Clear(self, all=True):
"""
Clear(all=True)
Resets Charcoal object to initial state.
If all is False, only reset canvas
"""
self.x = self.y = self.top = 0
self.lines = [""]
self.indices = [0]
self.lengths = [0]
self.right_indices = [0]
if all:
self.top_scope = self.scope = Scope(lookup={
"γ": " !\"#$%&'()*+,-./0123456789:;<=>?@\
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",
"β": "abcdefghijklmnopqrstuvwxyz",
"α": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"ω": "",
"ψ": "\000",
"χ": 10,
"φ": 1000,
"υ": []
})
self.inputs = self.original_inputs[:]
self.direction = Direction.right
self.background = " "
self.bg_lines = [" "]
self.bg_line_number = self.bg_line_length = 1
self.timeout_end = self.dump_timeout_end = 0
self.trim = False
self.print_at_end = True
self.last_printed = None
self.charcoal = None
if Info.step_canvas in self.info:
self.RefreshFastText("Clear", self.canvas_step)
elif Info.dump_canvas in self.info:
print("Clear")
print(str(self))
def Get(self):
"""
Get() -> str
Returns value of cell under cursor.
"""
y_index = self.y - self.top
if (
y_index >= len(self.lines) or
y_index < 0 or
self.x - self.indices[y_index] >= self.lengths[y_index] or
self.x - self.indices[y_index] < 0
):
return ""
return self.lines[y_index][self.x - self.indices[y_index]]
def CanFillAt(self, x, y):
"""
CanFillAt() -> bool
Returns whether there is a "\000" under the cursor
"""
y_index = y - self.top
result = False
if (
y_index < len(self.lines) and
y_index >= 0 and
x - self.indices[y_index] < self.lengths[y_index] and
x - self.indices[y_index] >= 0
):
result = (
self.lines[y_index][x - self.indices[y_index]] == "\000"
)
return result
def Put(self, string, x=None, y=None):
"""
Put(string, x=None, y=None)
Put string at position x, y. Defaults to cursor position.
"""
x = self.x if x is None else x
if y is not None:
original_x, original_y, self.x, self.y = self.x, self.y, x, y
self.FillLines()
self.x, self.y = original_x, original_y
y = self.y if y is None else y
y_index = y - self.top
x_index = self.indices[y_index]
line = self.lines[y_index]
if not line:
length = len(string)
self.lines[y_index] = string
self.indices[y_index] = x
self.lengths[y_index] = length
self.right_indices[y_index] = x + length
return
start = x - x_index
end = start + len(string)
self.lines[y_index] = (
line[:max(0, start)] +
"\000" * (start - len(line)) +
string +
"\000" * -end +
line[max(0, end):]
)
if x < x_index:
self.indices[y_index] = x
length = len(self.lines[y_index])
self.lengths[y_index] = length
self.right_indices[y_index] = self.indices[y_index] + length
def FillLines(self):
"""
FillLines()
Adds empty lines up to the y-index of the cursor.
"""
if self.y > self.top + len(self.lines) - 1:
number = self.y - self.top - len(self.lines) + 1
x_number = self.x - self.indices[-1]
x_sign = Sign(x_number)
x_number *= x_sign
x_number = min(number, x_number)
difference = number - x_number
if x_sign == 1:
indices = (
[0] * difference +
list(range(1, x_number + 1))
)
elif x_sign == -1:
indices = (
[0] * difference +
list(range(-x_number, 0)[::-1])
)
else:
indices = [0] * number
self.lines += [""] * number
self.indices += indices
self.lengths += [0] * number
self.right_indices += indices
elif self.y < self.top:
number = self.top - self.y
x_number = self.x - self.indices[0] if len(self.indices) else 0
x_sign = Sign(x_number)
x_number *= x_sign
x_number = min(number, x_number)
difference = number - x_number
if x_sign == 1:
indices = (
list(range(1, x_number + 1)[::-1]) +
[0] * difference
)
elif x_sign == -1:
indices = (
list(range(-x_number, 0)) +
[0] * difference
)
else:
indices = [0] * number
self.lines = [""] * number + self.lines
self.indices = indices + self.indices
self.lengths = [0] * number + self.lengths
self.right_indices = indices + self.right_indices
self.top = self.y
def SetBackground(self, string):
"""
SetBackground(string)
Sets the background of the canvas,
tiling with the top left at (0, 0).
"""
lines = string.split("\n")
length = max(len(line) for line in lines)
if length:
self.bg_lines = [
line + " " * (length - len(line))
for line in lines
]
self.bg_line_number = len(lines)
self.bg_line_length = length
if length > 1 or len(lines) > 1:
self.background = ""
else:
self.background = string
else:
print("RuntimeError: Cannot change background to nothing")
if Info.is_repl not in self.info:
sys.exit(1)
if Info.step_canvas in self.info:
self.RefreshFastText("Set background", self.canvas_step)
elif Info.dump_canvas in self.info:
print("Set background")
print(str(self))
def PrintLine(
self, directions, length, string="", multiprint=False,
coordinates=False, move_at_end=True, multichar_fill=False,
overwrite=True
):
"""
PrintLine(directions, length, string="", multiprint=False, \
coordinates=False, move_at_end=True, multichar_fill=False, overwrite=True)
Prints the given string, repeated to the given length, \
in the specified directions away from the cursor.
If the string is falsy, a character will be selected from \
\\/|-.
If multiprint is true, the cursor will return to \
its original position.
If coordinates is true, the coordinates of each character \
will be returned. If it is truthy, it will be assumed to be a \
Coordinates object and used as such.
If move_at_end is false, the cursor will stay on \
the last character instead of moving to the cell after it.
If multichar_fill is true, horizontal lines will also \
be added to the list of coordinates.
If overwrite is false, existing characters will not be overwritten.
"""
old_x = self.x
old_y = self.y
string_is_empty = not string
length = int(length)
if coordinates is True:
coordinates = Coordinates()
for direction in directions:
if string_is_empty:
string = DirectionCharacters[direction]
self.x = old_x
self.y = old_y
if (
overwrite and (
direction == Direction.right or
direction == Direction.left
)
):
if (
self.y < self.top or self.y > (self.top + len(self.lines))
) and not string:
continue
self.FillLines()
final = (string * (length // len(string) + 1))[:length]
if direction == Direction.left:
final = final[::-1]
self.x -= length - 1
self.Put(final)
if multichar_fill:
coordinates.Add(self.x, self.y)
coordinates.Add(self.x + length - 1, self.y)
if direction == Direction.right: