-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplay.py
executable file
·2407 lines (2396 loc) · 88.8 KB
/
play.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 python
# play.py - pydink player: engine for playing for pydink games.
# Copyright 2011 Bas Wijnen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Data management:
# Global data is stored by changing the game as an editor.
# Global variables are in the_globals.
# Local variables are in the_locals, which is a local variable of Script().
# Static variables are in the_statics[fname], which is a member of Sprite; see below.
# Current screen: scripts.
# A new script is instantiated whenever a function is called. This is different from the original game.
# It means that kill_this_task is useless (and not supported), and that you need static (or global) variables to communicate between event functions.
# function calls lock the calling function until the called function returns. This is implemented with generators.
# There is no way to communicate with a running script. It is not possible to count the scripts. There is no limit on the number of running scripts (except available memory).
# Current screen: sprites.
# Don't confuse Sprite and dink.Sprite! The former is a sprite on the screen, the latter a sprite in the editor.
# All dink.Sprites of a screen are copied into Sprites when load_screen() is called.
# A Sprite has the following members:
# visible, x, y, brain, hitpoints, defense, strength, gold, size, seq, frame, pseq, pframe, speed, base_walk, base_idle, base_attack, base_death, timing, que, hard, cropbox, warp, touch_seq, exp, sound, vision, nohit, touch_damage, script.
# src, num, editor_num, the_statics (dictionary of variables).
# Background sprites are drawn to the background pixmap, after that, the object is destroyed. It is impossible to adjust anything about them.
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
import gtkdink
import gobject
import pango
import sys
import os
import datetime
import random
import numpy
import pygame # for sound
NONEBRAIN = gtkdink.dink.make_brain ('none')
DINKBRAIN = gtkdink.dink.make_brain ('dink')
HEADLESSBRAIN = gtkdink.dink.make_brain ('headless')
DUCKBRAIN = gtkdink.dink.make_brain ('duck')
PIGBRAIN = gtkdink.dink.make_brain ('pig')
MARKBRAIN = gtkdink.dink.make_brain ('mark')
REPEATBRAIN = gtkdink.dink.make_brain ('repeat')
PLAYBRAIN = gtkdink.dink.make_brain ('play')
TEXTBRAIN = gtkdink.dink.make_brain ('text')
MONSTERBRAIN = gtkdink.dink.make_brain ('monster')
ROOKBRAIN = gtkdink.dink.make_brain ('rook')
MISSILEBRAIN = gtkdink.dink.make_brain ('missile')
RESIZEBRAIN = gtkdink.dink.make_brain ('resize')
POINTERBRAIN = gtkdink.dink.make_brain ('pointer')
BUTTONBRAIN = gtkdink.dink.make_brain ('button')
SHADOWBRAIN = gtkdink.dink.make_brain ('shadow')
PERSONBRAIN = gtkdink.dink.make_brain ('person')
FLAREBRAIN = gtkdink.dink.make_brain ('flare')
BUTTON_ACTION = 1
BUTTON_TALK = 2
BUTTON_MAGIC = 3
BUTTON_INVENTORY = 4
BUTTON_ESCAPE = 5
BUTTON_MAP = 6
BUTTON_DOWN = 12
BUTTON_LEFT = 14
BUTTON_RIGHT = 16
BUTTON_UP = 18
class Sprite:
def __init__ (self, data, x = None, y = None, brain = None, seq = None, frame = None, script = None, src = None, view = None):
self.data = data
self.last_time = data.current_time
self.alive = True
self.have_brain = False
if brain is not None:
brain = gtkdink.dink.make_brain (brain)
if src is not None:
map = data.the_globals['player_map']
map_x = (map - 1) % 32
map_y = (map - 1) / 32
assert brain == None and seq == None and frame == None and script == None
self.name = src.name
self.visible = src.is_visible ()
self.x = (src.x - map_x * 12 * 50) if x is None else x
self.y = (src.y - map_y * 8 * 50) if y is None else y
self.size = src.size
self.seq = None
self.frame = 1
self.pseq = data.data.seq.find_seq (src.seq)
self.pframe = src.frame
self.brain = gtkdink.dink.make_brain (src.brain)
self.hitpoints = src.hitpoints
self.defense = src.defense
self.strength = src.strength
self.gold = src.gold
self.speed = src.speed
self.base_walk = src.base_walk if src.base_walk is not None else ''
self.base_idle = src.base_idle if src.base_idle is not None else ''
self.base_attack = src.base_attack if src.base_attack is not None else ''
self.base_death = src.base_death if src.base_death is not None else ''
self.timing = src.timing
self.que = src.que
self.hard = src.hard
self.cropbox = (src.left, src.top, src.right, src.bottom)
self.warp = src.warp
self.touch_seq = data.data.seq.find_seq (src.touch_seq)
self.experience = src.experience
self.sound = src.sound
self.vision = src.vision
self.nohit = src.nohit
self.touch_damage = src.touch_damage
self.editor_num = src.editcode
self.script = src.script
else:
assert x != None and y != None and brain != None and ((brain == TEXTBRAIN and seq == None and frame == None) or (brain != TEXTBRAIN and seq != None and frame != None))
self.name = None
self.visible = True
self.x = x
self.y = y
self.brain = brain
self.hitpoints = 0
self.defense = 0
self.strength = 0
self.gold = 0
self.size = 100
self.seq = None
self.frame = 1
self.pseq = data.data.seq.find_seq (seq) if seq != None else None
self.pframe = frame
self.speed = 0
self.base_walk = ''
self.base_idle = ''
self.base_attack = ''
self.base_death = ''
self.timing = 20
self.que = 0
self.hard = False
self.cropbox = (0, 0, 0, 0)
self.warp = None
self.touch_seq = None
self.experience = 0
self.sound = ''
self.vision = 0
self.nohit = False
self.touch_damage = 0
self.editor_num = None
self.script = script
self.text = None
self.brain_parm = 0
self.brain_parm2 = 0
self.range = 40
self.distance = 0
self.reverse = False
self.flying = False
self.follow = 0
self.target = 0
self.nodraw = False
self.nocontrol = False
self.frame_delay = None
self.kill_time = None
self.deathcb = None
self.dir = 2
self.clip = True
self.frozen = False
self.mx = 0
self.my = 0
self.mxlimit = None
self.mylimit = None
self.mblock = None
self.bbox = (0, 0, 0, 0) # This will be updated when it is drawn.
self.the_statics = {}
if self.script:
if self.script not in data.functions:
print ("Warning: script %s doesn't exist" % self.script)
else:
for v in data.functions[self.script][''][0]:
self.the_statics[v] = 0
self.cache = (None,)
self.src = src
self.state = None
self.num = 0
self.set_state ('passive')
self.view = view
if view is not None:
self.num = data.next_sprite
data.next_sprite += 1
view.sprites[self.num] = self
def set_killdelay (self, delay):
olddelay = self.kill_time is not None
self.kill_time = self.data.current_time + datetime.timedelta (milliseconds = delay) if delay is not None else None
if olddelay and not delay:
self.view.kill_queue.remove (self)
elif not olddelay and delay:
self.view.kill_queue.append (self)
if delay:
self.view.kill_queue.sort (key = lambda x: x.kill_time)
def kill (self):
if not self.alive:
return
if self.num == 1:
# Don't kill Dink; code everywhere depends on its existence.
return
del self.view.sprites[self.num]
self.alive = False
if self.brain == TEXTBRAIN and self.owner:
self.owner.text = None
if self in self.view.blocker:
self.view.blocker.remove (self)
if self.deathcb:
self.view.events += ((self.data.current_time - datetime.timedelta (seconds = 1), self.deathcb[0], self.deathcb[1]),)
def set_state (self, state = None):
assert self.num != 1 or self.brain != NONEBRAIN
# First set dir according to movement.
if self.mx != 0 or self.my != 0:
mx, my = [t / abs (t) if t != 0 else 0 for t in (self.mx, self.my)]
self.dir = mx + 1 + 4 - 3 * my
if state != self.state:
self.frame = 1
if state != None:
self.state = state
# Set seq according to state.
if self.state == 'passive':
return
elif self.state == 'idle':
if self.base_idle:
self.seq = self.data.data.seq.get_dir_seq (self.base_idle, self.dir)
elif self.base_walk:
self.seq = None
self.pseq = self.data.data.seq.get_dir_seq (self.base_walk, self.dir)
self.pframe = 1
else:
self.seq = None
elif self.state == 'walk':
if self.base_walk:
self.seq = self.data.data.seq.get_dir_seq (self.base_walk, self.dir)
elif self.state == 'attack':
if self.base_attack:
self.seq = self.data.data.seq.get_dir_seq (self.base_attack, self.dir)
elif self.state == 'die':
if self.base_death:
self.seq = self.data.data.seq.get_dir_seq (self.base_death, self.dir)
else:
raise AssertionError ('invalid state %s' % state)
class View:
cursorkeys = (Gtk.keysyms.Left, Gtk.keysyms.Up, Gtk.keysyms.Right, Gtk.keysyms.Down)
def __init__ (self, data):
self.data = data
self.sprites = {}
self.events = []
self.choice = None
self.choice_title = None
self.choice_response = None
self.choice_current = 0
self.choice_waiter = None
self.stopped = False
self.wait_for_button = None
self.warp_wait = None
self.screenlock = False
self.blocker = []
self.fade_block = []
self.enable_sprites = True
self.kill_queue = []
self.push_delay = 0
self.touch_delay = 0
self.push_active = True
self.bow = [False, None, None, None]
self.fade = (0, True, self.data.current_time)
self.dink_can_walk_off_screen = False
self.bg = Gdk.Pixmap (self.data.window, self.data.winw, self.data.winh)
self.choice_sprites = [Sprite (self.data, x, y, brain, seq, frame, '', view = None) for x, y, brain, seq, frame in ((181, 270, 'none', 'textbox', 2), (355, 254, 'none', 'textbox', 3), (528, 270, 'none', 'textbox', 4), (165, 104, 'repeat', 'arrow-l', 4), (503, 104, 'repeat', 'arrow-r', 4))]
self.events += ((self.data.current_time, self.update (), -2),)
# Create pointer sprite.
self.sprites[1] = Sprite (self.data, 320, 240, 'pointer', 'special', 8, '', view = None)
self.sprites[1].num = 1
self.sprites[1].timing = 10
self.sprites[1].have_brain = True
self.events += ((self.data.current_time, self.do_brain (self.sprites[1]), -1),)
self.sprites[1].last_time = self.data.current_time
self.last_time = data.current_time
self.stat_info = {}
for stat, x, y, width, size, seq, step in (
('strength', 126, 428, 16, 3, 'numr', 1),
('defense', 126, 450, 16, 3, 'numb', 1),
('magic', 126, 472, 16, 3, 'nump', 1),
('exp', 450, 467, 10, 5, 'nums', 9),
('gold', 373, 470, 16, 5, 'numy', 9),
('level', 534, 471, 8, 1, 'level', 1),
):
self.stat_info[stat] = [0, Sprite (self.data, x, y, 'none', seq, 1, '', view = None), x, width, size, step]
self.stat_info[stat][1].clip = False
self.stat_info['life'] = [10, Sprite (self.data, 0, 425, 'none', 'health-r', 1, '', view = None), 300, 425, None, 1]
self.stat_info['life'][1].clip = False
self.stat_info['lifemax'] = [10, Sprite (self.data, 0, 425, 'none', 'health-w', 1, '', view = None), 300, 425, None, 1]
self.stat_info['lifemax'][1].clip = False
def add_sprite (self, x = None, y = None, brain = None, seq = None, frame = None, script = None, src = None):
ret = Sprite (self.data, x, y, brain, seq, frame, script, src = src, view = self)
self.data.run_script (ret.script, 'main', (), ret)
ret.have_brain = True
self.events += ((self.data.current_time, self.do_brain (ret), ret.num),)
ret.last_time = self.data.current_time
return ret
def get_sprite_by_editor_num (self, num):
for s in self.sprites:
if self.sprites[s].editor_num == num:
return self.sprites[s]
return None
def get_sprite_by_name (self, name):
for s in self.sprites:
if self.sprites[s].name == name:
return s
return 0
def get_editor_sprite (self, num):
for s in self.data.data.world.sprite:
if s.editcode == num:
return s
return None
def try_touch (self, target):
if not target.touch_seq:
return False
# Play touch sequence before warping.
# Find instantiated sprite.
find = [self.sprites[x] for x in self.sprites if self.sprites[x].src == target]
if len (find) > 0:
spr = find[0]
spr.seq = spr.touch_seq
spr.frame = 1
spr.brain = NONEBRAIN
spr.frame_delay = None
spr.last_time = self.data.current_time
else:
touch = self.data.data.seq.find_seq (target.touch_seq)
if touch is None:
print "Touch seq %s doesn't exist" % target.touch_seq
return False
# Create a new sprite.
map = self.data.the_globals['player_map']
map_x = (map - 1) % 32
map_y = (map - 1) / 32
spr = self.add_sprite (target.x - map_x * 12 * 50, target.y - map_y * 8 * 50, 'none', touch.code, 1)
spr.seq = touch
spr.frame = 1
spr.que = target.que
self.warp_wait = spr
return True
def do_brain (self, sprite):
while True:
# Reschedule callback. Do this at start, so continue can be used.
yield ('wait', sprite.timing)
# If this sprite is passive or dead, don't reschedule this function.
if not sprite.alive or (sprite.brain not in (DINKBRAIN, DUCKBRAIN, PIGBRAIN, PERSONBRAIN, MONSTERBRAIN, ROOKBRAIN, MISSILEBRAIN, FLAREBRAIN, HEADLESSBRAIN) and sprite.mx == 0 and sprite.my == 0):
sprite.have_brain = False
yield ('return', 0)
return
if sprite.nocontrol:
# Disable brain until control is back.
continue
# Move.
if not (0 <= sprite.y + sprite.my < 400) or not (0 <= sprite.x + sprite.mx - 20 < 600):
if sprite.brain == DINKBRAIN and not self.dink_can_walk_off_screen and not self.screenlock:
# Move to new screen (if possible).
if sprite.y + sprite.my < 0:
self.try_move (0, -1)
elif sprite.x + sprite.mx - 20 < 0:
self.try_move (-1, 0)
elif sprite.y + sprite.my >= 400:
self.try_move (0, 1)
elif sprite.x + sprite.mx - 20 >= 600:
self.try_move (1, 0)
# Whether it worked or not, don't do anything else.
continue
c = 1
else:
c = self.hardmap[sprite.y + sprite.my][sprite.x + sprite.mx - 20]
need_new_dir = False
mx, my = sprite.mx, sprite.my
if ((c == 0 or c == 1 and sprite.flying) and (mx != 0 or my != 0)) or sprite.mxlimit is not None or sprite.mylimit is not None:
sprite.x += sprite.mx
sprite.y += sprite.my
mx, my = 0, 0
sprite.set_state ('walk')
if sprite.brain == DINKBRAIN:
self.push_delay = 0
# limit[1] is True for negative movement, False for positive movement.
if (sprite.mxlimit is not None and (sprite.x < sprite.mxlimit[0]) == sprite.mxlimit[1]) or (sprite.mylimit is not None and (sprite.y < sprite.mylimit[0]) == sprite.mylimit[1]):
sprite.mx, sprite.my = 0, 0
sprite.mxlimit, sprite.mylimit = None, None
sprite.set_state ('idle')
if sprite.mblock:
self.events += ((self.data.current_time - datetime.timedelta (seconds = 1), sprite.mblock[0], sprite.mblock[1]),)
sprite.mblock = None
elif sprite.brain == DINKBRAIN and (mx != 0 or my != 0):
if c > 2:
target = self.get_editor_sprite (c)
if target.warp != None:
# Warp.
if not self.try_touch (target):
# Fade while warping.
self.fade = 500, False, self.data.current_time
# Freeze Dink during the touch sequence and fade down. He will be unfrozen at load_screen.
sprite.frozen = True
# Wake up when the fade is done. In case of a touch sequence, the fade is started from update.
yield ('stop', lambda x: self.fade_block.append (x))
self.data.the_globals['player_map'] = target.warp[0]
self.sprites[1].x = target.warp[1]
self.sprites[1].y = target.warp[2]
self.load_screen ()
self.fade = 500, True, self.data.current_time
# Push.
if self.push_active:
self.push_delay += 1
if self.push_delay == 50:
# Start pushing. Note that this is triggered only once, but Dink keeps pushing until something happens.
sprite.seq = self.data.data.seq.get_dir_seq ('push', sprite.dir)
# Call push() on affected sprite.
if c < 0 and -c in self.sprites:
# Generated sprite.
self.data.run_script (self.sprites[-c].script, 'push', (), self.sprites[-c])
elif c > 2:
# Editor sprite.
target = self.get_sprite_by_editor_num (c)
if target:
self.data.run_script (target.script, 'push', (), target)
elif sprite.brain in (DUCKBRAIN, PIGBRAIN, PERSONBRAIN):
# Stop walking.
sprite.mx = 0
sprite.my = 0
sprite.set_state ('idle')
elif sprite.brain in (MONSTERBRAIN, ROOKBRAIN):
# Choose new direction.
need_new_dir = True
if sprite.mxlimit is None and sprite.mylimit is None and sprite.speed > 0 and not sprite.frozen and sprite.brain in (DUCKBRAIN, PIGBRAIN, MONSTERBRAIN, ROOKBRAIN, PERSONBRAIN) and (need_new_dir or random.random () < (.01 if sprite.mx != 0 or sprite.my != 0 else .05)):
r = (-1, 0), (1, 0), (0, -1), (0, 1)
m = (-1, -1), (1, -1), (-1, 1), (1, 1)
if sprite.brain == ROOKBRAIN:
sprite.mx, sprite.my = random.choice (r)
sprite.set_state ('walk')
elif sprite.brain == MONSTERBRAIN:
sprite.mx, sprite.my = random.choice (m)
sprite.set_state ('walk')
elif sprite.brain == PIGBRAIN:
sprite.mx, sprite.my = random.choice (m)
sprite.set_state ('walk')
elif (sprite.mx, sprite.my) == (0, 0):
sprite.mx, sprite.my = random.choice (r + m)
sprite.set_state ('walk')
else:
sprite.mx, sprite.my = 0, 0
sprite.set_state ('idle')
sprite.dir = (mx + 1) + 3 * (my + 1) + 1
sprite.mx *= sprite.speed
sprite.my *= sprite.speed
elif sprite.frozen and sprite.mxlimit is None and sprite.mylimit is None:
sprite.mx, sprite.my = 0, 0
sprite.set_state ('idle')
if sprite.brain in (DINKBRAIN, MISSILEBRAIN, FLAREBRAIN, POINTERBRAIN) and sprite.mxlimit is None and sprite.mylimit is None:
# Test touch damage, warp and missile explosions.
for s in self.sprites.keys ():
if s not in self.sprites:
# This can happen because scripts are run from this loop.
continue
spr = self.sprites[s]
if spr == sprite or spr.brain == TEXTBRAIN:
continue
if spr.seq == None:
assert spr.pseq != None
seq = (spr.pseq, spr.pframe)
else:
seq = (spr.seq, spr.frame)
box = seq[0].frames[seq[1]].hardbox
if spr.x + box[0] <= sprite.x + mx <= spr.x + box[2] and spr.y + box[1] <= sprite.y + my <= spr.y + box[3]:
if sprite.brain == DINKBRAIN:
if spr.touch_damage != 0 and not sprite.nohit and not self.touch_delay:
if spr.touch_damage > 0:
self.touch_delay = 10
self.damage (spr.touch_damage, sprite, spr)
self.data.run_script (spr.script, 'touch', (), spr)
# TODO: only stop the direction in which the object is hit.
elif not spr.nohit:
# TODO: Explode.
pass
if self.data.space and sprite.brain == DINKBRAIN and not sprite.frozen:
self.data.space = False
# Talk.
targets = [x for x in self.hit_list (sprite, sprite.seq) if x.script in self.data.scripts and 'talk' in self.data.scripts[x.script]]
if len (targets) == 0:
self.data.run_script ('dnotalk', 'main', (), None)
else:
# Find closest.
targets.sort (key = lambda x: ((x.x - sprite.x) ** 2 + (x.y - sprite.y) ** 2))
self.data.run_script (targets[0].script, 'talk', (), targets[0])
if self.data.shift and sprite.brain == DINKBRAIN and not sprite.frozen:
# Cast magic.
if 0 < self.data.current_magic < len (self.data.magic) and self.data.magic[self.data.current_magic][0] is not None:
if self.data.the_globals['magic_level'] >= self.data.the_globals['magic_cost']:
self.data.the_globals['magic_level'] = 0
self.data.run_script (self.data.magic[self.data.current_magic][0], 'use', (), None)
else:
self.data.run_script ('dnomagic', 'main', (), None)
self.data.shift = False # This will never work, and it shouldn't trigger this script again.
def try_move (self, dx, dy):
# Move to a new screen if possible, otherwise do nothing.
screen = self.data.the_globals['player_map']
if screen == None:
return
oldx = (screen - 1) % 32
newscreen = screen + dx + 32 * dy
if not 0 <= oldx + dx < 32 or newscreen not in self.data.data.world.map:
return
# TODO: Make cool transition.
self.data.the_globals['player_map'] = newscreen
self.sprites[1].x -= dx * 599
self.sprites[1].y -= dy * 399
self.load_screen ()
def load_screen (self):
while len (self.sprites) > 1:
l = self.sprites.keys ()
self.sprites[l[1] if l[0] == 1 else l[0]].kill ()
# Kill all scripts, except those marked to survive.
self.events = [x for x in self.events if x[2] < 0]
spritelist = self.make_bg ()
self.sprites = { 1: self.sprites[1] }
self.sprites[1].frozen = False
self.screenlock = False
self.next_sprite = 2
if self.data.the_globals['player_map'] in self.data.data.world.map:
map = self.data.data.world.map[self.data.the_globals['player_map']]
script = map.script
self.data.run_script (script, 'main', (), None)
if map.music:
self.data.play_music (map.music)
for s in spritelist:
self.add_sprite (src = s)
self.make_hardmap ()
self.data.current_time = datetime.datetime.utcnow ()
self.data.checkpoint = self.data.current_time
for s in self.sprites:
spr = self.sprites[s]
self.data.run_script (spr.script, 'main', (), spr)
if spr.sound:
self.data.play_sound (spr.sound, True, spr)
self.compute_dir ()
def make_bg (self):
'''Write background to self.bg; return list of non-background sprites (sprite, x, y).'''
ret = []
# Draw tiles
if self.data.the_globals['player_map'] not in self.data.data.world.map:
self.data.gc.set_foreground (self.data.data.get_color (0))
self.bg.draw_rectangle (self.data.gc, True, 0, 0, 12 * self.data.data.scale, 8 * self.data.data.scale)
return ret
screen = self.data.data.world.map[self.data.the_globals['player_map']]
for y in range (8):
for x in range (12):
tile = screen.tiles[y][x]
self.bg.draw_drawable (self.data.gc, self.data.data.get_tiles (tile[0]), self.data.data.scale * tile[1], self.data.data.scale * tile[2], self.data.offset + self.data.data.scale * x, self.data.data.scale * y, self.data.data.scale, self.data.data.scale)
# Draw bg sprites
for s in self.data.data.world.map[self.data.the_globals['player_map']].sprite:
layer = self.parent.editor_sprites (s.num)['layer']
self.parent.is_visible (layer) and self.parent.is_bg (layer):
self.draw_sprite (self.bg, Sprite (self.data, src = s, view = None))
if self.parent.is_fg (layer):
ret += (s,)
return ret
def handle_event (self, now, target, sprite):
# This normally runs once, but a failed choice may need to run the whole function again.
while True:
if sprite in self.sprites and not self.sprites[sprite].alive:
return
result = next (target)
if result[0] in ('return', 'kill'):
pass
elif result[0] == 'stop':
result[1] ((target, sprite))
elif result[0] == 'wait':
if result[1] > 0:
then = now + datetime.timedelta (milliseconds = result[1])
if then < self.data.checkpoint:
then = self.data.checkpoint
if self.stopped:
self.stopped[1].append ((then, target, sprite))
else:
self.data.get_view ().events += ((then, target, sprite),)
else:
self.data.get_view ().events += ((self.data.current_time + datetime.timedelta (milliseconds = -result[1]), target, sprite),)
elif result[0] == 'error':
print ('Error reported: %s' % result[1])
elif result[0] == 'choice':
# Fail if we're already in a choice.
if self.choice_waiter is not None:
# Immediately continue the script, returning 0.
self.choice_response = 0
continue
self.choice_waiter = target, sprite
self.choice_current = 0
else:
raise AssertionError ('invalid return type %s' % result[0])
return
def next_event (self):
self.events.sort (key = lambda x: x[0])
self.data.current_time = datetime.datetime.utcnow ()
while self.data.current_time >= self.events[0][0] and self.data.get_view () == self:
self.handle_event (*self.events.pop (0))
self.events.sort (key = lambda x: x[0])
self.data.schedule_next ()
return False
def next_kill (self):
self.data.current_time = datetime.datetime.utcnow ()
while len (self.kill_queue) > 0 and self.kill_queue[0].kill_time <= self.data.current_time:
self.kill_queue.pop (0).kill ()
self.data.schedule_next ()
return False
def schedule_next (self):
if self.events == []:
# If for some reason dying didn't work, try again.
Gtk.main_quit ()
return
if self.data.dying:
# Don't schedule new events when dying.
return
if len (self.kill_queue) > 0 and self.kill_queue[0].kill_time < self.events[0][0]:
if self.kill_queue[0].kill_time > self.data.current_time:
t = self.kill_queue[0].kill_time - self.data.current_time
gobject.timeout_add ((t.days * 24 * 3600 + t.seconds) * 1000 + t.microseconds / 1000, self.next_kill)
else:
gobject.timeout_add (0, self.next_kill)
else:
if self.events[0][0] > self.data.current_time:
t = self.events[0][0] - self.data.current_time
gobject.timeout_add ((t.days * 24 * 3600 + t.seconds) * 1000 + t.microseconds / 1000, self.next_event)
else:
gobject.timeout_add (0, self.next_event)
def hit_list (self, sprite, seq):
'''Return a list of sprites which can be hit by this one. Used for hit and talk.'''
if seq is None or isinstance (seq.name, str) or seq.name[1] == 'die':
mx, my = 0, 0
else :
mx, my = (None, (-1, 1), (0, 1), (1, 1), (-1, 0), None, (1, 0), (-1, -1), (0, -1), (1, -1))[seq.name[1]]
x = sprite.x + mx * sprite.range
y = sprite.y + my * sprite.range
ret = []
for s in self.sprites:
spr = self.sprites[s]
if spr == sprite:
# Don't hit self.
continue
if spr.seq is not None:
hardbox = spr.seq.frames[spr.frame].hardbox
elif spr.pseq is not None:
hardbox = spr.pseq.frames[spr.pframe].hardbox
else:
assert spr.brain == TEXTBRAIN
continue
r = sprite.range / 2
if spr.x + hardbox[0] >= x + r:
continue
if spr.y + hardbox[1] >= y + r:
continue
if spr.x + hardbox[2] < x - r:
continue
if spr.y + hardbox[3] < y - r:
continue
ret.append (spr)
return ret
def update (self):
'''This is a generator to periodically update the screen.'''
while True:
# Wait some time before being called again. Do this at the start, so continue can be used.
yield ('wait', -50)
if self.data.the_globals['update_status'] != 0:
self.update_stats ()
if self.fade[0] != 0:
ticks = ((self.data.current_time - self.fade[2]) / 1000).microseconds
self.fade = (max (0, self.fade[0] - ticks), self.fade[1], self.data.current_time)
if self.fade[0] == 0:
for b in self.fade_block:
self.events += ((self.data.current_time, b[0], b[1]),)
self.fade_block = []
spr = self.sprites.keys ()
spr.sort (key = lambda s: (self.sprites[s].y - self.sprites[s].que))
if not self.stopped:
if self.bow[0]:
self.sprites[1].seq = None
self.sprites[1].pseq = self.data.data.seq.get_dir_seq (self.bow[3], self.dir)
ms = ((self.current_time - self.bow[1]) / 1000).microseconds
if ms >= 1000:
self.sprites[1].pframe = len (self.sprites[1].pseq.frames) - 1
else:
self.sprites[1].pframe = 1 + ms * (len (self.sprites[1].pseq.frames) - 1) / 1000
for s in spr:
if s not in self.sprites or self.sprites[s].nodraw:
continue
# Change frame.
self.animate (self.sprites[s])
if self.touch_delay:
self.touch_delay -= 1
if self.fade[:2] == (0, False):
self.data.gc.set_foreground (self.data.data.colors[0])
self.data.buffer.draw_rectangle (self.data.gc, True, 0, 0, self.data.winw, self.data.winh)
else:
self.data.buffer.draw_drawable (self.data.gc, self.bg, 0, 0, 0, 0, self.data.winw, self.data.winh)
if self.enable_sprites and self.fade[:2] != (0, False):
for s in spr:
if s not in self.sprites or self.sprites[s].nodraw or self.sprites[s].brain == TEXTBRAIN:
continue
self.draw_sprite (self.data.buffer, self.sprites[s])
if self.fade[:2] != (0, True):
if self.fade[0] != 0:
color = self.fade[0] * 255 / 500
if not self.fade[1]:
color = 255 - color
self.data.fade_pixbuf.fill (color)
self.data.buffer.draw_pixbuf (self.data.gc, self.data.fade_pixbuf, 0, 0, 0, 0)
for s in spr:
if s not in self.sprites or self.sprites[s].nodraw or self.sprites[s].brain != TEXTBRAIN:
continue
self.draw_textsprite (self.data.buffer, self.sprites[s])
if self.choice != None:
# Compute arrow position.
y = self.choice_title[2] + self.choice_title[4] + 30 + 5
for i in self.choice[:self.choice_current]:
y += i[3] + 5
y += self.choice[self.choice_current][3] / 2
self.choice_sprites[-1].y = y
self.choice_sprites[-2].y = y
for s in self.choice_sprites:
self.animate (s)
self.draw_sprite (self.data.buffer, s)
self.data.buffer.draw_layout (self.data.gc, self.choice_title[1], self.choice_title[2], self.choice_title[3], self.data.data.colors[-1], None)
y = self.choice_title[2] + self.choice_title[4] + 30
for n, i in enumerate (self.choice):
self.data.buffer.draw_layout (self.data.gc, i[2], y, i[4], self.data.data.colors[-1 if n == self.choice_current else -2], None)
y += i[3] + 5
self.data.expose (self, (0, 0, self.data.winw, self.data.winh))
def animate (self, sprite):
if sprite.brain == RESIZEBRAIN:
if ((self.data.current_time - sprite.last_time) / 1000).microseconds < 100:
return
if sprite.size == sprite.brain_parm:
sprite.kill ()
return
if sprite.size < sprite.brain_parm:
sprite.size = min (sprite.size + 10, sprite.brain_parm)
else:
sprite.size = max (sprite.size - 10, sprite.brain_parm)
return
if sprite.brain in (REPEATBRAIN, MARKBRAIN, PLAYBRAIN, FLAREBRAIN, MISSILEBRAIN) and sprite.seq is None:
sprite.seq = sprite.pseq
sprite.frame = 1
while sprite.seq != None:
if sprite.frame_delay is not None:
delay = sprite.frame_delay
else:
if sprite.frame >= len (sprite.seq.frames):
delay = 1
else:
delay = sprite.seq.frames[sprite.frame].delay
# Divide by 1000, so what's called microseconds is really milliseconds.
time = (self.data.current_time - sprite.last_time) / 1000
# Assume times to be smaller than 1000 s. Speed is more important than this obscure use case.
if time.microseconds < delay:
break
sprite.last_time += datetime.timedelta (microseconds = delay) * 1000
if sprite.frame + 1 < len (sprite.seq.frames):
sprite.frame += 1
else:
# This is reached if an animation has reached its last frame.
if self.warp_wait == sprite:
# We are waiting for this sequence to complete before warping.
# The warp is triggered from fade_block, so we only have to fade the screen.
self.fade = 500, False, self.data.current_time
if sprite.brain == MARKBRAIN:
self.draw_sprite (self.bg, sprite)
sprite.kill ()
continue
elif sprite.brain in (PLAYBRAIN, FLAREBRAIN):
sprite.kill ()
continue
elif sprite.mx != 0 or sprite.my != 0 or (sprite.brain < len (gtkdink.dink.brains) and sprite.brain != NONEBRAIN):
# If nocontrol is set, we are waiting for the animation to finish. This happened now.
if sprite.nocontrol:
sprite.nocontrol = False
sprite.frame = 1
if sprite.brain == DINKBRAIN and not sprite.frozen:
self.compute_dir ()
else:
sprite.set_state ('idle')
elif sprite.state != 'idle' or sprite.base_idle != '' or sprite.mx != 0 or sprite.my != 0 or sprite.brain == REPEATBRAIN:
# If idle without a seq, just freeze the walk seq by not returning to 1.
sprite.set_state ('idle') # reset idle sequence.
sprite.frame = 1
else:
# Force current state to be the final frame of the animation.
sprite.pseq = sprite.seq
sprite.pframe = sprite.frame
sprite.seq = None
if sprite.seq and sprite.seq.frames[sprite.frame].special:
# Hit things.
targets = [x for x in self.hit_list (sprite, sprite.seq) if not x.nohit]
for target in targets:
# Hit this sprite.
if target.hitpoints > 0:
if sprite.brain in (DINKBRAIN, POINTERBRAIN):
self.damage (self.data.the_globals['strength'], target, sprite)
else:
self.damage (sprite.strength, target, sprite)
# Call script.
target.the_statics['enemy_sprite'] = sprite.num
target.the_statics['missile_source'] = 1
self.data.run_script (target.script, 'hit', (), target)
def make_layout (self, text, width):
layout = self.data.create_pango_layout (text)
attrs = pango.AttrList ()
attrs.insert (pango.AttrWeight (pango.WEIGHT_BOLD, 0, len (text)))
layout.set_attributes (attrs)
layout.set_wrap (pango.WRAP_WORD)
layout.set_width (width * pango.SCALE)
return layout
def damage (self, strength, target, source):
self.hurt (strength / 2 + int (random.random () * strength / 2) + 1 - target.defense, target, source)
def hurt (self, dam, target, source):
if dam <= 0:
dam = random.choice ((0, 1))
if dam == 0:
return
seq, frame = (target.seq, target.frame) if target.seq is not None else (target.pseq, target.pframe)
t = self.add_text (target.x - 320, target.y + seq.frames[frame].boundingbox[1], '%d' % dam, {}, {}, -1)
t.my = -1
t.set_killdelay (1000)
t.mylimit = (0, True) # this makes the move ignore hardness.
t.have_brain = True
self.events += ((self.data.current_time, self.do_brain (t), t.num),)
if target.brain in (DINKBRAIN, POINTERBRAIN):
self.data.the_globals['life'] -= dam
death = self.data.the_globals['life'] <= 0
else:
target.hitpoints -= dam
death = target.hitpoints <= 0
if death:
if source == self.sprites[1]:
self.add_exp (target.experience, target)
# Create death sprite.
seq = None
if self.data.data.seq.find_collection (target.base_death):
seq = self.data.data.seq.get_dir_seq (target.base_death, target.dir)
else:
collection = self.data.data.seq.find_collection (target.base_walk)
if collection and 'die' in collection:
seq = collection['die']
if seq:
spr = self.add_sprite (target.x, target.y, 'mark', seq.code, 1)
spr.nohit = True
# Run die script.
self.data.run_script (target.script, 'die', (), target)
target.kill ()
def add_exp (self, amount, source):
if amount == 0:
return
self.data.the_globals['exp'] += amount
seq, frame = (source.seq, source.frame) if source.seq is not None else (source.pseq, source.pframe)
t = self.add_text (source.x - 320, source.y + seq.frames[frame].boundingbox[1] - 15, str (amount), {}, {})
t.my = -1
t.set_killdelay = (1000)
t.mylimit = (0, True)
t.have_brain = True
self.events += ((self.data.current_time, self.do_brain (t), t.num),)
def draw_textsprite (self, target, sprite, clip = True):
if sprite.owner:
offset = sprite.owner.x, sprite.owner.y
x = offset[0] + sprite.offset[0] + sprite.x - sprite.size[0] / 2
y = offset[1] + sprite.offset[1] + sprite.y - sprite.size[1]
else:
offset = 320, 0
x = offset[0] + sprite.offset[0] + sprite.x - sprite.size[0] / 2
y = offset[1] + sprite.offset[1] + sprite.y - sprite.size[1] / 2
x = x * self.data.data.scale / 50
y = y * self.data.data.scale / 50
if x < 20 * self.data.data.scale / 50:
x = 20 * self.data.data.scale / 50
if x + sprite.size[0] >= 620 * self.data.data.scale / 50:
x = 620 * self.data.data.scale / 50 - sprite.size[0]
if y < 0:
y = 0
if clip:
if y + sprite.size[1] >= 400 * self.data.data.scale / 50:
y = 400 * self.data.data.scale / 50 - sprite.size[1]
else:
if y + sprite.size[1] >= 480 * self.data.data.scale / 50:
y = 480 * self.data.data.scale / 50 - sprite.size[1]
# Draw a black shadow first, then the text.
target.draw_layout (self.data.clipgc if clip else self.data.gc, x - 1, y - 1, sprite.layout, self.data.data.colors[0], None)
target.draw_layout (self.data.clipgc if clip else self.data.gc, x, y, sprite.layout, sprite.fg, None)
return
def draw_sprite (self, target, sprite, clip = True):
if sprite.seq == None:
assert sprite.pseq != None
seq = (sprite.pseq, sprite.pframe)
else:
seq = (sprite.seq, sprite.frame)
info = seq, sprite.size, sprite.cropbox, self.data.data.scale
if sprite.cache[0] == info:
target.draw_pixbuf (self.data.clipgc if sprite.clip else None, sprite.cache[1], 0, 0, self.data.offset + (sprite.x + sprite.cache[2]) * self.data.data.scale / 50, (sprite.y + sprite.cache[3]) * self.data.data.scale / 50)
else:
sprite.bbox, sprite.cache = self.draw_frame (target, seq, (sprite.x, sprite.y), sprite.size, sprite.cropbox, sprite.clip, info)
def draw_frame (self, target, seqframe, pos, size, cropbox, clip, info = None):
seq, frame = seqframe
(x, y), bbox, box = self.data.data.get_box (size, pos, seq.frames[frame], cropbox)
left, top, right, bottom = bbox
w = (right - left) * self.data.data.scale / 50
h = (bottom - top) * self.data.data.scale / 50
if w > 0 and h > 0:
pb = self.data.data.get_seq (seq, frame)
if box != None:
pb = pb.subpixbuf (box[0] * self.data.data.scale / 50, box[1] * self.data.data.scale / 50, (box[2] - box[0]) * self.data.data.scale / 50, (box[3] - box[1]) * self.data.data.scale / 50)
if w != pb.get_width () or h != pb.get_height ():
pb = pb.scale_simple (w, h, Gdk.INTERP_BILINEAR)
target.draw_pixbuf (self.data.clipgc if clip else None, pb, 0, 0, self.data.offset + left * self.data.data.scale / 50, top * self.data.data.scale / 50)
else:
pb = 0
return bbox, (info, pb, left - pos[0], top - pos[1])
def add_sprite_hard (self, spr):
if not spr.hard or spr.brain == TEXTBRAIN:
return
if spr.seq == None:
assert spr.pseq != None
seq = (spr.pseq, spr.pframe)
else:
seq = (spr.seq, spr.frame)
box = list (seq[0].frames[seq[1]].hardbox[:])
box[0] = max (0, min (599, box[0] + spr.x - 20))
box[1] = max (0, min (399, box[1] + spr.y))
box[2] = max (0, min (599, box[2] + spr.x - 20))
box[3] = max (0, min (399, box[3] + spr.y))
if box[0] != box[2] and box[1] != box[3]:
self.hardmap[box[1]:box[3] + 1, box[0]:box[2] + 1] = (spr.editor_num if spr.editor_num is not None else -spr.num)
def make_hardmap (self):
# Add screen hardness.
self.hardmap = numpy.zeros ((400, 600), dtype = numpy.int64)
if self.data.the_globals['player_map'] in self.data.data.world.map:
screen = self.data.data.world.map[self.data.the_globals['player_map']]
hardmap = self.data.data.get_hard_tiles_PIL (screen.hard)
if hardmap is None:
for y in range (8):
for x in range (12):
tmap, tx, ty = screen.tiles[y][x]
h = numpy.array (self.data.data.get_hard_tiles_PIL (tmap))
tile = numpy.zeros ((50, 50), dtype = numpy.int64)
tile[h[ty * 50:(ty + 1) * 50, 50 * x + tx * 50:(tx + 1) * 50, 2] == 255] = 1 # Set all "blue" hardness (sets white as well, but that will be overwritten)
tile[h[ty * 50:(ty + 1) * 50, 50 * x + tx * 50:(tx + 1) * 50, 1] == 255] = 2 # Set all "white" hardness
self.hardmap[y * 50:(y + 1) * 50, x * 50:(x + 1) * 50] = tile
else:
hardmap = numpy.array (hardmap)
self.hardmap[hardmap[:, :, 2] == 255] = 1
self.hardmap[hardmap[:, :, 1] == 255] = 2
# Add background sprite hardness.
for s in screen.sprite:
if s.is_bg () and (s.hard or s.warp):
self.add_sprite_hard (Sprite (self.data, src = s, view = None))
# Add sprite hardness.
for s in self.sprites:
self.add_sprite_hard (self.sprites[s])
def launch (self):
# Launch missile with bow.
self.bow[0] = False
self.compute_dir ()
self.handle_event (self.data.current_time, self.bow[2][0], self.bow[2][1])
def attack (self):
a = False
clicking = []
for i in self.sprites:
if self.sprites[i].brain != BUTTONBRAIN or self.sprites[i].script not in self.data.scripts:
continue
if self.in_area ((self.sprites[1].x, self.sprites[1].y), self.sprites[i].bbox):
if 'click' in self.data.scripts[self.sprites[i].script]:
clicking.append (self.sprites[i])
a = True
for s in clicking:
self.data.run_script (s.script, 'click', (), s)
# Handle dink attacking.
if self.data.current_weapon > 0 and self.data.items[self.data.current_weapon] != None:
self.data.run_script (self.data.items[self.data.current_weapon][0], 'use', (), None)
else:
if not a:
self.data.run_script ('dnohit', 'main', (), None)
def in_area (self, pos, area):
return area[0] <= pos[0] <= area[2] and area[1] <= pos[1] <= area[3]
def choice_button (self, button):