/
Util.py
1199 lines (947 loc) · 43 KB
/
Util.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
__author__ = 'Tangil'
import random
import sys
import time
import pygame
import Constants
import GameData
# Time related management...
# http://www.roguebasin.com/index.php?title=A_simple_turn_scheduling_system_--_Python_implementation
class Ticker(object):
"""Adapted time for Roguelike game"""
def __init__(self):
self.ticks = 0 # current ticks--sys.maxint is 2147483647
self.schedule = {} # this is the dict of things to do {ticks: [obj1, obj2, ...], ticks+1: [...], ...}
return
def schedule_turn(self, interval, obj):
"""
Schedule the next turn for this object in {interval} time
"""
if isinstance(obj, str):
self.schedule.setdefault(self.ticks + interval, []).append(obj)
else:
self.schedule.setdefault(self.ticks + interval, []).append(obj.id)
return
def next_turn(self):
self.ticks += 1
# print("Tick {} - Future Actions: {}".format(self.ticks, self.schedule))
actions = self.schedule.pop(self.ticks, [])
for object_id in actions:
if GameData.object_exist(object_id):
GameData.game_dict[object_id].take_action()
return
def cancel_future_actions(self, obj):
"""
Used to remove the future actions of the obj - for example in kind of death
"""
if not isinstance(obj, str):
obj = obj.id
for actions in self.schedule:
actions[:] = [anobj for anobj in actions if anobj != obj]
return
# http://www.roguebasin.com/index.php?title=Markov_chains_name_generator_in_Python
# from http://www.geocities.com/anvrill/names/cc_goth.html
PLACES = ['Adara', 'Adena', 'Adrianne', 'Alarice', 'Alvita', 'Amara', 'Ambika', 'Antonia', 'Araceli', 'Balandria',
'Basha',
'Beryl', 'Bryn', 'Callia', 'Caryssa', 'Cassandra', 'Casondrah', 'Chatha', 'Ciara', 'Cynara', 'Cytheria',
'Dabria', 'Darcei',
'Deandra', 'Deirdre', 'Delores', 'Desdomna', 'Devi', 'Dominique', 'Drucilla', 'Duvessa', 'Ebony', 'Fantine',
'Fuscienne',
'Gabi', 'Gallia', 'Hanna', 'Hedda', 'Jerica', 'Jetta', 'Joby', 'Kacila', 'Kagami', 'Kala', 'Kallie', 'Keelia',
'Kerry',
'Kerry-Ann', 'Kimberly', 'Killian', 'Kory', 'Lilith', 'Lucretia', 'Lysha', 'Mercedes', 'Mia', 'Maura',
'Perdita', 'Quella',
'Riona', 'Safiya', 'Salina', 'Severin', 'Sidonia', 'Sirena', 'Solita', 'Tempest', 'Thea', 'Treva', 'Trista',
'Vala', 'Winta']
# ##############################################################################
# Markov Name model
# A random name generator, by Peter Corbett
# http://www.pick.ucam.org/~ptc24/mchain.html
# This script is hereby entered into the public domain
###############################################################################
class Mdict:
def __init__(self):
self.d = {}
def __getitem__(self, key):
if key in self.d:
return self.d[key]
else:
raise KeyError(key)
def add_key(self, prefix, suffix):
if prefix in self.d:
self.d[prefix].append(suffix)
else:
self.d[prefix] = [suffix]
def get_suffix(self, prefix):
l = self[prefix]
return random.choice(l)
class MName:
"""
A name from a Markov chain
"""
def __init__(self, chainlen=2):
"""
Building the dictionary
"""
if chainlen > 10 or chainlen < 1:
print("Chain length must be between 1 and 10, inclusive")
sys.exit(0)
self.mcd = Mdict()
oldnames = []
self.chainlen = chainlen
for l in PLACES:
l = l.strip()
oldnames.append(l)
s = " " * chainlen + l
for n in range(0, len(l)):
self.mcd.add_key(s[n:n + chainlen], s[n + chainlen])
self.mcd.add_key(s[len(l):len(l) + chainlen], "\n")
def new(self):
"""
New name from the Markov chain
"""
prefix = " " * self.chainlen
name = ""
suffix = ""
while True:
suffix = self.mcd.get_suffix(prefix)
if suffix == "\n" or len(name) > 9:
break
else:
name = name + suffix
prefix = prefix[1:] + suffix
return name.capitalize()
class Event(object):
def __init__(self, message):
# Custom message
pygame.event.post(pygame.event.Event(Constants.DISPLAY_EVENT, message=message))
class DebugEvent(object):
def __init__(self, message):
# Custom message
pygame.event.post(pygame.event.Event(Constants.DEBUG_EVENT, message=message))
# A STAR Algo
# Version 1.1
#
# Changes in 1.1:
# In order to optimize the list handling I implemented the location id (lid) attribute.
# This will make the all list serahces to become extremely more optimized.
class Path:
def __init__(self, nodes, totalCost):
self.nodes = nodes;
self.totalCost = totalCost;
def getNodes(self):
return self.nodes
def getTotalMoveCost(self):
return self.totalCost
class Node:
def __init__(self, location, mCost, lid, parent=None):
self.location = location # where is this node located
self.mCost = mCost # total move cost to reach this node
self.parent = parent # parent node
self.score = 0 # calculated score for this node
self.lid = lid # set the location id - unique for each location in the map
def __eq__(self, n):
if n.lid == self.lid:
return 1
else:
return 0
class AStar:
def __init__(self, maphandler):
self.mh = maphandler
def _getBestOpenNode(self):
bestNode = None
for n in self.on:
if not bestNode:
bestNode = n
else:
if n.score <= bestNode.score:
bestNode = n
return bestNode
def _tracePath(self, n):
nodes = [];
totalCost = n.mCost;
p = n.parent;
nodes.insert(0, n);
while 1:
if p.parent is None:
break
nodes.insert(0, p)
p = p.parent
return Path(nodes, totalCost)
def _handleNode(self, node, end):
i = self.o.index(node.lid)
self.on.pop(i)
self.o.pop(i)
self.c.append(node.lid)
nodes = self.mh.getAdjacentNodes(node, end)
for n in nodes:
if n.location == end:
# reached the destination
return n
elif n.lid in self.c:
# already in close, skip this
continue
elif n.lid in self.o:
# already in open, check if better score
i = self.o.index(n.lid)
on = self.on[i];
if n.mCost < on.mCost:
self.on.pop(i);
self.o.pop(i);
self.on.append(n);
self.o.append(n.lid);
else:
# new node, append to open list
self.on.append(n);
self.o.append(n.lid);
return None
def findPath(self, fromlocation, tolocation):
self.o = []
self.on = []
self.c = []
end = tolocation
fnode = self.mh.getNode(fromlocation)
self.on.append(fnode)
self.o.append(fnode.lid)
nextNode = fnode
while nextNode is not None:
finish = self._handleNode(nextNode, end)
if finish:
return self._tracePath(finish)
nextNode = self._getBestOpenNode()
return None
class SQ_Location:
"""A simple Square Map Location implementation"""
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, l):
"""MUST BE IMPLEMENTED"""
if l.x == self.x and l.y == self.y:
return 1
else:
return 0
class SQ_MapHandler:
"""A simple Square Map implementation"""
def __init__(self, mapdata, width, height):
self.m = mapdata
self.w = width
self.h = height
def getNode(self, location):
"""MUST BE IMPLEMENTED"""
x = location.x
y = location.y
if x < 0 or x >= self.w or y < 0 or y >= self.h:
return None
tile = self.m[(x, y)]
if tile.blocking:
return None
#d = self.m[(y*self.w)+x]
#if d == -1:
# return None
d = 1
return Node(location, d, ((y * self.w) + x));
def getAdjacentNodes(self, curnode, dest):
"""MUST BE IMPLEMENTED"""
result = []
cl = curnode.location
dl = dest
n = self._handleNode(cl.x + 1, cl.y, curnode, dl.x, dl.y)
if n: result.append(n)
n = self._handleNode(cl.x - 1, cl.y, curnode, dl.x, dl.y)
if n: result.append(n)
n = self._handleNode(cl.x, cl.y + 1, curnode, dl.x, dl.y)
if n: result.append(n)
n = self._handleNode(cl.x, cl.y - 1, curnode, dl.x, dl.y)
if n: result.append(n)
return result
def _handleNode(self, x, y, fromnode, destx, desty):
n = self.getNode(SQ_Location(x, y))
if n is not None:
dx = max(x, destx) - min(x, destx)
dy = max(y, desty) - min(y, desty)
emCost = dx + dy
n.mCost += fromnode.mCost
n.score = n.mCost + emCost
n.parent = fromnode
return n
return None
# Pyganim (pyganim.py, ver 1)
# A sprite animation module for Pygame.
#
# By Al Sweigart al@inventwithpython.com
# http://inventwithpython.com/pyganim
# Released under a "Simplified BSD" license
#
# There's a tutorial (and sample code) on how to use this library at http://inventwithpython.com/pyganim
# NOTE: This module requires Pygame to be installed to use. Download it from http://pygame.org
#
# This should be compatible with both Python 2 and Python 3. Please email any
# bug reports to Al at al@inventwithpython.com
#
# TODO: Feature idea: if the same image file is specified, re-use the Surface object. (Make this optional though.)
# setting up constants
PLAYING = 'playing'
PAUSED = 'paused'
STOPPED = 'stopped'
# These values are used in the anchor() method.
NORTHWEST = 'northwest'
NORTH = 'north'
NORTHEAST = 'northeast'
WEST = 'west'
CENTER = 'center'
EAST = 'east'
SOUTHWEST = 'southwest'
SOUTH = 'south'
SOUTHEAST = 'southeast'
class PygAnimation(object):
# A dictionary of already loaded images, indexed by filename.
loaded_image = {}
def __init__(self, frames, loop=True):
# Constructor function for the animation object. Starts off in the STOPPED state.
#
# @param frames
# A list of tuples for each frame of animation, in one of the following format:
# (image_of_frame<pygame.Surface>, duration_in_seconds<int>)
# (filename_of_image<str>, duration_in_seconds<int>)
# Note that the images and duration cannot be changed. A new PygAnimation object
# will have to be created.
# @param loop Tells the animation object to keep playing in a loop.
# _images stores the pygame.Surface objects of each frame
self._images = []
# _durations stores the durations (in seconds) of each frame.
# e.g. [1, 1, 2.5] means the first and second frames last one second,
# and the third frame lasts for two and half seconds.
self._durations = []
# _startTimes shows when each frame begins. len(self._startTimes) will
# always be one more than len(self._images), because the last number
# will be when the last frame ends, rather than when it starts.
# The values are in seconds.
# So self._startTimes[-1] tells you the length of the entire animation.
# e.g. if _durations is [1, 1, 2.5], then _startTimes will be [0, 1, 2, 4.5]
self._startTimes = None
# if the sprites are transformed, the originals are kept in _images
# and the transformed sprites are kept in _transformedImages.
self._transformedImages = []
self._state = STOPPED # The state is always either PLAYING, PAUSED, or STOPPED
self._loop = loop # If True, the animation will keep looping. If False, the animation stops after playing once.
self._rate = 1.0 # 2.0 means play the animation twice as fast, 0.5 means twice as slow
self._visibility = True # If False, then nothing is drawn when the blit() methods are called
self._playingStartTime = 0 # the time that the play() function was last called.
self._pausedStartTime = 0 # the time that the pause() function was last called.
if frames != '_copy': # ('_copy' is passed for frames by the getCopies() method)
self.numFrames = len(frames)
assert self.numFrames > 0, 'Must contain at least one frame.'
for i in range(self.numFrames):
# load each frame of animation into _images
frame = frames[i]
#assert type(frame) in (list, tuple) and len(frame) == 2 or 5, 'Frame %s has incorrect format.' % (i)
assert type(frame) in (list, tuple) and len(frame) == 5, 'Frame %s has incorrect format.' % (i)
assert type(frame[0]) in (
str, pygame.Surface), 'Frame %s image must be a string filename or a pygame.Surface' % (i)
if len(frame) == 2:
assert frame[1] > 0, 'Frame %s duration must be greater than zero.' % (i)
if type(frame[0]) == str:
if frame[0] not in PygAnimation.loaded_image.keys():
PygAnimation.loaded_image[frame[0]] = pygame.image.load(frame[0]).convert_alpha()
frame = (PygAnimation.loaded_image[frame[0]].copy(), frame[1])
else:
assert frame[2] > 0, 'Frame %s duration must be greater than zero.' % (i)
file_tile_size = frame[3]
game_tile_size = frame[4]
if type(frame[0]) == str:
if frame[0] not in PygAnimation.loaded_image.keys():
PygAnimation.loaded_image[frame[0]] = pygame.image.load(frame[0]).convert_alpha()
a_frame = PygAnimation.loaded_image[frame[0]].subsurface(frame[1], file_tile_size).copy()
frame = (pygame.transform.smoothscale(a_frame, game_tile_size), frame[2])
self._images.append(frame[0])
self._durations.append(frame[1])
self._startTimes = self._getStartTimes()
def _getStartTimes(self):
# Internal method to get the start times based off of the _durations list.
# Don't call this method.
startTimes = [0]
for i in range(self.numFrames):
startTimes.append(startTimes[-1] + self._durations[i])
return startTimes
def reverse(self):
# Reverses the order of the animations.
self.elapsed = self._startTimes[-1] - self.elapsed
self._images.reverse()
self._transformedImages.reverse()
self._durations.reverse()
def getCopy(self):
# Returns a copy of this PygAnimation object, but one that refers to the
# Surface objects of the original so it efficiently uses memory.
#
# NOTE: Messing around with the original Surface objects will affect all
# the copies. If you want to modify the Surface objects, then just make
# copies using constructor function instead.
return self.getCopies(1)[0]
def getCopies(self, numCopies=1):
# Returns a list of copies of this PygAnimation object, but one that refers to the
# Surface objects of the original so it efficiently uses memory.
#
# NOTE: Messing around with the original Surface objects will affect all
# the copies. If you want to modify the Surface objects, then just make
# copies using constructor function instead.
retval = []
for i in range(numCopies):
newAnim = PygAnimation('_copy', loop=self.loop)
newAnim._images = self._images[:]
newAnim._transformedImages = self._transformedImages[:]
newAnim._durations = self._durations[:]
newAnim._startTimes = self._startTimes[:]
newAnim.numFrames = self.numFrames
retval.append(newAnim)
return retval
def blit(self, destSurface, dest):
# Draws the appropriate frame of the animation to the destination Surface
# at the specified position.
#
# NOTE: If the visibility attribute is False, then nothing will be drawn.
#
# @param destSurface
# The Surface object to draw the frame
# @param dest
# The position to draw the frame. This is passed to Pygame's Surface's
# blit() function, so it can be either a (top, left) tuple or a Rect
# object.
if self.isFinished():
self.state = STOPPED
if not self.visibility or self.state == STOPPED:
return
frameNum = findStartTime(self._startTimes, self.elapsed)
destSurface.blit(self.getFrame(frameNum), dest)
def getFrame(self, frameNum):
# Returns the pygame.Surface object of the frameNum-th frame in this
# animation object. If there is a transformed version of the frame,
# it will return that one.
if self._transformedImages == []:
return self._images[frameNum]
else:
return self._transformedImages[frameNum]
def getCurrentFrame(self):
# Returns the pygame.Surface object of the frame that would be drawn
# if the blit() method were called right now. If there is a transformed
# version of the frame, it will return that one.
return self.getFrame(self.currentFrameNum)
def clearTransforms(self):
# Deletes all the transformed frames so that the animation object
# displays the original Surfaces/images as they were before
# transformation functions were called on them.
#
# This is handy to do for multiple transformation, where calling
# the rotation or scaling functions multiple times results in
# degraded/noisy images.
self._transformedImages = []
def makeTransformsPermanent(self):
self._images = [pygame.Surface(surfObj.get_size(), 0, surfObj) for surfObj in self._transformedImages]
for i in range(len(self._transformedImages)):
self._images[i].blit(self._transformedImages[i], (0, 0))
def blitFrameNum(self, frameNum, destSurface, dest):
# Draws the specified frame of the animation object. This ignores the
# current playing state.
#
# NOTE: If the visibility attribute is False, then nothing will be drawn.
#
# @param frameNum
# The frame to draw (the first frame is 0, not 1)
# @param destSurface
# The Surface object to draw the frame
# @param dest
# The position to draw the frame. This is passed to Pygame's Surface's
# blit() function, so it can be either a (top, left) tuple or a Rect
# object.
if self.isFinished():
self.state = STOPPED
if not self.visibility or self.state == STOPPED:
return
destSurface.blit(self.getFrame(frameNum), dest)
def blitFrameAtTime(self, elapsed, destSurface, dest):
# Draws the frame the is "elapsed" number of seconds into the animation,
# rather than the time the animation actually started playing.
#
# NOTE: If the visibility attribute is False, then nothing will be drawn.
#
# @param elapsed
# The amount of time into an animation to use when determining which
# frame to draw. blitFrameAtTime() uses this parameter rather than
# the actual time that the animation started playing. (In seconds)
# @param destSurface
# The Surface object to draw the frame
# @param dest
# The position to draw the frame. This is passed to Pygame's Surface's
# blit() function, so it can be either a (top, left) tuple or a Rect
# object. elapsed = int(elapsed * self.rate)
if self.isFinished():
self.state = STOPPED
if not self.visibility or self.state == STOPPED:
return
frameNum = findStartTime(self._startTimes, elapsed)
destSurface.blit(self.getFrame(frameNum), dest)
def isFinished(self):
# Returns True if this animation doesn't loop and has finished playing
# all the frames it has.
return not self.loop and self.elapsed >= self._startTimes[-1]
def play(self, startTime=None):
# Start playing the animation.
# play() is essentially a setter function for self._state
# NOTE: Don't adjust the self.state property, only self._state
if startTime is None:
startTime = time.time()
if self._state == PLAYING:
if self.isFinished():
# if the animation doesn't loop and has already finished, then
# calling play() causes it to replay from the beginning.
self._playingStartTime = startTime
elif self._state == STOPPED:
# if animation was stopped, start playing from the beginning
self._playingStartTime = startTime
elif self._state == PAUSED:
# if animation was paused, start playing from where it was paused
self._playingStartTime = startTime - (self._pausedStartTime - self._playingStartTime)
self._state = PLAYING
def pause(self, startTime=None):
# Stop having the animation progress, and keep it at the current frame.
# pause() is essentially a setter function for self._state
# NOTE: Don't adjust the self.state property, only self._state
if startTime is None:
startTime = time.time()
if self._state == PAUSED:
return # do nothing
elif self._state == PLAYING:
self._pausedStartTime = startTime
elif self._state == STOPPED:
rightNow = time.time()
self._playingStartTime = rightNow
self._pausedStartTime = rightNow
self._state = PAUSED
def stop(self):
# Reset the animation to the beginning frame, and do not continue playing
# stop() is essentially a setter function for self._state
# NOTE: Don't adjust the self.state property, only self._state
if self._state == STOPPED:
return # do nothing
self._state = STOPPED
def togglePause(self):
# If paused, start playing. If playing, then pause.
# togglePause() is essentially a setter function for self._state
# NOTE: Don't adjust the self.state property, only self._state
if self._state == PLAYING:
if self.isFinished():
# the one exception: if this animation doesn't loop and it
# has finished playing, then toggling the pause will cause
# the animation to replay from the beginning.
#self._playingStartTime = time.time() # effectively the same as calling play()
self.play()
else:
self.pause()
elif self._state in (PAUSED, STOPPED):
self.play()
def areFramesSameSize(self):
# Returns True if all the Surface objects in this animation object
# have the same width and height. Otherwise, returns False
width, height = self.getFrame(0).get_size()
for i in range(len(self._images)):
if self.getFrame(i).get_size() != (width, height):
return False
return True
def getMaxSize(self):
# Goes through all the Surface objects in this animation object
# and returns the max width and max height that it finds. (These
# widths and heights may be on different Surface objects.)
frameWidths = []
frameHeights = []
for i in range(len(self._images)):
frameWidth, frameHeight = self._images[i].get_size()
frameWidths.append(frameWidth)
frameHeights.append(frameHeight)
maxWidth = max(frameWidths)
maxHeight = max(frameHeights)
return (maxWidth, maxHeight)
def getRect(self):
# Returns a pygame.Rect object for this animation object.
# The top and left will be set to 0, 0, and the width and height
# will be set to what is returned by getMaxSize().
maxWidth, maxHeight = self.getMaxSize()
return pygame.Rect(0, 0, maxWidth, maxHeight)
def anchor(self, anchorPoint=NORTHWEST):
# If the Surface objects are of different sizes, align them all to a
# specific "anchor point" (one of the NORTH, SOUTH, SOUTHEAST, etc. constants)
#
# By default, they are all anchored to the NORTHWEST corner.
if self.areFramesSameSize():
return # nothing needs to be anchored
# This check also prevents additional calls to anchor() from doing
# anything, since anchor() sets all the image to the same size.
# The lesson is, you can only effectively call anchor() once.
self.clearTransforms() # clears transforms since this method anchors the original images.
maxWidth, maxHeight = self.getMaxSize()
halfMaxWidth = int(maxWidth / 2)
halfMaxHeight = int(maxHeight / 2)
for i in range(len(self._images)):
# go through and copy all frames to a max-sized Surface object
# NOTE: This makes changes to the original images in self._images, not the transformed images in self._transformedImages
newSurf = pygame.Surface(
(maxWidth, maxHeight)) # TODO: this is probably going to have errors since I'm using the default depth.
# set the expanded areas to be transparent
newSurf = newSurf.convert_alpha()
newSurf.fill((0, 0, 0, 0))
frameWidth, frameHeight = self._images[i].get_size()
halfFrameWidth = int(frameWidth / 2)
halfFrameHeight = int(frameHeight / 2)
# position the Surface objects to the specified anchor point
if anchorPoint == NORTHWEST:
newSurf.blit(self._images[i], (0, 0))
elif anchorPoint == NORTH:
newSurf.blit(self._images[i], (halfMaxWidth - halfFrameWidth, 0))
elif anchorPoint == NORTHEAST:
newSurf.blit(self._images[i], (maxWidth - frameWidth, 0))
elif anchorPoint == WEST:
newSurf.blit(self._images[i], (0, halfMaxHeight - halfFrameHeight))
elif anchorPoint == CENTER:
newSurf.blit(self._images[i], (halfMaxWidth - halfFrameWidth, halfMaxHeight - halfFrameHeight))
elif anchorPoint == EAST:
newSurf.blit(self._images[i], (maxWidth - frameWidth, halfMaxHeight - halfFrameHeight))
elif anchorPoint == SOUTHWEST:
newSurf.blit(self._images[i], (0, maxHeight - frameHeight))
elif anchorPoint == SOUTH:
newSurf.blit(self._images[i], (halfMaxWidth - halfFrameWidth, maxHeight - frameHeight))
elif anchorPoint == SOUTHEAST:
newSurf.blit(self._images[i], (maxWidth - frameWidth, maxHeight - frameHeight))
self._images[i] = newSurf
def nextFrame(self, jump=1):
# Set the elapsed time to the beginning of the next frame.
# You can jump ahead by multiple frames by specifying a different
# argument for jump.
# Negative values have the same effect as calling prevFrame()
self.currentFrameNum += int(jump)
def prevFrame(self, jump=1):
# Set the elapsed time to the beginning of the previous frame.
# You can jump ahead by multiple frames by specifying a different
# argument for jump.
# Negative values have the same effect as calling nextFrame()
self.currentFrameNum -= int(jump)
def rewind(self, seconds=None):
# Set the elapsed time back relative to the current elapsed time.
if seconds is None:
self.elapsed = 0.0
else:
self.elapsed -= seconds
def fastForward(self, seconds=None):
# Set the elapsed time forward relative to the current elapsed time.
if seconds is None:
self.elapsed = self._startTimes[-1] - 0.00002 # done to compensate for rounding errors
else:
self.elapsed += seconds
def _makeTransformedSurfacesIfNeeded(self):
# Internal-method. Creates the Surface objects for the _transformedImages list.
# Don't call this method.
if self._transformedImages == []:
self._transformedImages = [surf.copy() for surf in self._images]
# Transformation methods.
# (These are analogous to the pygame.transform.* functions, except they
# are applied to all frames of the animation object.
def flip(self, xbool, ybool):
# Flips the image horizontally, vertically, or both.
# See http://pygame.org/docs/ref/transform.html#pygame.transform.flip
self._makeTransformedSurfacesIfNeeded()
for i in range(len(self._images)):
self._transformedImages[i] = pygame.transform.flip(self.getFrame(i), xbool, ybool)
def scale(self, width_height):
# NOTE: Does not support the DestSurface parameter
# Increases or decreases the size of the images.
# See http://pygame.org/docs/ref/transform.html#pygame.transform.scale
self._makeTransformedSurfacesIfNeeded()
for i in range(len(self._images)):
self._transformedImages[i] = pygame.transform.scale(self.getFrame(i), width_height)
def rotate(self, angle):
# Rotates the image.
# See http://pygame.org/docs/ref/transform.html#pygame.transform.rotate
self._makeTransformedSurfacesIfNeeded()
for i in range(len(self._images)):
self._transformedImages[i] = pygame.transform.rotate(self.getFrame(i), angle)
def rotozoom(self, angle, scale):
# Rotates and scales the image simultaneously.
# See http://pygame.org/docs/ref/transform.html#pygame.transform.rotozoom
self._makeTransformedSurfacesIfNeeded()
for i in range(len(self._images)):
self._transformedImages[i] = pygame.transform.rotozoom(self.getFrame(i), angle, scale)
def scale2x(self):
# NOTE: Does not support the DestSurface parameter
# Double the size of the image using an efficient algorithm.
# See http://pygame.org/docs/ref/transform.html#pygame.transform.scale2x
self._makeTransformedSurfacesIfNeeded()
for i in range(len(self._images)):
self._transformedImages[i] = pygame.transform.scale2x(self.getFrame(i))
def smoothscale(self, width_height):
# NOTE: Does not support the DestSurface parameter
# Scales the image smoothly. (Computationally more expensive and
# slower but produces a better scaled image.)
# See http://pygame.org/docs/ref/transform.html#pygame.transform.smoothscale
self._makeTransformedSurfacesIfNeeded()
for i in range(len(self._images)):
self._transformedImages[i] = pygame.transform.smoothscale(self.getFrame(i), width_height)
# pygame.Surface method wrappers
# These wrappers call their analogous pygame.Surface methods on all Surface objects in this animation.
# They are here for the convenience of the module user. These calls will apply to the transform images,
# and can have their effects undone by called clearTransforms()
#
# It is not advisable to call these methods on the individual Surface objects in self._images.
def _surfaceMethodWrapper(self, wrappedMethodName, *args, **kwargs):
self._makeTransformedSurfacesIfNeeded()
for i in range(len(self._images)):
methodToCall = getattr(self._transformedImages[i], wrappedMethodName)
methodToCall(*args, **kwargs)
# There's probably a more terse way to generate the following methods,
# but I don't want to make the code even more unreadable.
def convert(self, *args, **kwargs):
# See http://pygame.org/docs/ref/surface.html#Surface.convert
self._surfaceMethodWrapper('convert', *args, **kwargs)
def convert_alpha(self, *args, **kwargs):
# See http://pygame.org/docs/ref/surface.html#Surface.convert_alpha
self._surfaceMethodWrapper('convert_alpha', *args, **kwargs)
def set_alpha(self, *args, **kwargs):
# See http://pygame.org/docs/ref/surface.html#Surface.set_alpha
self._surfaceMethodWrapper('set_alpha', *args, **kwargs)
def scroll(self, *args, **kwargs):
# See http://pygame.org/docs/ref/surface.html#Surface.scroll
self._surfaceMethodWrapper('scroll', *args, **kwargs)
def set_clip(self, *args, **kwargs):
# See http://pygame.org/docs/ref/surface.html#Surface.set_clip
self._surfaceMethodWrapper('set_clip', *args, **kwargs)
def set_colorkey(self, *args, **kwargs):
# See http://pygame.org/docs/ref/surface.html#Surface.set_colorkey
self._surfaceMethodWrapper('set_colorkey', *args, **kwargs)
def lock(self, *args, **kwargs):
# See http://pygame.org/docs/ref/surface.html#Surface.unlock
self._surfaceMethodWrapper('lock', *args, **kwargs)
def unlock(self, *args, **kwargs):
# See http://pygame.org/docs/ref/surface.html#Surface.lock
self._surfaceMethodWrapper('unlock', *args, **kwargs)
# Getter and setter methods for properties
def _propGetRate(self):
return self._rate
def _propSetRate(self, rate):
rate = float(rate)
if rate < 0:
raise ValueError('rate must be greater than 0.')
self._rate = rate
rate = property(_propGetRate, _propSetRate)
def _propGetLoop(self):
return self._loop
def _propSetLoop(self, loop):
if self.state == PLAYING and self._loop and not loop:
# if we are turning off looping while the animation is playing,
# we need to modify the _playingStartTime so that the rest of
# the animation will play, and then stop. (Otherwise, the
# animation will immediately stop playing if it has already looped.)
self._playingStartTime = time.time() - self.elapsed
self._loop = bool(loop)
loop = property(_propGetLoop, _propSetLoop)
def _propGetState(self):
if self.isFinished():
self._state = STOPPED # if finished playing, then set state to STOPPED.
return self._state
def _propSetState(self, state):
if state not in (PLAYING, PAUSED, STOPPED):
raise ValueError('state must be one of pyganim.PLAYING, pyganim.PAUSED, or pyganim.STOPPED')
if state == PLAYING:
self.play()
elif state == PAUSED:
self.pause()
elif state == STOPPED:
self.stop()
state = property(_propGetState, _propSetState)
def _propGetVisibility(self):
return self._visibility
def _propSetVisibility(self, visibility):
self._visibility = bool(visibility)
visibility = property(_propGetVisibility, _propSetVisibility)
def _propSetElapsed(self, elapsed):
# NOTE: Do to floating point rounding errors, this doesn't work precisely.
elapsed += 0.00001 # done to compensate for rounding errors
# TODO - I really need to find a better way to handle the floating point thing.
# Set the elapsed time to a specific value.
if self._loop:
elapsed = elapsed % self._startTimes[-1]
else:
elapsed = getInBetweenValue(0, elapsed, self._startTimes[-1])
rightNow = time.time()
self._playingStartTime = rightNow - (elapsed * self.rate)
if self.state in (PAUSED, STOPPED):
self.state = PAUSED # if stopped, then set to paused
self._pausedStartTime = rightNow
def _propGetElapsed(self):
# NOTE: Do to floating point rounding errors, this doesn't work precisely.
# To prevent infinite recursion, don't use the self.state property,
# just read/set self._state directly because the state getter calls
# this method.
# Find out how long ago the play()/pause() functions were called.
if self._state == STOPPED:
# if stopped, then just return 0
return 0
if self._state == PLAYING:
# if playing, then draw the current frame (based on when the animation
# started playing). If not looping and the animation has gone through
# all the frames already, then draw the last frame.
elapsed = (time.time() - self._playingStartTime) * self.rate
elif self._state == PAUSED:
# if paused, then draw the frame that was playing at the time the
# PygAnimation object was paused
elapsed = (self._pausedStartTime - self._playingStartTime) * self.rate
if self._loop:
elapsed = elapsed % self._startTimes[-1]
else:
elapsed = getInBetweenValue(0, elapsed, self._startTimes[-1])