-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtsapp.py
1341 lines (1050 loc) · 43.1 KB
/
tsapp.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
"""
TechSmart Graphics Library Support. (Also known as tsapp)
In particular it:
* Provides additional functionality to Python and PyGame.
Copyright (c) 2020 TechSmart Inc.
Version 1.3.2
Released on 2021-12-07
"""
#
# This library's API is highly visible.
# Please do not make API changes without discussing with the rest of the team.
#
from __future__ import division
# NOTE: Be careful when extending the list of top-level imports since it can
# noticeably delay the DPython interpreter startup time if the new
# imports are not burned into interpreter filesystem or are not
# statically linked to the interpreter.
#
# For rarely used imports consider the use of local imports instead.
import json
import pygame
import pygame.freetype
import sys
pygame.init()
try:
from typing import TYPE_CHECKING
except ImportError:
TYPE_CHECKING = False
if TYPE_CHECKING:
from typing import Any, Callable, List, Optional, Union
# ------------------------------------------------------------------------------
# Common Types
if TYPE_CHECKING:
ImageFilePath = str
ImageDescriptor = Union[ImageFilePath, "ImageSheet"]
# ------------------------------------------------------------------------------
# Check whether currently running on TS platform, used for optimization
if not hasattr(sys, 'tsk_query_ui'): # if not DPython
_query_ui = None # type: Optional[Callable]
else:
def _query_ui(command, args):
# Assumes that PyGame has been initialized
return json.loads(sys.tsk_query_ui('pygame:' + command + ':' + json.dumps(args)))
# ------------------------------------------------------------------------------
# Constants
"""
Color constants
Names and values based on standard HTML 4.01 web colors
"""
WHITE = (255, 255, 255)
SILVER = (192, 192, 192)
GRAY = (128, 128, 128)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
MAROON = (128, 0, 0)
YELLOW = (255, 255, 0)
OLIVE = (128, 128, 0)
LIME = (0, 255, 0)
GREEN = (0, 128, 0)
AQUA = (0, 255, 255)
TEAL = (0, 128, 128)
BLUE = (0, 0, 255)
NAVY = (0, 0, 128)
FUCHSIA = (255, 0, 255)
MAGENTA = FUCHSIA # Added because Fuchsia is impossible to spell correctly
PURPLE = (128, 0, 128)
# Added from "extended" color set: https://www.w3.org/wiki/CSS/Properties/color/keywords
# Note: May be worth adding full extended color names set at some point
ORANGE = (255, 165, 0)
PINK = (255, 192, 203)
GOLD = (255, 215, 0)
BROWN = (165, 42, 42)
TAN = (210, 180, 140)
CYAN = AQUA
"""
Key Constants
Matches the values from pygame to avoid unnecessary imports
"""
# TODO: How will you prevent confusion in Code Assist if you have
# to list all of these duplicated values in multiple places?
K_SPACE = pygame.K_SPACE
K_LEFT = pygame.K_LEFT
K_RIGHT = pygame.K_RIGHT
K_UP = pygame.K_UP
K_DOWN = pygame.K_DOWN
K_RETURN = pygame.K_RETURN
K_a = pygame.K_a
K_b = pygame.K_b
K_c = pygame.K_c
K_d = pygame.K_d
K_e = pygame.K_e
K_f = pygame.K_f
K_g = pygame.K_g
K_h = pygame.K_h
K_i = pygame.K_i
K_j = pygame.K_j
K_k = pygame.K_k
K_l = pygame.K_l
K_m = pygame.K_m
K_n = pygame.K_n
K_o = pygame.K_o
K_p = pygame.K_p
K_q = pygame.K_q
K_r = pygame.K_r
K_s = pygame.K_s
K_t = pygame.K_t
K_u = pygame.K_u
K_v = pygame.K_v
K_w = pygame.K_w
K_x = pygame.K_x
K_y = pygame.K_y
K_z = pygame.K_z
K_0 = pygame.K_0
K_1 = pygame.K_1
K_2 = pygame.K_2
K_3 = pygame.K_3
K_4 = pygame.K_4
K_5 = pygame.K_5
K_6 = pygame.K_6
K_7 = pygame.K_7
K_8 = pygame.K_8
K_9 = pygame.K_9
"""
Other Constants & Globals
"""
MAX_AUDIO_CHANNELS = 8 # Should never be < 8, which is the default starting value
# Caption standards are based on the US CaptionMax format for the verbose version,
# and designed to be more conversational/subtitle-like for the short version.
# Captions are the sound filename by default, but can be overwritten individually
# on each sound if desired. Captions are therefore in the following format:
# Verbose: [SPEAKER] Sound text [sound action, present tense]
# Example: [SOUND] Buzz.mp3 [stops]
# Example: [SOUND] BOOM! [plays]
# Short: Sound text with optional action
# Example: Buzz.mp3 stops
# Example: BOOM!
captions_on = False
captions_short = False
# Global current window; helpful to keep track of the currently-open window
_active_window = None
# ------------------------------------------------------------------------------
# Graphics
# Global event list; this is kept because events are
# automatically wiped after processing, so this allows querying
_current_frame_event_list = [] # type: List[Any]
class GraphicsWindow(object):
"""
A window, into which drawable objects can be added and managed.
Also maintains the event loop.
"""
def __init__(self, width=1018, height=573, background_color=WHITE):
# Private variables
self._surface = pygame.display.set_mode([width, height])
self._width = width
self._height = height
self._clock = pygame.time.Clock()
self.creation_time = pygame.time.get_ticks()
self.framerate = 30
self._draw_list = []
# Public variables
self.is_running = True
self.background_color = background_color
global _active_window
_active_window = self
# === Properties === #
@property
def width(self):
return self._width
@property
def height(self):
return self._height
@property
def center_x(self):
return int(self.width / 2)
@property
def center_y(self):
return int(self.height / 2)
@property
def center(self):
return (self.center_x, self.center_y)
# === Objects ===
def add_object(self, drawable_object):
"""
Adds a drawable object to the scene.
"""
if not isinstance(drawable_object, GraphicalObject):
raise TypeError(
str(drawable_object) + " of type " + str(type(drawable_object)) + " cannot be added to the GraphicsWindow. Requires a GraphicalObject such as Sprite or TextLabel."
)
self._draw_list.append(drawable_object)
# Note: instead of "remove_object", use
# GraphicalObject.destroy() to remove an object
# === Layers ===
def move_forward(self, drawable_object):
# NOTE: Would prefer to use list.find, but this does not
# seem to be available in Python 2.X
if drawable_object not in self._draw_list:
raise ValueError(
"Cannot change the layer of an object that has not been added to graphics window" # noqa: E501
)
else:
position = self._draw_list.index(drawable_object)
if position == len(self._draw_list) - 1:
return
# Otherwise, swap positions with object above
new_position = position + 1
swap = self._draw_list[position]
self._draw_list[position] = self._draw_list[new_position]
self._draw_list[new_position] = swap
def move_to_front(self, drawable_object):
if drawable_object not in self._draw_list:
raise ValueError(
"Cannot change the layer of an object that has not been added to graphics window" # noqa: E501
)
self._draw_list.remove(drawable_object)
self._draw_list.append(drawable_object)
def move_backward(self, drawable_object):
if drawable_object not in self._draw_list:
raise ValueError(
"Cannot change the layer of an object that has not been added to graphics window" # noqa: E501
)
else:
position = self._draw_list.index(drawable_object)
if position == 0:
return
new_position = position - 1
swap = self._draw_list[position]
self._draw_list[position] = self._draw_list[new_position]
self._draw_list[new_position] = swap
def move_to_back(self, drawable_object):
if drawable_object not in self._draw_list:
raise ValueError(
"Cannot change the layer of an object that has not been added to graphics window" # noqa: E501
)
self._draw_list.remove(drawable_object)
self._draw_list.insert(0, drawable_object)
# Gets layer number (index in draw list; 0 is back layer)
def get_layer(self, drawable_object):
if drawable_object not in self._draw_list:
raise ValueError(
"Cannot change the layer of an object that has not been added to graphics window" # noqa: E501
)
else:
return self._draw_list.index(drawable_object)
# Setting layer puts object at the given index,
# which places it just behind the object previously
# at the named layer
# TODO: TEST THIS FUNCTION
def set_layer(self, drawable_object, layer_index):
if layer_index < 0:
raise ValueError("Layer value must be positive")
if drawable_object not in self._draw_list:
raise ValueError(
"Cannot set the layer of an object that has not been added to graphics window" # noqa: E501
)
self._draw_list.remove(drawable_object)
# If the user selects a layer beyond what is in the draw list,
# just put it on top
if layer_index >= len(self._draw_list):
self._draw_list.append(drawable_object)
else:
self._draw_list.insert(layer_index, drawable_object)
# === Event Loop Management ===
def finish_frame(self):
"""
Intended to be called once a frame while GraphicsWindow.is_running
Performs all the most common end-of-frame actions, including:
- tracking time
- updating the position and image of graphical objects
- removing destroyed objects
- flipping the screen
- checking for the "QUIT" event
"""
# Track timing
self._clock.tick(self.framerate)
# Draw frame
destroyed_items = []
self._surface.fill(self.background_color)
for drawable_item in self._draw_list:
if not drawable_item.destroyed:
drawable_item._draw()
drawable_item._update(self._clock.get_time())
if drawable_item.destroyed:
destroyed_items.append(drawable_item)
pygame.display.flip()
# Remove destroyed elements
for drawable_item in destroyed_items:
self._draw_list.remove(drawable_item)
# Capture events from the current frame
global _current_frame_event_list
_current_frame_event_list = pygame.event.get()
# Check for QUIT
for event in _current_frame_event_list:
if event.type == pygame.QUIT:
self.is_running = False
# Returns the current active GraphicsWindow instance;
# for the current active display surface, use _get_window()._surface
def _get_window():
return _active_window
class GraphicalObject(object):
"""
Abstract: Encompasses any object that can be drawn into a
Graphical Window
"""
def __init__(self):
self.visible = True
self.x_speed = 0
self.y_speed = 0
self._destroyed = False
def _draw(self):
raise NotImplementedError(
"All GraphicalObjects must have some way of drawing themselves."
)
def _update(self, delta_time):
# Update can be called on all Graphical Objects, but not every object does
# something
pass
def _get_speed(self):
return (self.x_speed, self.y_speed)
def _set_speed(self, speed_tuple):
(self.x_speed, self.y_speed) = speed_tuple
speed = property(_get_speed, _set_speed)
# === Lifecycle ===
def destroy(self):
"""Marks this graphical object for destruction."""
self._destroyed = True
@property
def destroyed(self):
return self._destroyed
class RectangularObject(GraphicalObject):
"""
A subtype of GraphicalObject
Rectangular Object is a parent class for various other types
of graphical objects that all have rectangular bounds
"""
def __init__(self, x, y, width, height):
super().__init__()
self.x = x
self.y = y
self._width = width
self._height = height
self.show_bounds = False
self.bounds_color = (50, 50, 50)
def _get_center_x(self):
return self.x + (self.width / 2)
def _set_center_x(self, center_x):
self.x = center_x - (self.width / 2)
center_x = property(_get_center_x, _set_center_x)
def _get_center_y(self):
return self.y + (self.height / 2)
def _set_center_y(self, center_y):
self.y = center_y - (self.height / 2)
center_y = property(_get_center_y, _set_center_y)
def _get_center(self):
return (self.center_x, self.center_y)
def _set_center(self, center):
(self.center_x, self.center_y) = center
center = property(_get_center, _set_center)
@property
def width(self):
return self._width
@property
def height(self):
return self._height
@property
def rect(self):
# NOTE: pygame.Rect does not support non-integer values.
return pygame.Rect(int(self.x), int(self.y), self.width, self.height)
def is_colliding_rect(self, other_rect_obj):
return self.rect.colliderect(other_rect_obj.rect)
def is_colliding_point(self, x, y):
return self.rect.collidepoint((x, y))
def _update(self, delta_time):
x_speed, y_speed = self.speed
self.x += (x_speed / 1000) * delta_time
self.y += (y_speed / 1000) * delta_time
class Sprite(RectangularObject):
"""
Represents a sprite, a persistent image on the screen
with a particular location.
Mostly identical to previous 'Sprite' class from the
'tsk' library, but with some exceptions:
- inherits from RectangularObject
- can automatically detect spritesheets for animation
- includes "get" and "set" for arrays of pixels,
allowing direct pixel manipulation
"""
def __init__(self, image_descriptor, x, y, scale=1.0):
# type: ('ImageDescriptor', float, float, float) -> None
self.image_animation_rate = (
None # <- should be done first, as it may be overwritten by _set_image
)
self._set_image(image_descriptor, init=True)
self._scale = scale # For initial scale ONLY, image is scaled using the top-left corner as the anchor point
self._angle = 0
self._flip_x = False
self._flip_y = False
super().__init__(
x,
y,
self._current_transformed_cell.get_width(),
self._current_transformed_cell.get_height(),
)
def _get_image(self):
return self._image_descriptor
def _set_image(self, image_descriptor, init=False):
# If image is already set to the current image,
# don't set it again (this avoids accidentally pausing
# animated spritesheets by resetting to the first frame
# over and over
if not init:
if self.image == image_descriptor:
return
# Figure out automatically if this should be animated
# based on the presence of a .json meta file of same name
image_file_path = image_descriptor
meta_image_path = image_file_path.split(".")[0] + ".json"
try:
with open(meta_image_path) as meta_file:
size_dict = json.load(meta_file)
row_count = size_dict["rows"]
column_count = size_dict["cols"]
image_sheet = ImageSheet(image_descriptor, row_count, column_count)
if (
self.image_animation_rate is None
): # if a previous animation rate exists, use that
self.image_animation_rate = row_count * column_count
cells = image_sheet.cells
except IOError:
cells = [pygame.image.load(image_file_path)]
if not init:
old_center = self.center
if not isinstance(image_descriptor, str):
raise ValueError(
"Expected image descriptor to be an image file path but found: %r"
% image_descriptor
)
self._image_descriptor = image_descriptor
# Change cells
self._current_cell_index = 0
self._cells = cells
self._transformed_cells = [None] * len(cells)
# Reset cell animation timing
self._time_current_cell_visible = 0
if not init:
self.center = old_center
image = property(
_get_image,
_set_image,
doc="""The static or animated image that this sprite displays.""",
)
# TODO: Test this to see if it can be used to overwrite changes to a sprite image
def reset_image(self):
self._set_image(self.image, True)
# The current image cell, before scale, flip, and rotate transformations.
@property
def _current_cell(self):
return self._cells[self._current_cell_index]
# The current image cell, after scale, flip, and rotate transformations.
@property
def _current_transformed_cell(self):
transformed_cell = self._transformed_cells[self._current_cell_index]
if transformed_cell is None: # not yet cached
cell = self._cells[self._current_cell_index]
transformed_cell = self._transform_cell(cell)
self._transformed_cells[self._current_cell_index] = transformed_cell
return transformed_cell
# Invalidates all cached transformed image cells.
# Should be called whenever any fields that affect _transform_cell() are changed.
def _invalidate_transformed_cells(self):
for i in range(len(self._transformed_cells)):
self._transformed_cells[i] = None
def _get_image_animation_rate(self):
return self._image_animation_rate
def _set_image_animation_rate(self, image_animation_rate):
if image_animation_rate is None:
time_per_cell = None
elif isinstance(image_animation_rate, (int, float)):
if image_animation_rate > 0:
time_per_cell = 1000 / image_animation_rate
elif image_animation_rate == 0:
time_per_cell = -1
else:
raise ValueError(
"Expected animation rate to be >=0 but got %r."
% image_animation_rate
)
else:
raise ValueError("Not a valid animation rate: %r" % image_animation_rate)
# Update image animation rate
self._image_animation_rate = image_animation_rate
self._time_per_cell = time_per_cell
# Reset cell animation timing
self._time_current_cell_visible = 0
image_animation_rate = property(
_get_image_animation_rate,
_set_image_animation_rate,
doc="""
The rate at which the animated sprite image advances.
Does not apply to static sprite images.
If None then 1 cell per frame (regardless of frame length),
if a double then X cells per second.
""",
)
def _transform_cell(self, cell):
transformed_cell = cell
# Scale
if self._scale != 1.0:
transformed_cell = pygame.transform.scale(
transformed_cell,
(
int(transformed_cell.get_width() * self._scale),
int(transformed_cell.get_height() * self._scale),
),
)
# Flip
if self._flip_x or self._flip_y:
transformed_cell = pygame.transform.flip(
transformed_cell, self._flip_x, self._flip_y
)
# Rotate
if self._angle != 0:
transformed_cell = pygame.transform.rotate(transformed_cell, self._angle)
return transformed_cell
@property
def width(self):
return self._current_transformed_cell.get_width()
@property
def height(self):
return self._current_transformed_cell.get_height()
# === Scale ===
def _get_scale(self):
return self._scale
def _set_scale(self, scale):
min_pixel_threshold = 1
width = self._current_cell.get_width()
height = self._current_cell.get_height()
if int(width * scale) < min_pixel_threshold:
raise ValueError("At scale " + str(scale) + " sprite image width is less than " + str(min_pixel_threshold) + " pixel")
if int(height * scale) < min_pixel_threshold:
raise ValueError("At scale " + str(scale) + " sprite image height is less than " + str(min_pixel_threshold) + " pixel")
old_center = self.center
self._scale = scale
self._invalidate_transformed_cells()
self.center = old_center
scale = property(_get_scale, _set_scale)
# === Flip ===
def _get_flip_x(self):
return self._flip_x
def _set_flip_x(self, flipped):
if self._flip_x == flipped:
return
self._flip_x = flipped
self._invalidate_transformed_cells()
flip_x = property(_get_flip_x, _set_flip_x)
def _get_flip_y(self):
return self._flip_y
def _set_flip_y(self, flipped):
if self._flip_y == flipped:
return
self._flip_y = flipped
self._invalidate_transformed_cells()
flip_y = property(_get_flip_y, _set_flip_y)
# === Angle ===
def _get_angle(self):
return self._angle
def _set_angle(self, angle):
old_center = self.center
self._angle = angle
self._invalidate_transformed_cells()
self.center = old_center
angle = property(_get_angle, _set_angle)
# === Pixels ===
# NOTE: Though colors are implemented as lists instead of tuples, which is not what students would expect,
# we expect students to change these values and update the sprite via the set_pixels method
def get_pixels(self):
active_surface = self._current_transformed_cell
# Optimization for TechSmart platform
if _query_ui:
return _query_ui('surfarray_ts_array3d', [active_surface._id])
int_array = pygame.surfarray.array2d(active_surface)
width, height = active_surface.get_size()
rgba_array = [None] * width
for x in range(width):
rgba_array[x] = [None] * height
for y in range(height):
int_color = int_array[x][y]
rgba_color = active_surface.unmap_rgb(int_color)
# Typecasting to list for return type consistency with in-platform implementation
rgba_array[x][y] = list(rgba_color)
return rgba_array
def set_pixels(self, rgba_array):
# Type & value checking of outer list
if not isinstance(rgba_array, (list, tuple)):
raise TypeError("set_pixels expects a 2D list of RGBA tuples (got " + str(type(rgba_array)) + ")")
active_surface = self._current_transformed_cell
width, height = active_surface.get_size()
if len(rgba_array) != width:
raise ValueError(
"set_pixels requires 2D list to match sprite dimensions (expected width " + str(
width) + ", got width " + str(len(rgba_array)) + ")")
# Optimization for TechSmart platform
if _query_ui:
# ABRIDGED TYPE CHECK VERSION (checks only element 0 of collections)
if len(rgba_array) > 0:
first_col = rgba_array[0]
if not isinstance(first_col, (list, tuple)):
raise TypeError(
"set_pixels expects a 2D list of RGBA tuples (got " + str(type(rgba_array)) + " of " + str(
type(first_col)) + "s)")
if len(first_col) != height:
raise ValueError(
"set_pixels requires 2D list to match sprite dimensions (expected height " + str(
height) + ", got height " + str(len(first_col)) + ")")
if len(first_col) > 0:
first_val = first_col[0]
if not isinstance(first_val, (list, tuple, pygame.Color)):
raise TypeError("set_pixels expects all color values to be RGBA tuples (got " + str(type(first_val)) + ")")
if not (3 <= len(first_val) <= 4):
raise ValueError("All color values must be in RGB or RGBA format (got " + str(first_val) + ")")
active_surface._id = _query_ui('surfarray_ts_blit_array3d', [active_surface._id, rgba_array])
return
# Int array construction
int_array = [None] * width
for x in range(width):
# Type & value checking of inner list
column = rgba_array[x]
if not isinstance(column, (list, tuple)):
raise TypeError(
"set_pixels expects a 2D list of RGBA tuples (got " + str(type(rgba_array)) + " of " + str(
type(column)) + "s)")
if len(column) != height:
raise ValueError(
"set_pixels requires 2D list to match sprite dimensions (expected height " + str(
height) + ", got height " + str(len(column)) + ")")
# Inner list construction
int_array[x] = [None] * height
for y in range(height):
rgba_color = rgba_array[x][y]
# Type & value checking of colors
if not isinstance(rgba_color, (list, tuple)):
raise TypeError("set_pixel expects all color values to be RGBA tuples (got " + str(type(rgba_color)) + ")")
if not (3 <= len(rgba_color) <= 4):
raise ValueError("All color values must be in RGB or RGBA format (got " + str(rgba_color) + ")")
for value in rgba_color:
if not isinstance(value, int) or not (0 <= value <= 255):
raise ValueError("Color values must contain only integers between 0 and 255 (got " + str(value) + ")")
# Final color construction
int_color = active_surface.map_rgb(rgba_color)
int_array[x][y] = int_color
pygame.surfarray.blit_array(active_surface, int_array)
# === Behavior ===
def _update(self, delta_time):
"""
Updates this sprite's animated image.
Parameters:
* delta_time -- The amount of time since the last call to update,
in milliseconds.
"""
super()._update(delta_time)
self._time_current_cell_visible += delta_time
# Advance cell if appropriate
if self._time_per_cell == -1:
# Cell animation is disabled
pass
elif self._time_per_cell is None:
# Time per cell is 1 frame/cell, regardless of frame duration
if len(self._cells) > 1:
self._current_cell_index += 1
if self._current_cell_index == len(self._cells):
self._current_cell_index = 0
else:
# Time per cell is X seconds/cell
time_per_cell = self._time_per_cell
# Change current cell if enough time has passed
if self._time_current_cell_visible >= time_per_cell:
(num_cells_to_advance, self._time_current_cell_visible) = divmod(
self._time_current_cell_visible, time_per_cell
)
self._current_cell_index = (
self._current_cell_index + int(num_cells_to_advance)
) % len(self._cells)
def _draw(self):
"""Draws this sprite if it is visible."""
if self.visible:
_get_window()._surface.blit(self._current_transformed_cell, [self.x, self.y])
if self.show_bounds:
pygame.draw.rect(_get_window()._surface, self.bounds_color, self.rect, width=2)
class ImageSheet(object):
"""
Represents an image file that is divided into an (m x n) grid of cells.
The cells are intended for use in an animation.
Copied wholesale from previous tsk module
"""
def __init__(self, file_path, row_count, column_count):
# type: (ImageFilePath, int, int) -> None
if not (row_count >= 1 and column_count >= 1):
raise ValueError("Expected row and column count to be >= 1.")
sheet_image = pygame.image.load(file_path)
sheet_width, sheet_height = sheet_image.get_size()
# Slice the sheet into cells
cells = []
(cell_width, cell_height) = (
sheet_width // column_count,
sheet_height // row_count,
)
for gy in range(row_count):
for gx in range(column_count):
cell = sheet_image.subsurface(
pygame.Rect(
gx * cell_width, gy * cell_height, cell_width, cell_height
)
)
cells.append(cell)
self.cells = cells
self.row_count = row_count
self.column_count = column_count
class TextLabel(RectangularObject):
"""
A text label that wraps and uses baseline position.
Can be aligned (left-aligned by default).
"""
def __init__(self, font_name, font_size, x, y, width, text="", color=BLACK):
correct_args = "; TextLabel argument order is: font_name, font_size, x, y, width, optional_text, optional_color"
if not isinstance(font_name, str):
raise TypeError("TextLabel font name must be a string" + correct_args)
if not isinstance(font_size, (int, float)) or font_size <= 0:
raise TypeError("TextLabel font size must be a positive integer or float" + correct_args)
if not isinstance(x, (int, float)) or not isinstance(y, (int, float)):
raise TypeError("TextLabel coordinate positions x and y must be integers or floats" + correct_args)
if not isinstance(width, (int, float)):
raise TypeError("TextLabel width must be an integer" + correct_args)
self._font = pygame.freetype.Font(font_name, font_size)
self._font_identifier = font_name
self._font.origin = True
self._font.fgcolor = color
self.position = (x, y)
self._width = width
self._text = str(text)
self._wrap_into_lines() # Creates self._lines list
self._align = "left"
self._set_line_spacing(1.2)
super().__init__(x, y, self.width, self.height)
self.bounds_color = self.color
def _get_text(self):
return self._text
def _set_text(self, text_string): # Setting text causes re-calculation of wrapping
self._text = str(text_string)
self._wrap_into_lines()
text = property(_get_text, _set_text)
def _get_width(self):
return self._width
def _set_width(self, new_width): # Setting width causes re-calculation of wrapping
self._width = new_width
self._wrap_into_lines()
width = property(_get_width, _set_width)
@property
def height(self):
return self._pixel_line_height * len(self._lines)
@property
def rect(self):
# NOTE: pygame.Rect does not support non-integer values for position
return pygame.Rect(int(self.x), int(self.y - self._font.get_sized_ascender()), int(self.width), int(self.height))
def _get_align(self):
return self._align
def _set_align(self, alignment):
alignment = alignment.lower()
if alignment != "right" and alignment != "left" and alignment != "center":
raise ValueError(
'Text Label alignment must be "left", "right", or "center": got "'
+ str(alignment)
+ '"'
)
else:
self._align = alignment
align = property(_get_align, _set_align)
def _get_font(self):
return self._font_identifier
def _set_font(self, font_name):
new_font = pygame.freetype.Font(
font_name, self.font_size
) # Setting font causes re-calculation of wrapping and line height
new_font.fgcolor = self.color
new_font.origin = True
self._font = new_font
self._wrap_into_lines()
self._font_identifier = font_name
font = property(_get_font, _set_font)
def _update_pixel_line_height(self):
# Test all letters in font to get line height
full_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwkxyz!?0123456789/@#$%^&*()"
self._pixel_line_height = self._font.get_rect(full_alphabet).height * self._line_spacing