-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibengine.py
3429 lines (3339 loc) · 151 KB
/
libengine.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
from errors import script_error
import pickle
import zlib
import os,sys
sys.path.append("core/include")
sys.path.append("include")
if sys.platform=="win32":
os.environ['SDL_VIDEODRIVER']='windib'
import random
from core import *
import gui
import save
import load
from pwvlib import *
import settings
import tools_menu
try:
import android
except:
android = None
d = get_data_from_folder(".")
__version__ = d["version"]
VERSION = "Version "+cver_s(d["version"])
clock = pygame.time.Clock()
def pauseandquit():
import time
end = time.time()+5
while time.time()<end:
pass
sys.exit()
#~ import psyco
#~ pscyo.full()
def category(cat,type=None):
def _dec(f):
f.cat = cat
if type:
f.ftype = type
f.name = [""]
return f
return _dec
class DOCTYPE():
def __init__(self,name,description="",default=None):
self.name = name
self.description = description
self.default = default
def __repr__(self):
s = self.__class__.__name__+" ( "+self.name+":"+self.description+" ) "
if self.default is not None:
s+="default:"+repr(self.default)
return s
class COMBINED(DOCTYPE):
"""Set of arguments joined as text"""
class KEYWORD(DOCTYPE):
"""A value assigned by name"""
class TOKEN(DOCTYPE):
"""This exact token string may be present"""
class VALUE(DOCTYPE):
"""A named value, assigned by position"""
class ETC(DOCTYPE):
"""Each following argument is a separate entity, all potentially optional"""
class CHOICE():
"""One of these options should be present here"""
def __init__(self,options):
self.options = options
def __repr__(self):
return self.__class__.__name__+" ["+" ".join(repr(o) for o in self.options)+"]"
delete_on_menu = [evidence,portrait,fg]
def addevmenu():
try:
em = evidence_menu(assets.items)
assets.cur_script.add_object(em,True)
except art_error,e:
assets.cur_script.obs.append(error_msg(e.value,"",0,assets.cur_script))
import traceback
traceback.print_exc()
return
return em
def add_s(scene):
s = assets.Script()
s.init(scene)
assets.stack.append(s)
assets.addevmenu = addevmenu
assets.addscene = add_s
def parseargs(arglist,intvals=[],defaults = {},setzero = {}):
kwargs = {}
for k in defaults:
kwargs[str(k)] = defaults[k]
args = []
for a in arglist:
if "=" in a:
a = a.split("=",1)
if a[0] in intvals:
try:
kwargs[str(a[0])] = int(a[1])
except:
kwargs[str(a[0])] = float(a[1])
else:
kwargs[str(a[0])]=a[1]
elif setzero.has_key(a):
kwargs[str(setzero[a])]=0
else:
kwargs[str(a)] = 1
return kwargs,args
def argsort(list,arg="pri",get=getattr):
def _cmp(a,b):
return cmp(get(a,arg),get(b,arg))
list.sort(_cmp)
def getz(ob,arg):
v = getattr(ob,arg)
if type(v)==type(""):
v = assets.variables.get(v,0)
return v
class mylist(list): pass
class World:
"""A collection of objects"""
def __init__(self,obs=None):
if not obs: obs = []
self.all = obs[:]
for o in self.all:
o.cur_script = assets.cur_script
def render_order(self):
"""Return a list of objects in the order they should
be rendered"""
n = mylist(self.all[:])
if assets.variables.get("_layering_method","zorder") == "zorder":
argsort(n,"z")
else:
pass
oldapp = n.append
def _app(ob):
self.append(ob)
oldapp(ob)
n.append = _app
return n
def update_order(self):
"""Return a list of objects in the order they
should be updated"""
n = self.all[:]
argsort(n,"pri")
return n
def select(self):
"""Return a list of objects that match the query"""
def append(self,ob):
self.all.append(ob)
ob.cur_script = assets.cur_script
def extend(self,obs,unique=True):
if unique:
for o in obs:
if o not in self.all:
self.all.append(o)
else:
self.all.extend(o)
def remove(self,ob):
self.all.remove(ob)
assets.World = World
def INT(n):
try:
return int(n)
except:
return float(n)
def EVAL(stuff):
stuff = stuff.split(" ",2)
if len(stuff)==1:
return vtrue(assets.variables.get(stuff[0],""))
if len(stuff)==2:
stuff = stuff[0],"=",stuff[1]
current,op,check = stuff
if op not in ["<",">","=","!=","<=",">="]:
check = op+" "+check
op = "="
current = assets.variables.get(current)
if op=="=":op="=="
if op not in ["==","!="]:
current = INT(current)
check = INT(check)
if op == ">":
return current > check
elif op == "<":
return current < check
elif op == "==":
return current == check
elif op == "!=":
return current != check
elif op == "<=":
return current <= check
elif op == ">=":
return current >= check
def GV(v):
if v[0].isdigit():
if "." in v:
return float(v)
return int(v)
if v.startswith("'") and v.endswith("'"):
return v[1:-1]
v = assets.variables.get(v,"")
if v[0].isdigit():
if "." in v:
return float(v)
return int(v)
return v
def ADD(statements):
return GV(statements[0])+GV(statements[1])
def MUL(statements):
return GV(statements[0])*GV(statements[1])
def MINUS(statements):
return GV(statements[0])-GV(statements[1])
def DIV(statements):
return GV(statements[0])/GV(statements[1])
def EQ(statements):
return str(GV(statements[0])==GV(statements[1])).lower()
def GTEQ(statements):
return str(GV(statements[0])>=GV(statements[1])).lower()
def GT(statements):
return str(GV(statements[0])>GV(statements[1])).lower()
def LT(statements):
return str(GV(statements[0])<GV(statements[1])).lower()
def LTEQ(statements):
return str(GV(statements[0])<=GV(statements[1])).lower()
def AND(statements):
if vtrue(statements[0]) and vtrue(statements[1]):
return "true"
return "false"
def OR(stuff):
for line in stuff:
if EVAL(line):
return True
return False
def OR2(statements):
if vtrue(statements[0]) or vtrue(statements[1]):
return "true"
return "false"
def EXPR(line):
statements = []
cur = ""
paren = []
quote = []
for word in line.split(" "):
if not paren and not quote and word == "+":
statements.append(ADD)
elif not paren and not quote and word == "*":
statements.append(MUL)
elif not paren and not quote and word == "-":
statements.append(MINUS)
elif not paren and not quote and word == "/":
statements.append(DIV)
elif not paren and not quote and word == "==":
statements.append(EQ)
elif not paren and not quote and word == "<=":
statements.append(LTEQ)
elif not paren and not quote and word == ">=":
statements.append(GTEQ)
elif not paren and not quote and word == "<":
statements.append(LT)
elif not paren and not quote and word == ">":
statements.append(GT)
elif not paren and not quote and word == "AND":
statements.append(AND)
elif not paren and not quote and word == "OR":
statements.append(OR2)
elif word.strip():
if paren:
if word.endswith(")"):
paren.append(word)
statements.append(EXPR(" ".join(paren)[1:-1]))
paren = []
else:
paren.append(word)
elif quote:
quote.append(word)
if word.endswith("'"):
statements.append(" ".join(quote))
quote = []
elif word.startswith("(") and word.endswith(")"):
statements.append(word[1:-1])
elif word.startswith("("):
paren.append(word)
elif word.startswith("'") and word.endswith("'"):
statements.append(word)
elif word.startswith("'"):
quote.append(word)
else:
statements.append(word)
return statements
def EVAL_EXPR(expr):
if not isinstance(expr,list):
return str(expr)
if len(expr)==1:
return EVAL_EXPR(expr[0])
oop = [MUL,DIV,ADD,MINUS,EQ,LT,GT,LTEQ,GTEQ,OR2,AND]
ops = []
for i,v in enumerate(expr):
if v in oop:
ops.append((i,v))
if not ops:
return str(expr[0])
ops.sort(key=lambda x: oop.index(x[1]))
op = ops[0]
left = expr[op[0]-1:op[0]]
right = expr[op[0]+1:op[0]+2]
left = EVAL_EXPR(left)
right = EVAL_EXPR(right)
v = op[1]([left,right])
expr[op[0]-1] = v
del expr[op[0]]
del expr[op[0]]
return EVAL_EXPR(expr)
assert EVAL_EXPR(EXPR("5 + 1 + 3 * 10"))=="36"
assert EVAL_EXPR(EXPR("2 * (5 + 1)"))=="12"
assert EVAL_EXPR(EXPR("'funny ' + 'business'"))=="funny business"
assert vtrue(EVAL_EXPR(EXPR("2 * (5 + 1) == (5 + 1) * 2")))
assets.variables["something"] = "1"
assert EVAL_EXPR(EXPR("5 + something + 3 * 10"))=="36"
del assets.variables["something"]
assert EVAL_EXPR(EXPR("(5 == 4 OR 5 == 5) AND (1 + 3 == 4) AND ('funny' = 'not funny')"))=="false"
assert EVAL_EXPR(EXPR("(5 == 4 OR 5 == 5) AND (1 + 3 == 4) OR ('funny' = 'not funny')"))=="true"
assert EVAL_EXPR(EXPR("5 > 3"))=="true"
assert EVAL_EXPR(EXPR("5 > 6"))=="false"
assert EVAL_EXPR(EXPR("5 < 3"))=="false"
assert EVAL_EXPR(EXPR("5 < 6"))=="true"
assert EVAL_EXPR(EXPR("5 >= 3"))=="true"
assert EVAL_EXPR(EXPR("5 >= 5"))=="true"
assert EVAL_EXPR(EXPR("5 >= 6"))=="false"
assert EVAL_EXPR(EXPR("5 <= 3"))=="false"
assert EVAL_EXPR(EXPR("5 <= 5"))=="true"
assert EVAL_EXPR(EXPR("5 <= 6"))=="true"
class Script(gui.widget):
save_me = True
def __init__(self,parent=None):
self.world = World()
self.scene = ""
#widget stuff
self.rpos = [0,0]
self.parent = parent
self.viewed = {} #keeps track of viewed textboxes
self.imgcache = {} #Used to preload images
self.lastline = "" #Remember where we jumped from in a script so we can go back
self.lastline_value = "" #Remember last line we executed
self.held = []
def __repr__(self):
return "Script object, scene=%s id=%s line_no=%s"%(self.scene,id(self),self.si)
obs = property(lambda self: self.world.render_order(),lambda self,val: setattr(self,"world",World(val)))
upobs = property(lambda self: self.world.update_order())
def _gchildren(self): return self.world.render_order()
children = property(_gchildren)
width = property(lambda x: sw)
height = property(lambda x: sh*2)
def handle_events(self,evts):
n = []
dp = translate_click
dps = scale_relative_click
for e in evts:
if e.type==pygame.MOUSEMOTION:
d = {"buttons":e.buttons}
d["pos"] = dp(e.pos)
d["rel"] = dps(e.pos,e.rel)
e = pygame.event.Event(pygame.MOUSEMOTION,d)
if e.type==pygame.MOUSEBUTTONUP:
d = {"button":e.button}
d["pos"] = dp(e.pos)
e = pygame.event.Event(pygame.MOUSEBUTTONUP,d)
if e.type==pygame.MOUSEBUTTONDOWN:
d = {"button":e.button}
d["pos"] = dp(e.pos)
e = pygame.event.Event(pygame.MOUSEBUTTONDOWN,d)
n.append(e)
gui.widget.mouse_pos = dp(pygame.mouse.get_pos())
gui.widget.handle_events(self,n)
def save(self):
props = {}
save.cp(["scene","si","cross","statement","instatement","lastline","pri","viewed"],self,props)
if self.parent and self.parent in assets.stack:
props["_parent_index"] = assets.stack.index(self.parent)
obs = []
for ob in self.world.all:
save_state = save.save(ob)
if save_state:
obs.append(save_state)
props["_objects"] = obs
props["_world_id"] = id(self.world)
return ["assets.Script",[],props,["stack",assets.stack.index(self)]]
def after_load(self):
p = {}
for k in ["si","cross","statement","instatement","lastline","pri","viewed"]:
p[k] = getattr(self,k,"")
self.init(self.scene)
for k in p:
setattr(self,k,p[k])
if hasattr(self,"_parent_index"):
try:
self.parent = assets.stack[self._parent_index]
except IndexError:
pass
obs = []
after_after = []
if not hasattr(self,"_world_id"):
self._world_id = id(self)
if self._world_id in assets.loading_cache:
self.world = assets.loading_cache[self._world_id]
return
assets.loading_cache[self._world_id] = self.world
for o in getattr(self,"_objects",[]):
try:
o,later = load.load(self,o)
except:
import traceback
traceback.print_exc()
continue
if o:
print "append",o
obs.append(o)
if later:
after_after.append(later)
print obs
self.world.all = obs
print [getattr(x,"id_name",None) for x in self.world.all]
for of in after_after:
of()
def load(self,s):
vals = pickle.loads(s)
self.scene,self.si,self.cross,self.statement,self.instatement,self.lastline,self.pri = vals[:7]
self.init(self.scene)
self.scene,self.si,self.cross,self.statement,self.instatement,self.lastline,self.pri = vals[:7]
if len(vals)>7:
self.viewed = vals[7]
self.si-=1
def init(self,scene="",macros=True,ext=".txt",scriptlines=None):
self.imgcache.clear()
self.scene = scene
self.scriptlines = []
self.macros = {}
if scriptlines:
self.scriptlines = scriptlines
self.macros = assets.parse_macros(self.scriptlines)
self.si = 0
self.cross = None
self.statement = ""
self.instatement = False
self.lastline = 0
self.pri = 0
self.held = []
#~ if vtrue(assets.variables.get("_preload","on")):
#~ self.preload()
if scene:
try:
self.scriptlines = assets.open_script(scene,macros,ext)
except Exception,e:
import traceback
traceback.print_exc()
#@self.obs.append(error_msg(e.value,self.lastline_value,self.si,self))
self.scriptlines = ['"error opening script{n}\'%s\'"'%scene]
return True
self.macros = assets.macros
self.labels = []
state = "none"
for i,line in enumerate(self.scriptlines):
line = line.lstrip()
if line.startswith(("label ", "result ")):
rn = line.split(" ",1)[1].strip().replace(" ","_")
if rn:
self.labels.append([rn,i])
if line.startswith(("list ", "statement ")):
rn = line.split(" ",1)[1].strip().replace(" ","_")
if rn:
self.labels.append([rn,i-1])
if line.startswith("cross ") or line=="cross":
state = "cross"
rn = "_".join([x for x in line.split(" ")[1:] if not x.startswith("fail=")]).strip()
if rn:
self.labels.append([rn,i-1])
if line.startswith("endcross"):
state = "none"
if line.startswith("statement") and state!="cross":
print "append",line
self.obs.append(error_msg("'statement' command may only be used between 'cross' and 'endcross'.",line,i,self))
return True
def preload(self):
old = self.obs[:]
self.obs = []
import time
t = time.time()
nt = time.time()
for line in self.scriptlines:
if line.strip().startswith("set _preload") and line[13:].strip() in ["0","off","false"]:
return
if line.strip()=="preload_cancel": return
try:
args = [x for x in line.split(" ")]
except:
pass
if not args: continue
if args[0] not in ["bg","char","fg","ev"]: continue
func = getattr(self,"_"+args[0],None)
if func:
try:
func(*args)
except:
pass
nt = time.time()
if nt-t>1.5:
pygame.screen.blit(arial14.render("Loading Script...",1,[255,255,255]),[0,100])
draw_screen()
self.obs = old[:]
def getline(self):
try:
line = self.scriptlines[self.si]
line = line.replace("\t"," ")
line = line.replace("\r","").replace("\n","")
line = line.rsplit("#",1)[0]
line = line.rsplit("//",1)[0]
self.lastline_value = line.strip()
return line.strip()
except TypeError:
return
except IndexError:
return
def update_objects(self):
for o in self.world.update_order():
if not getattr(o,"kill",None) and o.update():
if o.cur_script not in assets.stack:
o.cur_script = assets.cur_script
if o.cur_script==self: return False
return True
def safe_exec(self,method,*args):
try:
return method(*args)
except script_error,e:
self.obs.append(error_msg(e.value,self.lastline_value,self.si,self))
import traceback
traceback.print_exc()
return e
except art_error,e:
if vtrue(assets.variables.get("_debug","false")):
self.obs.append(error_msg(e.value,self.lastline_value,self.si,self))
import traceback
traceback.print_exc()
return e
except markup_error,e:
self.obs.append(error_msg(e.value,self.lastline_value,self.si,self))
import traceback
traceback.print_exc()
return e
except Exception,e:
self.obs.append(error_msg("Undefined:"+e.message,self.lastline_value,self.si,self))
import traceback
traceback.print_exc()
return e
def update(self):
if time.time()-assets.last_autosave>assets.autosave_interval*60:
self.autosave()
interp = self.safe_exec(self.update_objects)
if interp==True:
return self.safe_exec(self.interpret)
def add_object(self,ob,single=False):
if single:
for o2 in self.obs[:]:
if isinstance(o2,ob.__class__):
o2.delete()
self.obs.append(ob)
def draw(self,screen):
for o in self.obs:
if not getattr(o,"hidden",False) and not getattr(o,"kill",False):
o.draw(screen)
if vtrue(assets.variables.get("_debug","false")):
screen.blit(assets.get_font("nt").render("debug",1,[240,240,240]),[220,0])
def tboff(self):
for o in self.obs:
if isinstance(o,testimony_blink):
self.world.remove(o)
break
def tbon(self):
self.add_object(testimony_blink("testimony"),True)
def state_test_true(self,test):
if test is None:
return True
return vtrue(assets.variables.get(test,"false"))
def refresh_arrows(self,tbox):
arrows = [x for x in self.obs if isinstance(x,uglyarrow) and not getattr(x,"kill",0)]
for a in arrows:
a.delete()
if vtrue(assets.variables.get("_textbox_show_button","true")):
u = uglyarrow()
self.add_object(u,True)
u.textbox = tbox
if assets.variables.get("_statements",[]) and self.cross=="proceed":
statements = [x for x in assets.variables["_statements"] if self.state_test_true(x["test"])]
if statements and (statements[0]["words"] == self.statement) or not self.statement:
u.showleft = False
else:
u.showleft = True
tbox.showleft = True
def interpret(self):
self.buildmode = True
exit = False
while self.buildmode and not exit:
line = self.getline()
while not line:
if line is None:
return self._endscript()
self.si += 1
line = self.getline()
#print "exec(",repr(line),")"
self.si += 1
assets.variables["_currentline"] = str(self.si)
exit = self.execute_line(line)
if assets.debugging == "step":
self.obs.append(script_code(self))
return True
def _framerate(self,command,fr):
assets.framerate = int(fr)
@category([COMBINED("text","Text to be print in the textbox, with markup.","")],type="text")
def _textbox(self,command,line):
"""Draws a several line animated textbox to the screen. Uses data/art/general/textbox_2 as the back
drop. The letters of the textbox will print one by one at a set rate, which can be modified
with the markup commands. If there is a character speaking (the _speaking variable is set, a char
command has just been issued, etc) then the character will animate as the text is output.
The game script will pause until the player (or the textbox via markup) tells the game to
continue. This command can also be issued by having a blank line surrounded by quotes. Ex:
{{{
char test
textbox This is some text that is printing
#The same text could be printed this way:
char test
"This is some text that is printing."
}}}"""
text = line.replace("{n}","\n")
tbox = textbox(text)
tbox.showleft=False
if not self.viewed.get(assets.game+self.scene+str(self.si-1)):
tbox.can_skip = False
if vtrue(assets.variables.get("_debug","false")):
tbox.can_skip = True
if vtrue(assets.variables.get("_textbox_allow_skip","false")):
tbox.can_skip = True
self.viewed[assets.game+self.scene+str(self.si-1)] = True
self.add_object(tbox,True)
self.refresh_arrows(tbox)
self.tboff()
if self.cross is not None and self.instatement:
tbox.init_cross()
self.tbon()
if self.cross == "proceed":
tbox.statement = self.statement
nt,t = tbox._text.split("\n",1)
tbox.set_text("{c283}"+t)
else:
tbox.init_normal()
def execute_line(self,line):
if not line:
return
if line[0] in [u'"',u'\u201C'] and len(line)>1:
if not (line.endswith(('"', u'\u201C'))):
line = line+u'"'
self.call_func("textbox",["textbox",line[1:-1]])
return True
def repvar(x):
if x.startswith("$") and not x[1].isdigit():
return assets.variables[x[1:]]
elif x.startswith("$"):
return u""
if u"=" in x:
spl = x.split(u"=",1)
if spl[1].startswith(u"$"):
return spl[0]+u"="+assets.variables[spl[1][1:]]
return x
args = []
try:
args = [repvar(x) for x in line.split(u" ")]
except KeyError:
self.obs.append(error_msg("Variable not defined:",line,self.si,self))
return True
#print repr(args)
if self.execute_macro(args[0]," ".join(args[1:])):
return True
self.call_func(args[0],args)
def call_func(self,command,args):
func = getattr(self,"_"+command,None)
if func:
func(*args)
elif vtrue(assets.variables.get("_debug","false")):
self.obs.append(error_msg("Invalid command:"+command,line,self.si,self))
return True
def execute_macro(self,macroname,args="",obs=None):
mlines = self.macros.get(macroname,None)
if not mlines: return
if args: args = " "+args
nscript = assets.Script(self)
nscript.world = self.world
scriptlines = ["{"+macroname+args+"}"]
assets.replace_macros(scriptlines,self.macros)
nscript.init(scriptlines=scriptlines)
nscript.scene = self.scene+"/"+macroname
nscript.macros = self.macros
assets.stack.append(nscript)
self.buildmode = False
return nscript
def next_statement(self):
if not assets.variables.get("_statements",[]):
return
which = None
for s in assets.variables["_statements"]:
if not self.state_test_true(s["test"]):
continue
#return
if s["index"]>self.si and s["words"]!=self.statement:
which = s["index"]
break
if which is not None:
self.si = which
def prev_statement(self):
if not assets.variables.get("_statements",[]):
return
which = None
for s in reversed(assets.variables["_statements"]):
if not self.state_test_true(s["test"]):
continue
if s["index"]<self.si and s["words"]!=self.statement:
which = s["index"]
break
if which is not None:
self.si = which
else:
self.si -= 1
def goto_result(self,name,wrap=False,backup="none"):
for o in self.obs:
if isinstance(o,guiWait): o.delete()
if name.startswith("{") and name.endswith("}"):
self.execute_macro(name[1:-1])
return
name = name.replace(" ","_")
wrap=True
first = None
self.lastline = self.si
self.instatement = False
assets.variables["_lastline"] = str(self.si)
for label,index in self.labels:
#print repr(name),repr(label),repr(index)
if not first and label==name:
first = index
assets.variables["_currentlabel"] = label
if label == name and index>=self.si:
self.si = index+1
assets.variables["_currentlabel"] = label
return
if label == backup and index>self.si:
self.si = index+1
assets.variables["_currentlabel"] = backup
return
if first is not None and wrap:
self.si = first+1
return
try:
name = int(name)-1
except:
raise script_error,"no label \"%s\" to go to in %s"%(name,self.labels)
if name>=len(self.scriptlines) or name<0:
raise script_error,"Trying to go to invalid line number"
self.si = name+1
@category([COMBINED("text","Some text to print")],type="debug")
def _print(self,*args):
"""Prints some text to the logfile. Only useful for debugging purposes."""
print " ".join(args[1:])
@category([],type="debug")
def _step(self,*args):
"""Begins stepping each line of code. Only works in debug mode."""
print "STEP MODE BEGINS"
if assets.debugging != 'step':
assets.debugging = "step"
@category([],type="gameflow")
def _endscript(self,*args):
"""Ends the currently running script and pops it off the stack. Multiple scripts
may be running in PyWright, in which case the next script on the stack will
resume running."""
self.buildmode = False
if self in assets.stack:
assets.stack.remove(self)
if "enter" in self.held: self.held.remove("enter")
if self.parent:
self.parent.held = []
self.parent.world = self.world
if not assets.stack:
assets.variables.clear()
assets.stop_music()
assets.stack[:] = []
assets.make_start_script(False)
return
@category([CHOICE([TOKEN("true","turns on debug mode"),TOKEN("false","turns off debug mode")])],type="debug")
def _debug(self,command,value):
"""Used to turn debug mode on or off. Debug mode will print more errors to the screen,
and allow you to skip through any text."""
if value.lower() in ["on","1","true"]:
assets.variables["_debug"] = "on"
else:
assets.variables["_debug"] = "off"
@category([COMBINED("label text","The name of this section of code")],type="logic")
def _label(self,command,*name):
"""Used to mark a spot in a wrightscript file. Other code can then refer to this spot,
specifically for making the code reader "goto" this spot."""
assets.variables["_lastlabel"] = " ".join(name)
@category([VALUE("game","Path to game. Should be from the root, i.e. games/mygame or games/mygame/mycase"),
VALUE("script","Script to look for in the game folder to run first","intro")],type="gameflow")
def _game(self,command,game,script="intro"):
"""Can be used to start a new game or case."""
assets.start_game(game,script,"nomenu")
@category([COMBINED("destination","The destination label to move to"),
KEYWORD("fail","A label to jump to if the destination can't be found")],type="logic")
@category([VALUE("folder","List all games in this folder, relative to current game directory")],type="gameflow")
def _gamemenu(self,command,folder,*args):
"""Can be used to list games in a folder"""
cm = choose_game()
cm.pause = True
cm.list_games(assets.game+"/"+folder)
if "close" in args:
cm.close_button(True)
self.add_object(cm,True)
self._gui("gui","Wait")
@category([COMBINED("destination","The destination label to move to"),
KEYWORD("fail","A label to jump to if the destination can't be found")],type="logic")
def _goto(self,command,place,*args):
"""Makes the script go to a different section, based on the label name."""
fail = None
for x in args:
if "=" in x:
k,v = x.split("=",1)
if k == "fail":
fail = v
self.goto_result(place,wrap=True,backup=fail)
@category([COMBINED("flag_expression","list of flag names joined with AND or OR"),
CHOICE([
TOKEN("?"),VALUE("label","label to jump to if the evaluation is true")
]),
KEYWORD("fail","label to jump to if evaluation is false","none")],type="logic")
def flag_logic(self,value,*args):
fail=None
args = list(args)
label = args.pop(-1)
if label.startswith("fail="):
fail=label.split("=",1)[1]
label = args.pop(-1)
if label.endswith("?"):
args.append(label[:-1])
label = "?"
sentance = ""
mode = 0
for a in args:
if mode == 0:
sentance+="('"+a+"' in assets.variables)"
elif mode == 1:
if a=="AND": sentance+=" and "
elif a=="OR": sentance+=" or "
else: raise script_error("Logic must be AND or OR")
mode = 1-mode
if not eval(sentance)==value: return self.fail(label,fail)
self.succeed(label)
@category([COMBINED("flag_expression","list of flag names joined with AND or OR"),
CHOICE([
TOKEN("?"),VALUE("label","label to jump to if the evaluation is true")
]),
KEYWORD("fail","label to jump to if evaluation is false","none")],type="logic")
def _noflag(self,command,*args):
"""Evaluates an expression with flag names. If the expression
is not true, jumps to the listed label. Otherwise, will
jump to the fail keyword if that was given. If the line ends
with a '?', it will execute the next line and the next line only
when the flag expression is false."""
self.flag_logic(False,*args)
@category([COMBINED("flag_expression","list of flag names joined with AND or OR"),
CHOICE([
TOKEN("?"),VALUE("label","label to jump to if the evaluation is true")
]),
KEYWORD("fail","label to jump to if evaluation is false","none")],type="logic")
def _flag(self,command,*args):
"""Evaluates an expression with flag names. If the expression
is true, jumps to the listed label. Otherwise, will
jump to the fail keyword if that was given. If the line ends
with a '?', it will execute the next line and the next line only
when the flag expression is true."""
self.flag_logic(True,*args)
@category([VALUE('flag_name','flag to set')],type="logic")
def _setflag(self,command,flag):
"""Sets a flag. Shorthand for setting a variable equal to true. Flags
will remain set for the remainder of the game, and can be used to
track what a player has done."""
if flag not in assets.variables: assets.variables[flag]="true"
@category([VALUE('flag_name','flag to unset')],type="logic")
def _delflag(self,command,flag):
"""Deletes a flag. Flags will remain set for the remainder of the game, but
can be forgotten with delflag."""
if flag in assets.variables: del assets.variables[flag]
@category([VALUE("variable","variable name to set"),COMBINED("value","Text to assign to the variable. Can include $x to replace words of the text with the value of other variables.")],type="logic")
def _set(self,command,variable,*args):
"""Sets a variable to some value."""
value = u" ".join(args)
assets.variables[variable]=value
@category([VALUE("variable","variable name to set"),COMBINED("expression2","The results of the expression will be stored in the variable.")],type="logic")
def _set_ex(self,command,variable,*args):
"""Sets a variable to some value based on an expression"""
value = EVAL_EXPR(EXPR(" ".join(args)))
assets.variables[variable]=value
@category([VALUE("variable","The variable to save the value into"),COMBINED("source variable","The variable to get the value from. Can use $x to use another variable to point to which variable to copy from, like a signpost.")],type="logic")
def _getvar(self,command,variable,*args):
"""Copies the value of one variable into another."""
value = u"".join(args)
assets.variables[variable]=assets.variables.get(value,"")
_setvar = _set
_setvar_ex = _set_ex
@category([VALUE("variable","The variable to save the value into"),KEYWORD("name","The object to get the property from"),KEYWORD("prop","The property to get from the object")],type="logic")
def _getprop(self,command,variable,*args):
"""Copies the value of some property of an object into a variable"""
name = None
prop = None
for a in args:
if a.startswith("name="):
name = a.split("=",1)[1]
if a.startswith("prop="):
prop = a.split("=",1)[1]
if not name or not prop:
raise script_error("getprop: need to supply an object name= and a prop= to get")
for o in self.obs:
if getattr(o,"id_name",None)==name:
p = str(o.getprop(prop))
assets.variables[variable]=p
return
raise script_error("getprop: object not found")
@category([VALUE("variable","The variable to save the value into"),KEYWORD("name","The object to get the property from"),KEYWORD("prop","The property to get from the object")],type="logic")
def _setprop(self,command,*args):
"""Copies the value of a variable to some property of an object"""
name = None
prop = None
val = []
for a in args:
if a.startswith("name="):
name = a.split("=",1)[1]
elif a.startswith("prop="):
prop = a.split("=",1)[1]
else:
val.append(a)
val = " ".join(val)
if not name or not prop:
raise script_error("setprop: need to supply an object name= and a prop= to set")
for o in self.obs:
if getattr(o,"id_name",None)==name:
o.setprop(prop,val)
return
raise script_error("setprop: object not found")
@category([VALUE("variable","variable name to save random value to"),VALUE("start","smallest number to generate"),VALUE("end","largest number to generate")],type="logic")
def _random(self,command,variable,start,end):
"""Generates a random integer with a minimum
value of START, a maximum value of END, and
stores that value to VARIABLE"""
random.seed(pygame.time.get_ticks()+random.random())
value = random.randint(int(start),int(end))
assets.variables[variable]=str(value)
@category([VALUE("variable","variable to save value to"),COMBINED("words","words to join together")],type="logic")
def _joinvar(self,command,variable,*args):
"""Takes a series of words and joins them together, save the joined
string to a variable. For instance:
{{{setvar hour 3
setvar minute 15
joinvar time $hour : $minute
"{$time}"}}}
will output "3:15"
"""
value = "".join(args)
assets.variables[variable]=value
@category([VALUE("variable","variable to save to"),VALUE("amount","amount to add to the variable")],type="logic")
def _addvar(self,command,variable,value):
"""Adds an amount to a variable. If the variable 'x' were set to 4, the script:
{{{addvar x 1}}}
would set 'x' to 5."""
oldvalue = INT(assets.variables.get(variable,0))
oldvalue += INT(value)
assets.variables[variable] = str(oldvalue)
@category([VALUE("variable","variable to subtract from and save to"),VALUE("amount","amount to subtract from the variable")],type="logic")
def _subvar(self,command,variable,value):
"""Subtract an amount from a variable. If the variable 'x' were set to 33, the script:
{{{subvar x 3}}}
would set 'x' to 30."""
oldvalue = INT(assets.variables[variable])
oldvalue -= INT(value)
assets.variables[variable] = str(oldvalue)
@category([VALUE("variable","variable to save to"),VALUE("amount","amount to multiply the variable by")],type="logic")