forked from poiuyqwert/PyMS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PyAI.pyw
executable file
·3565 lines (3324 loc) · 132 KB
/
PyAI.pyw
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 Libs.utils import *
from Libs.setutils import *
from Libs.trace import setup_trace
from Libs.SFmpq import *
from Libs import AIBIN, TBL, DAT
from Tkinter import *
from tkMessageBox import *
import tkFileDialog,tkColorChooser
from thread import start_new_thread
from shutil import copy
import optparse, os, re, webbrowser, sys
VERSION = (2,5)
LONG_VERSION = 'v%s.%s' % VERSION
IMG_CACHE = {}
def get_img(n):
if n in IMG_CACHE:
return IMG_CACHE[n]
IMG_CACHE[n] = PhotoImage(file=os.path.join(BASE_DIR, 'Images','%s.gif' % n))
return IMG_CACHE[n]
types = [
('byte','A number in the range 0 to 255'),
('word','A number in the range 0 to 65535'),
('dword','A number in the range 0 to 4294967295'),
('unit','A unit ID from 0 to 227, or a full unit name from stat_txt.tbl'),
('building','Same as unit type, but only units that are Buildings, Resource Miners, and Overlords'),
('military','Same as unit type, but only for a unit to train (not a Building, Resource Miners, or Overlords)'),
('gg_military','Same as Military type, but only for defending against an enemy Ground unit attacking your Ground unit'),
('ag_military','Same as Military type, but only for defending against an enemy Air unit attacking your Ground unit'),
('ga_military','Same as Military type, but only for defending against an enemy Ground unit attacking your Air unit'),
('aa_military','Same as Military type, but only for defending against an enemy Air unit attacking your Air unit'),
('upgrade','An upgrade ID from 0 to 60, or a full upgrade name from stat_txt.tbl'),
('technology','An technology ID from 0 to 43, or a full technology name from stat_txt.tbl'),
('string',"A string of any characters (except for nulls: <0>) in TBL string formatting (use <40> for an open parenthesis '(', <41> for a close parenthesis ')', and <44> for a comma ',')"),
('block','The label name of a block in the code'),
]
TYPE_HELP = odict()
for t,h in types:
TYPE_HELP[t] = h
cmds = [
('Header',[
('farms_notiming','Build necessary farms only when it hits the maximum supply available.'),
('farms_timing','Build necessary farms with a correct timing, so nothing is paused by a maximum supply limit hit.'),
('start_areatown','Starts the AI Script for area town management.'),
('start_campaign','Starts the AI Script for Campaign.'),
('start_town','Starts the AI Script for town management.'),
('transports_off','Tells the AI to not worry about managing transports until check_transports is called.'),
]),
('Build/Attack/Defense order',[
('attack_add','Add Byte Military to the current attacking party.'),
('attack_clear','Clear the attack data.'),
('attack_do','Attack the enemy with the current attacking party.'),
('attack_prepare','Prepare the attack.'),
('build','Build Building until it commands Byte(1) of them, at priority Byte(2).'),
('defensebuild_aa','Build Byte Military to defend against enemy attacking air units, when air units are attacked.'),
('defensebuild_ag','Build Byte Military to defend against enemy attacking air units, when ground units are attacked.'),
('defensebuild_ga','Build Byte Military to defend against enemy attacking ground units, when air units are attacked.'),
('defensebuild_gg','Build Byte Military to defend against enemy attacking ground units, when ground units are attacked.'),
('defenseclear_aa','Clear defense against enemy attacking air units, when air units are attacked.'),
('defenseclear_ag','Clear defense against enemy attacking air units, when ground units are attacked.'),
('defenseclear_ga','Clear defense against enemy attacking ground units, when air units are attacked.'),
('defenseclear_gg','Clear defense against enemy attacking ground units, when ground units are attacked.'),
('defenseuse_aa','Use Byte Military to defend against enemy attacking air units, when air units are attacked.'),
('defenseuse_ag','Use Byte Military to defend against enemy attacking air units, when ground units are attacked.'),
('defenseuse_ga','Use Byte Military to defend against enemy attacking ground units, when air units are attacked.'),
('defenseuse_gg','Use Byte Military to defend against enemy attacking ground units, when ground units are attacked.'),
('guard_resources','Send units of type Military to guard as many resources spots as possible(1 per spot).'),
('tech','Research technology Technology, at priority Byte.'),
('train','Train Military until it commands Byte of them.'),
('do_morph','Train Military if it commands less than Byte of them.'),
('upgrade','Research upgrade Upgrade up to level Byte(1), at priority Byte(2).'),
('wait','Wait for Word tenths of second in normal game speed.'),
('wait_finishattack','Wait until attacking party has finished to attack.'),
('wait_build','Wait until computer commands Byte Building.'),
('wait_buildstart','Wait until construction of Byte Unit has started.'),
('wait_train','Wait until computer commands Byte Unit.'),
('clear_combatdata','Clear previous combat data.'),
('nuke_rate','Tells the AI to launch nukes every Byte minutes.'),
]),
('Flow control',[
('call','Call Block as a sub-routine.'),
('enemyowns_jump','If enemy has a Unit, jump to Block.'),
('enemyresources_jump','If enemy has at least Word(1) minerals and Word(2) gas then jump in Block.'),
('goto','Jump to Block.'),
('groundmap_jump','If it is a ground map(in other words, if the enemy is reachable without transports), jump to Block.'),
('killable','Allows the current thread to be killed by another one.'),
('kill_thread','Kill the current thread.'),
('notowns_jump','If computer doesn\'t have a Unit, jump to Block.'),
('race_jump','According to the enemy race, jump in Block(1) if enemy is Terran, Block(2) if Zerg or Block(3) if Protoss.'),
('random_jump','There is Byte chances out of 256 to jump to Block.'),
('resources_jump','If computer has at least Word(1) minerals and Word(2) gas then jump in Block.'),
('return','Return to the flow point of the call command.'),
('stop','Stop script code execution. Often used to close script blocks called simultaneously.'),
('time_jump','Jumps to Block if Byte normal game minutes have passed in the game.'),
('region_size','Something to do with an enemy being in an unknown radius of the computer.'),
('panic','Appears to trigger Block if attacked. Still unclear.'),
('rush','Depending on Byte, it detects combinations of units and buildings either built or building, and jumps to Block'),
('debug','Show debug string String and continue in Block.'),
]),
('Multiple threads',[
('expand','Run code at Block for expansion number Byte.'),
('multirun','Run simultaneously code (so in another thread) at Block.'),
]),
('Miscellaneous',[
('create_nuke','Create a nuke. Should only be used in campaign scripts.'),
('create_unit','Create Unit at map position (x,y) where x = Word(1) and y = Word(2). Should only be used in campaign scripts.'),
('define_max','Define maximum number of Unit to Byte.'),
('give_money','Give 2000 ore and gas if owned resources are low. Should only be used in campaign scripts.'),
('nuke_pos','Launch a nuke at map position (x,y) where x = Word(1) and y = Word(2). Should only be used in campaign scripts.'),
('send_suicide','Send all units to suicide mission. Byte determines which type, 0 = Strategic suicide; 1 = Random suicide.'),
('set_randomseed','Set random seed to DWord(1).'),
('switch_rescue','Switch computer to rescuable passive mode.'),
('help_iftrouble','Ask allies for help if ever in trouble.'),
('check_transports','Used in combination with header command transports_off, the AI will build and keep as many transports as was set by the define_max (max 5?) and use them for drops and expanding.'),
('creep','Effects the placement of towers (blizzard always uses 3 or 4 for Byte, see link below)'),
('get_oldpeons','Pull Byte existing workers from the main base to the expansion, but the main base will train the workers to replace the ones you took. Useful if you need workers as quickly as possible at the expansion.'),
]),
('StarEdit',[
('disruption_web','Disruption Web at selected location. (STAREDIT)'),
('enter_bunker','Enter Bunker in selected location. (STAREDIT)'),
('enter_transport','Enter in nearest Transport in selected location. (STAREDIT)'),
('exit_transport','Exit Transport in selected location. (STAREDIT)'),
('harass_location','AI Harass at selected location. (STAREDIT)'),
('junkyard_dog','Junkyard Dog at selected location. (STAREDIT)'),
('make_patrol','Make units patrol in selected location. (STAREDIT)'),
('move_dt','Move Dark Templars to selected location. (STAREDIT)'),
('nuke_location','Nuke at selected location. (STAREDIT)'),
('player_ally','Make selected player ally. (STAREDIT)'),
('player_enemy','Make selected player enemy. (STAREDIT)'),
('recall_location','Recall at selected location. (STAREDIT)'),
('sharedvision_off','Disable Shared Vision for selected player. (STAREDIT)'),
('sharedvision_on','Enable Shared vision for selected player. (STAREDIT)'),
('value_area','Value this area higher. (STAREDIT)'),
('set_gencmd','Set generic command target. (STAREDIT)'),
]),
('Unknown',[
('allies_watch','The use of this command is unknown. Takes Byte and Block as parameters.'),
('capt_expand','The use of this command is unknown. Takes no parameter.'),
('default_min','The use of this command is unknown. Takes Byte as parameter.'),
('defaultbuild_off','The use of this command is unknown. Takes no parameter.'),
('fake_nuke','The use of this command is unknown. Takes no parameters.'),
('guard_all','The use of this command is unknown. Takes no parameters.'),
('if_owned','The use of this command is unknown. Takes Unit and Block as parameters.'),
('max_force','The use of this command is unknown. Takes Word as parameter.'),
('place_guard','The use of this command is unknown. Takes Unit and Byte as parameters.'),
('player_need','The use of this command is unknown. Takes Byte and Building as parameters.'),
('scout_with','This command is unused.'),
('set_attacks','The use of this command is unknown. Takes Byte as parameter.'),
('target_expansion','The use of this command is unknown. Takes no parameter.'),
('try_townpoint','The use of this command is unknown. Takes Byte and Block as parameters.'),
('wait_force','The use of this command is unknown. Takes Byte and Unit as parameters.'),
]),
('Undefined',[
('build_bunkers','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('build_turrets','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('default_build','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('easy_attack','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('eval_harass','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('fatal_error','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('harass_factor','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('if_dif','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('if_towns','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('implode','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('prep_down','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('quick_attack','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('wait_bunkers','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('wait_secure','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('wait_turrets','The definition of this command is unknown. It is never used in Blizzard scripts.'),
('wait_upgrades','The definition of this command is unknown. It is never used in Blizzard scripts.'),
]),
]
CMD_HELP = odict()
for s,cmdl in cmds:
CMD_HELP[s] = odict()
for c,h in cmdl:
CMD_HELP[s][c] = h
#
class FindReplaceDialog(PyMSDialog):
def __init__(self, parent):
self.resettimer = None
PyMSDialog.__init__(self, parent, 'Find/Replace', grabwait=False, resizable=(True, False))
def widgetize(self):
self.find = StringVar()
self.replacewith = StringVar()
self.replace = IntVar()
self.inselection = IntVar()
self.casesens = IntVar()
self.regex = IntVar()
self.multiline = IntVar()
self.updown = IntVar()
self.updown.set(1)
l = Frame(self)
f = Frame(l)
s = Frame(f)
Label(s, text='Find:', anchor=E, width=12).pack(side=LEFT)
self.findentry = TextDropDown(s, self.find, self.parent.parent.findhistory, 30)
self.findentry.c = self.findentry['bg']
self.findentry.pack(fill=X)
self.findentry.entry.selection_range(0, END)
self.findentry.focus_set()
s.pack(fill=X)
s = Frame(f)
Label(s, text='Replace With:', anchor=E, width=12).pack(side=LEFT)
self.replaceentry = TextDropDown(s, self.replacewith, self.parent.parent.replacehistory, 30)
self.replaceentry.pack(fill=X)
s.pack(fill=X)
f.pack(side=TOP, fill=X, pady=2)
f = Frame(l)
self.selectcheck = Checkbutton(f, text='In Selection', variable=self.inselection, anchor=W)
self.selectcheck.pack(fill=X)
Checkbutton(f, text='Case Sensitive', variable=self.casesens, anchor=W).pack(fill=X)
Checkbutton(f, text='Regular Expression', variable=self.regex, anchor=W, command=lambda i=1: self.check(i)).pack(fill=X)
self.multicheck = Checkbutton(f, text='Multi-Line', variable=self.multiline, anchor=W, state=DISABLED, command=lambda i=2: self.check(i))
self.multicheck.pack(fill=X)
f.pack(side=LEFT, fill=BOTH)
f = Frame(l)
lf = LabelFrame(f, text='Direction')
self.up = Radiobutton(lf, text='Up', variable=self.updown, value=0, anchor=W)
self.up.pack(fill=X)
self.down = Radiobutton(lf, text='Down', variable=self.updown, value=1, anchor=W)
self.down.pack()
lf.pack()
f.pack(side=RIGHT, fill=Y)
l.pack(side=LEFT, fill=BOTH, pady=2, expand=1)
l = Frame(self)
Button(l, text='Find Next', command=self.findnext).pack(fill=X, pady=1)
Button(l, text='Count', command=self.count).pack(fill=X, pady=1)
self.replacebtn = Button(l, text='Replace', command=lambda i=1: self.findnext(replace=i))
self.replacebtn.pack(fill=X, pady=1)
self.repallbtn = Button(l, text='Replace All', command=self.replaceall)
self.repallbtn.pack(fill=X, pady=1)
Button(l, text='Close', command=self.ok).pack(fill=X, pady=4)
l.pack(side=LEFT, fill=Y, padx=2)
self.bind('<Return>', self.findnext)
self.bind('<FocusIn>', lambda e,i=3: self.check(i))
if 'findreplacewindow' in self.parent.parent.settings:
loadsize(self, self.parent.parent.settings, 'findreplacewindow')
return self.findentry
def check(self, i):
if i == 1:
if self.regex.get():
self.multicheck['state'] = NORMAL
else:
self.multicheck['state'] = DISABLED
self.multiline.set(0)
if i in [1,2]:
s = [NORMAL,DISABLED][self.multiline.get()]
self.up['state'] = s
self.down['state'] = s
if s == DISABLED:
self.updown.set(1)
elif i == 3:
if self.parent.text.tag_ranges('Selection'):
self.selectcheck['state'] = NORMAL
else:
self.selectcheck['state'] = DISABLED
self.inselection.set(0)
def findnext(self, key=None, replace=0):
f = self.find.get()
if not f in self.parent.parent.findhistory:
self.parent.parent.findhistory.append(f)
if f:
regex = f
if not self.regex.get():
regex = re.escape(regex)
try:
r = re.compile(regex, [re.I,0][self.casesens.get()] | [0,re.M | re.S][self.multiline.get()])
except:
self.resettimer = self.after(1000, self.updatecolor)
self.findentry['bg'] = '#FFB4B4'
return
if replace:
rep = self.replacewith.get()
if not rep in self.parent.parent.replacehistory:
self.parent.parent.replacehistory.append(rep)
item = self.parent.text.tag_ranges('Selection')
if item and r.match(self.parent.text.get(*item)):
ins = r.sub(rep, self.parent.text.get(*item))
self.parent.text.delete(*item)
self.parent.text.insert(item[0], ins)
self.parent.text.update_range(item[0])
if self.multiline.get():
m = r.search(self.parent.text.get(INSERT, END))
if m:
self.parent.text.tag_remove('Selection', '1.0', END)
s,e = '%s +%sc' % (INSERT, m.start(0)),'%s +%sc' % (INSERT,m.end(0))
self.parent.text.tag_add('Selection', s, e)
self.parent.text.mark_set(INSERT, e)
self.parent.text.see(s)
self.check(3)
else:
p = self
if key and key.keycode == 13:
p = self.parent
askquestion(parent=p, title='Find', message="Can't find text.", type=OK)
else:
u = self.updown.get()
s,lse,rlse,e = ['-','+'][u],['lineend','linestart'][u],['linestart','lineend'][u],[self.parent.text.index('1.0 lineend'),self.parent.text.index(END)][u]
i = self.parent.text.index(INSERT)
if i == e:
return
if i == self.parent.text.index('%s %s' % (INSERT, rlse)):
i = self.parent.text.index('%s %s1lines %s' % (INSERT, s, lse))
n = -1
while not u or i != e:
if u:
m = r.search(self.parent.text.get(i, '%s %s' % (i, rlse)))
else:
m = None
a = r.finditer(self.parent.text.get('%s %s' % (i, rlse), i))
c = 0
for x,f in enumerate(a):
if x == n or n == -1:
m = f
c = x
n = c - 1
if m:
self.parent.text.tag_remove('Selection', '1.0', END)
if u:
s,e = '%s +%sc' % (i,m.start(0)),'%s +%sc' % (i,m.end(0))
self.parent.text.mark_set(INSERT, e)
else:
s,e = '%s linestart +%sc' % (i,m.start(0)),'%s linestart +%sc' % (i,m.end(0))
self.parent.text.mark_set(INSERT, s)
self.parent.text.tag_add('Selection', s, e)
self.parent.text.see(s)
self.check(3)
break
if (not u and n == -1 and self.parent.text.index('%s lineend' % i) == e) or i == e:
p = self
if key and key.keycode == 13:
p = self.parent
askquestion(parent=p, title='Find', message="Can't find text.", type=OK)
break
i = self.parent.text.index('%s %s1lines %s' % (i, s, lse))
else:
p = self
if key and key.keycode == 13:
p = self.parent
askquestion(parent=p, title='Find', message="Can't find text.", type=OK)
def count(self):
f = self.find.get()
if f:
regex = f
if not self.regex.get():
regex = re.escape(regex)
try:
r = re.compile(regex, [re.I,0][self.casesens.get()] | [0,re.M | re.S][self.multiline.get()])
except:
self.resettimer = self.after(1000, self.updatecolor)
self.findentry['bg'] = '#FFB4B4'
return
askquestion(parent=self, title='Count', message='%s matches found.' % len(r.findall(self.parent.text.get('1.0', END))), type=OK)
def replaceall(self):
f = self.find.get()
if f:
regex = f
if not self.regex.get():
regex = re.escape(regex)
try:
r = re.compile(regex, [re.I,0][self.casesens.get()] | [0,re.M | re.S][self.multiline.get()])
except:
self.resettimer = self.after(1000, self.updatecolor)
self.findentry['bg'] = '#FFB4B4'
return
text = r.subn(self.replacewith.get(), self.parent.text.get('1.0', END))
if text[1]:
self.parent.text.delete('1.0', END)
self.parent.text.insert('1.0', text[0].rstrip('\n'))
self.parent.text.update_range('1.0')
askquestion(parent=self, title='Replace Complete', message='%s matches replaced.' % text[1], type=OK)
def updatecolor(self):
if self.resettimer:
self.after_cancel(self.resettimer)
self.resettimer = None
self.findentry['bg'] = self.findentry.c
def destroy(self):
self.parent.parent.settings['findreplacewindow'] = self.winfo_geometry()
PyMSDialog.withdraw(self)
class CodeColors(PyMSDialog):
def __init__(self, parent):
self.cont = False
self.tags = dict(parent.text.tags)
self.info = odict()
self.info['Block'] = 'The color of a --block-- in the code.'
self.info['Keywords'] = 'Keywords:\n extdef aiscript bwscript'
self.info['Types'] = 'Variable types:\n ' + ' '.join(AIBIN.types)
self.info['Commands'] = 'The color of all the commands.'
self.info['Number'] = 'The color of all numbers.'
self.info['TBL Format'] = 'The color of TBL formatted characters, like null: <0>'
self.info['Info Comment'] = 'The color of a one line Extra Information Comment either for a script or block.'
self.info['MultiInfo Comment'] = 'The color of a multi-line Extra Information Comment either for a script or block.'
self.info['Comment'] = 'The color of a regular comment.'
self.info['AI ID'] = 'The color of the AI ID in the AI header.'
self.info['Header String'] = 'The color of the String index in the AI header.'
self.info['Header Flags'] = 'The color of the Flags in the AI header'
self.info['Operators'] = 'The color of the operators:\n ( ) , = :'
self.info['Error'] = 'The color of an error when compiling.'
self.info['Warning'] = 'The color of a warning when compiling.'
self.info['Selection'] = 'The color of selected text in the editor.'
PyMSDialog.__init__(self, parent, 'Color Settings', resizable=(False, False))
def widgetize(self):
self.listbox = Listbox(self, font=couriernew, width=20, height=16, exportselection=0, activestyle=DOTBOX)
self.listbox.bind('<ButtonRelease-1>', self.select)
for t in self.info.keys():
self.listbox.insert(END, t)
self.listbox.select_set(0)
self.listbox.pack(side=LEFT, fill=Y, padx=2, pady=2)
self.fg = IntVar()
self.bg = IntVar()
self.bold = IntVar()
self.infotext = StringVar()
r = Frame(self)
opt = LabelFrame(r, text='Style:', padx=5, pady=5)
f = Frame(opt)
c = Checkbutton(f, text='Foreground', variable=self.fg, width=20, anchor=W)
c.bind('<ButtonRelease-1>', lambda e,i=0: self.select(e,i))
c.grid(sticky=W)
c = Checkbutton(f, text='Background', variable=self.bg)
c.bind('<ButtonRelease-1>', lambda e,i=1: self.select(e,i))
c.grid(sticky=W)
c = Checkbutton(f, text='Bold', variable=self.bold)
c.bind('<ButtonRelease-1>', lambda e,i=2: self.select(e,i))
c.grid(sticky=W)
self.fgcanvas = Canvas(f, width=32, height=32, background='#000000')
self.fgcanvas.bind('<Button-1>', lambda e,i=0: self.colorselect(e, i))
self.fgcanvas.grid(column=1, row=0)
self.bgcanvas = Canvas(f, width=32, height=32, background='#000000')
self.bgcanvas.bind('<Button-1>', lambda e,i=1: self.colorselect(e, i))
self.bgcanvas.grid(column=1, row=1)
f.pack(side=TOP)
Label(opt, textvariable=self.infotext, height=6, justify=LEFT).pack(side=BOTTOM, fill=X)
opt.pack(side=TOP, fill=Y, expand=1, padx=2, pady=2)
f = Frame(r)
ok = Button(f, text='Ok', width=10, command=self.ok)
ok.pack(side=LEFT, padx=3)
Button(f, text='Cancel', width=10, command=self.cancel).pack(side=LEFT)
f.pack(side=BOTTOM, pady=2)
r.pack(side=LEFT, fill=Y)
self.select()
return ok
def select(self, e=None, n=None):
i = self.info.getkey(int(self.listbox.curselection()[0]))
s = self.tags[i.replace(' ', '')]
if n == None:
t = self.info[i].split('\n')
text = ''
if len(t) == 2:
d = ' '
text = t[0] + '\n'
else:
d = ''
text += fit(d, t[-1], 35, True)[:-1]
self.infotext.set(text)
if s['foreground'] == None:
self.fg.set(0)
self.fgcanvas['background'] = '#000000'
else:
self.fg.set(1)
self.fgcanvas['background'] = s['foreground']
if s['background'] == None:
self.bg.set(0)
self.bgcanvas['background'] = '#000000'
else:
self.bg.set(1)
self.bgcanvas['background'] = s['background']
self.bold.set(s['font'] != None)
else:
v = [self.fg,self.bg,self.bold][n].get()
if n == 2:
s['font'] = [self.parent.text.boldfont,couriernew][v]
else:
s[['foreground','background'][n]] = ['#000000',None][v]
if v:
[self.fgcanvas,self.bgcanvas][n]['background'] = '#000000'
def colorselect(self, e, i):
if [self.fg,self.bg][i].get():
v = [self.fgcanvas,self.bgcanvas][i]
g = ['foreground','background'][i]
c = tkColorChooser.askcolor(parent=self, initialcolor=v['background'], title='Select %s color' % g)
if c[1]:
v['background'] = c[1]
self.tags[self.info.getkey(int(self.listbox.curselection()[0])).replace(' ','')][g] = c[1]
self.focus_set()
def ok(self):
self.cont = self.tags
PyMSDialog.ok(self)
def cancel(self):
self.cont = False
PyMSDialog.ok(self)
class AICodeText(CodeText):
def __init__(self, parent, ai, ecallback=None, icallback=None, scallback=None, highlights=None):
self.ai = ai
self.boldfont = ('Courier New', -11, 'bold')
if highlights:
self.highlights = highlights
else:
self.highlights = {
'Block':{'foreground':'#FF00FF','background':None,'font':None},
'Keywords':{'foreground':'#0000FF','background':None,'font':self.boldfont},
'Types':{'foreground':'#0000FF','background':None,'font':self.boldfont},
'Commands':{'foreground':'#0000AA','background':None,'font':None},
'Number':{'foreground':'#FF0000','background':None,'font':None},
'TBLFormat':{'foreground':None,'background':'#E6E6E6','font':None},
'InfoComment':{'foreground':'#FF963C','background':None,'font':None},
'MultiInfoComment':{'foreground':'#FF963C','background':None,'font':None},
'Comment':{'foreground':'#008000','background':None,'font':None},
'AIID':{'foreground':'#FF00FF','background':None,'font':self.boldfont},
'HeaderString':{'foreground':'#FF0000','background':None,'font':self.boldfont},
'HeaderFlags':{'foreground':'#8000FF','background':None,'font':self.boldfont},
'Operators':{'foreground':'#0000FF','background':None,'font':self.boldfont},
'Newline':{'foreground':None,'background':None,'font':None},
'Error':{'foreground':None,'background':'#FF8C8C','font':None},
'Warning':{'foreground':None,'background':'#FFC8C8','font':None},
}
CodeText.__init__(self, parent, ecallback, icallback, scallback)
self.text.bind('<Control-q>', self.commentrange)
def setedit(self):
if self.ecallback != None:
self.ecallback()
self.edited = True
def commentrange(self, e=None):
item = self.tag_ranges('Selection')
if item:
head,tail = self.index('%s linestart' % item[0]),self.index('%s linestart' % item[1])
while self.text.compare(head, '<=', tail):
m = re.match('(\s*)(#?)(.*)', self.get(head, '%s lineend' % head))
if m.group(2):
self.tk.call(self.text.orig, 'delete', '%s +%sc' % (head, len(m.group(1))))
elif m.group(3):
self.tk.call(self.text.orig, 'insert', head, '#')
head = self.index('%s +1line' % head)
self.update_range(self.index('%s linestart' % item[0]), self.index('%s lineend' % item[1]))
def setupparser(self):
infocomment = '(?P<InfoComment>\\{[^\\n]+\\})'
multiinfocomment = '^[ \\t]*(?P<MultiInfoComment>\\{[ \\t]*(?:\\n[^}]*)?\\}?)$'
comment = '(?P<Comment>#[^\\n]*$)'
header = '^(?P<AIID>[^\n\x00,():]{4})(?=\\([^#]+,[^#]+,[^#]+\\):.+$)'
header_string = '\\b(?P<HeaderString>\\d+)(?=,[^#]+,[^#]+\\):.+$)'
header_flags = '\\b(?P<HeaderFlags>[01]{3})(?=,[^#]+\\):.+$)'
block = '^[ \\t]*(?P<Block>--[^\x00:(),\\n]+--)(?=.+$)'
cmds = '\\b(?P<Commands>%s)\\b' % '|'.join(AIBIN.AIBIN.short_labels)
num = '\\b(?P<Number>\\d+)\\b'
tbl = '(?P<TBLFormat><0*(?:25[0-5]|2[0-4]\d|1?\d?\d)?>)'
operators = '(?P<Operators>[():,=])'
kw = '\\b(?P<Keywords>extdef|aiscript|bwscript)\\b'
types = '\\b(?P<Types>%s)\\b' % '|'.join(AIBIN.types)
self.basic = re.compile('|'.join((infocomment, multiinfocomment, comment, header, header_string, header_flags, block, cmds, num, tbl, operators, kw, types, '(?P<Newline>\\n)')), re.S | re.M)
self.tooptips = [CommandCodeTooltip(self.text,self.ai),TypeCodeTooltip(self.text,self.ai),StringCodeTooltip(self.text,self.ai),FlagCodeTooltip(self.text,self.ai)]
self.tags = dict(self.highlights)
def colorize(self):
next = '1.0'
while True:
item = self.tag_nextrange("Update", next)
if not item:
break
head, tail = item
self.tag_remove('Newline', head, tail)
item = self.tag_prevrange('Newline', head)
if item:
head = item[1] + ' linestart'
else:
head = "1.0"
chars = ""
next = head
lines_to_get = 1
ok = False
while not ok:
mark = next
next = self.index(mark + '+%d lines linestart' % lines_to_get)
lines_to_get = min(lines_to_get * 2, 100)
ok = 'Newline' in self.tag_names(next + '-1c')
line = self.get(mark, next)
if not line:
return
for tag in self.tags.keys():
if tag != 'Selection':
self.tag_remove(tag, mark, next)
chars = chars + line
m = self.basic.search(chars)
while m:
for key, value in m.groupdict().items():
if value != None:
a, b = m.span(key)
self.tag_add(key, head + '+%dc' % a, head + '+%dc' % b)
m = self.basic.search(chars, m.end())
if 'Newline' in self.tag_names(next + '-1c'):
head = next
chars = ''
else:
ok = False
if not ok:
self.tag_add('Update', next)
self.update()
if not self.coloring:
return
class CodeTooltip(Tooltip):
tag = ''
def __init__(self, widget, ai):
self.ai = ai
Tooltip.__init__(self, widget)
def setupbinds(self, press):
if self.tag:
self.widget.tag_bind(self.tag, '<Enter>', self.enter, '+')
self.widget.tag_bind(self.tag, '<Leave>', self.leave, '+')
self.widget.tag_bind(self.tag, '<Motion>', self.motion, '+')
self.widget.tag_bind(self.tag, '<Button-1>', self.leave, '+')
self.widget.tag_bind(self.tag, '<ButtonPress>', self.leave)
def showtip(self):
if self.tip:
return
t = ''
if self.tag:
pos = list(self.widget.winfo_pointerxy())
head,tail = self.widget.tag_prevrange(self.tag,self.widget.index('@%s,%s+1c' % (pos[0] - self.widget.winfo_rootx(),pos[1] - self.widget.winfo_rooty())))
t = self.widget.get(head,tail)
try:
t = self.gettext(t)
self.tip = Toplevel(self.widget, relief=SOLID, borderwidth=1)
self.tip.wm_overrideredirect(1)
frame = Frame(self.tip, background='#FFFFC8', borderwidth=0)
Label(frame, text=t, justify=LEFT, font=self.font, background='#FFFFC8', relief=FLAT).pack(padx=1, pady=1)
frame.pack()
pos = list(self.widget.winfo_pointerxy())
self.tip.wm_geometry('+%d+%d' % (pos[0],pos[1]+22))
self.tip.update_idletasks()
move = False
if pos[0] + self.tip.winfo_reqwidth() > self.tip.winfo_screenwidth():
move = True
pos[0] = self.tip.winfo_screenwidth() - self.tip.winfo_reqwidth()
if pos[1] + self.tip.winfo_reqheight() + 22 > self.tip.winfo_screenheight():
move = True
pos[1] -= self.tip.winfo_reqheight() + 44
if move:
self.tip.wm_geometry('+%d+%d' % (pos[0],pos[1]+22))
except:
if self.tip:
try:
self.tip.destroy()
except:
pass
self.tip = None
return
def gettext(self, t):
# Overload to specify tooltip text
return ''
class CommandCodeTooltip(CodeTooltip):
tag = 'Commands'
def gettext(self, cmd):
for help,info in CMD_HELP.iteritems():
if cmd in info:
text = '%s Command:\n %s(' % (help, cmd)
break
params = self.ai.parameters[self.ai.short_labels.index(cmd)]
pinfo = ''
if params:
pinfo = '\n\n'
done = []
for p in params:
t = p.__doc__.split(' ',1)[0]
text += t + ', '
if not t in done:
pinfo += fit(' %s: ' % t, TYPE_HELP[t], end=True, indent=4)
done.append(t)
text = text[:-2]
text += ')'
return text + '\n' + fit(' ', info[cmd], end=True)[:-1] + pinfo[:-1]
class TypeCodeTooltip(CodeTooltip):
tag = 'Types'
def gettext(self, type):
return '%s:\n%s' % (type, fit(' ', TYPE_HELP[type], end=True)[:-1])
class StringCodeTooltip(CodeTooltip):
tag = 'HeaderString'
def gettext(self, stringid):
stringid = int(stringid)
m = len(self.ai.tbl.strings)
if stringid > m:
text = 'Invalid String ID (Range is 0 to %s)' % (m-1)
else:
text = 'String %s:\n %s' % (stringid, TBL.decompile_string(self.ai.tbl.strings[stringid]))
return text
class FlagCodeTooltip(CodeTooltip):
tag = 'HeaderFlags'
def gettext(self, flags):
text = 'AI Script Flags:\n %s:\n ' % flags
if flags == '000':
text += 'None'
else:
text += '\n '.join([d for d,f in zip(['BroodWar Only','Invisible in StarEdit','Requires a Location'], flags) if f == '1'])
return text
class CodeEditDialog(PyMSDialog):
def __init__(self, parent, ids):
self.ids = ids
self.decompile = ''
self.file = None
self.autocomptext = TYPE_HELP.keys()
self.completing = False
self.complete = [None, 0]
t = ''
if ids:
t = ', '.join(ids[:5])
if len(ids) > 5:
t += '...'
t += ' - '
t += 'AI Script Editor'
PyMSDialog.__init__(self, parent, t, grabwait=False)
self.findwindow = None
def widgetize(self):
self.extrainfo = IntVar()
self.extrainfo.set(self.parent.settings.get('codeeditextrainfo', 1))
buttons = [
('save', self.save, 'Save (Ctrl+S)', '<Control-s>'),
('test', self.test, 'Test Code (Ctrl+T)', '<Control-t>'),
4,
('export', self.export, 'Export Code (Ctrl+E)', '<Control-e>'),
('saveas', self.exportas, 'Export As... (Ctrl+Alt+A)', '<Control-Alt-a>'),
('import', self.iimport, 'Import Code (Ctrl+I)', '<Control-i>'),
4,
('saveextra', self.extrainfo, 'Save Information Comments and Labels', True),
10,
('find', self.find, 'Find/Replace (Ctrl+F)', '<Control-f>'),
10,
('colors', self.colors, 'Color Settings (Ctrl+Alt+C)', '<Control-Alt-c>'),
10,
('asc3topyai', self.asc3topyai, 'Compile ASC3 to PyAI (Ctrl+Alt+P)', '<Control-Alt-p>'),
('debug', self.debuggerize, 'Debuggerize your code (Ctrl+D)', '<Control-D>'),
]
self.bind('<Alt-Left>', lambda e,i=0: self.gotosection(e,i))
self.bind('<Alt-Right>', lambda e,i=1: self.gotosection(e,i))
self.bind('<Alt-Up>', lambda e,i=2: self.gotosection(e,i))
self.bind('<Alt-Down>', lambda e,i=3: self.gotosection(e,i))
bar = Frame(self)
for btn in buttons:
if isinstance(btn, tuple):
image = get_img(btn[0])
if btn[3] == True:
button = Checkbutton(bar, image=image, width=20, height=20, indicatoron=0, variable=btn[1])
else:
button = Button(bar, image=image, width=20, height=20, command=btn[1])
self.bind(btn[3], btn[1])
button.image = image
button.tooltip = Tooltip(button, btn[2], couriernew)
button.pack(side=LEFT)
if button.winfo_reqwidth() > 26:
button['width'] = 18
if button.winfo_reqheight() > 26:
button['height'] = 18
else:
Frame(bar, width=btn).pack(side=LEFT)
bar.pack(fill=X, padx=2, pady=2)
self.text = AICodeText(self, self.parent.ai, self.edited, highlights=self.parent.highlights)
self.text.pack(fill=BOTH, expand=1, padx=1, pady=1)
self.text.icallback = self.statusupdate
self.text.scallback = self.statusupdate
self.text.acallback = self.autocomplete
self.status = StringVar()
if self.ids:
self.status.set("Original ID's: " + ', '.join(self.ids))
self.scriptstatus = StringVar()
self.scriptstatus.set('Line: 1 Column: 0 Selected: 0')
statusbar = Frame(self)
Label(statusbar, textvariable=self.status, bd=1, relief=SUNKEN, anchor=W).pack(side=LEFT, expand=1, padx=1, fill=X)
image = get_img('save')
self.editstatus = Label(statusbar, image=image, bd=0, state=DISABLED)
self.editstatus.image = image
self.editstatus.pack(side=LEFT, padx=1, fill=Y)
Label(statusbar, textvariable=self.scriptstatus, bd=1, relief=SUNKEN, anchor=W).pack(side=LEFT, expand=1, padx=1, fill=X)
statusbar.pack(side=BOTTOM, fill=X)
if self.ids:
self.after(1, self.load)
if 'codeeditwindow' in self.parent.settings:
loadsize(self, self.parent.settings, 'codeeditwindow', True)
return self.text
def gotosection(self, e, i):
c = [self.text.tag_prevrange, self.text.tag_nextrange][i % 2]
t = [('Error','Warning'),('AIID','Block')][i > 1]
a = c(t[0], INSERT)
b = c(t[1], INSERT)
s = None
if a:
if not b or self.text.compare(a[0], ['>','<'][i % 2], b[0]):
s = a
else:
s = b
elif b:
s = b
if s:
self.text.see(s[0])
self.text.mark_set(INSERT, s[0])
def autocomplete(self):
i = self.text.tag_ranges('Selection')
if i and '\n' in self.text.get(*i):
return False
self.completing = True
self.text.taboverride = ' (,)'
def docomplete(s, e, v, t):
self.text.delete(s, e)
self.text.insert(s, v)
ss = '%s+%sc' % (s,len(t))
se = '%s+%sc' % (s,len(v))
self.text.tag_remove('Selection', '1.0', END)
self.text.tag_add('Selection', ss, se)
if self.complete[0] == None:
self.complete = [t, 1, s, se]
else:
self.complete[1] += 1
self.complete[3] = se
if self.complete[0] != None:
t,f,s,e = self.complete
else:
s,e = self.text.index('%s -1c wordstart' % INSERT),self.text.index('%s -1c wordend' % INSERT)
t,f = self.text.get(s,e),0
if t and t[0].lower() in 'abcdefghijklmnopqrstuvwxyz':
ac = list(self.autocomptext)
m = re.match('\\A\\s*[a-z\\{]+\\Z',t)
if not m:
for _,c in CMD_HELP.iteritems():
ac.extend(c.keys())
for ns in self.parent.tbl.strings[:228]:
cs = ns.split('\x00')
if cs[1] != '*':
cs = TBL.decompile_string('\x00'.join(cs[:2]), '\x0A\x28\x29\x2C')
else:
cs = TBL.decompile_string(cs[0], '\x0A\x28\x29\x2C')
if not cs in ac:
ac.append(cs)
for i in range(61):
cs = TBL.decompile_string(self.parent.tbl.strings[self.parent.upgrades.get_value(i,'Label') - 1].split('\x00',1)[0].strip(), '\x0A\x28\x29\x2C')
if not cs in ac:
ac.append(cs)
for i in range(44):
cs = TBL.decompile_string(self.parent.tbl.strings[self.parent.tech.get_value(i,'Label') - 1].split('\x00',1)[0].strip(), '\x0A\x28\x29\x2C')
if not cs in ac:
ac.append(cs)
aiid = ''
item = self.text.tag_prevrange('AIID', INSERT)
if item:
aiid = self.text.get(*item)
head = '1.0'
while True:
item = self.text.tag_nextrange('Block', head)
if not item:
break
head,tail = item
block = ''
if aiid:
item = self.text.tag_prevrange('AIID', head)
if item:
id = self.text.get(*item)
if id != aiid:
block = id + ':'
block += self.text.get('%s +2c' % head,'%s -2c' % tail)
if not block in ac:
ac.append(block)
head = tail
ac.sort()
if not m:
x = []
for _,c in CMD_HELP.iteritems():
x.extend(c.keys())
x.sort()
ac = x + ac
r = False
matches = []
for v in ac:
if v and v.lower().startswith(t.lower()):
matches.append(v)
if matches:
if f < len(matches):
docomplete(s,e,matches[f],t)
self.text.taboverride = ' (,)'
elif self.complete[0] != None:
docomplete(s,e,t,t)
self.complete[1] = 0
r = True
self.after(1, self.completed)
return r
def completed(self):
self.completing = False
def statusupdate(self):
if not self.completing:
self.text.taboverride = False
self.complete = [None, 0]
i = self.text.index(INSERT).split('.') + [0]
item = self.text.tag_ranges('Selection')
if item:
i[2] = len(self.text.get(*item))
self.scriptstatus.set('Line: %s Column: %s Selected: %s' % tuple(i))
def edited(self):
if not self.completing:
self.text.taboverride = False
self.complete = [None, 0]
self.editstatus['state'] = NORMAL
if self.file:
self.title('AI Script Editor [*%s*]' % self.file)
def cancel(self):
if self.text.edited:
save = askquestion(parent=self, title='Save Code?', message="Would you like to save the code?", default=YES, type=YESNOCANCEL)
if save != 'no':
if save == 'cancel':
return
self.save()
self.ok()
def save(self, e=None):
if self.parent.iimport(iimport=self, parent=self, extra=self.extrainfo.get()):
self.text.edited = False
self.editstatus['state'] = DISABLED
def ok(self):
savesize(self, self.parent.settings, 'codeeditwindow')
self.parent.settings['codeeditextrainfo'] = self.extrainfo.get()
PyMSDialog.ok(self)
def test(self, e=None):
i = AIBIN.AIBIN(False, self.parent.unitsdat, self.parent.upgradesdat, self.parent.techdat, self.parent.tbl)
i.bwscript = AIBIN.BWBIN(self.parent.unitsdat, self.parent.upgradesdat, self.parent.techdat, self.parent.tbl)
try:
warnings = i.interpret(self, self.parent.extdefs)
for id in i.ais.keys():
if id in self.parent.ai.externaljumps[0]:
for o,l in self.parent.ai.externaljumps[0].iteritems():
for cid in l:
if not cid in i.ais:
raise PyMSError('Interpreting',"You can't edit scripts (%s) that are referenced externally with out editing the scripts with the external references (%s) at the same time." % (id,cid))
except PyMSError, e:
if e.line != None:
self.text.see('%s.0' % e.line)
self.text.tag_add('Error', '%s.0' % e.line, '%s.end' % e.line)
if e.warnings:
for w in e.warnings:
if w.line != None:
self.text.tag_add('Warning', '%s.0' % w.line, '%s.end' % w.line)
ErrorDialog(self, e)
return
if warnings:
c = False
for w in warnings:
if w.line != None:
if not c:
self.text.see('%s.0' % w.line)
c = True