-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
executable file
·511 lines (435 loc) · 19.3 KB
/
utils.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
import sys
import pygame
from pygame.locals import QUIT
from gi.repository import Gtk
import consts
OLPC_SCREEN_SIZE = (1200, 900)
EVENT_REFRESH = pygame.USEREVENT+1
EVENT_SHOW_NEXT_WORD = pygame.USEREVENT+2
EVENT_SHOW_NEXT_QUESTION = pygame.USEREVENT+3
EVENT_ANSWER_EXPIRED = pygame.USEREVENT+4
EVENT_SHOW_NEXT_PARAGRAPH = pygame.USEREVENT+5
import logging
_logger = logging.getLogger('genio-activity')
class ImageSprite(pygame.sprite.Sprite):
'''Class to create a background image'''
def __init__(self, image_file, location=(0, 0), name=None, scale=None):
'''
image_file: filepath for the image
location: tuple of x y coordinates
name: name for the sprite
scale: tuple of the new size of the image
'''
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load(image_file).convert_alpha()
if scale:
self.image = pygame.transform.scale(self.image, scale)
self.name = name
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
class BaseHelperClass(object):
'''
Helper class to locate objects on the screen based on percentage
need to improve the name of this
'''
width, height = OLPC_SCREEN_SIZE
game_state = None
def translate_percent(self, width, height):
'''translates percentages to screen positions'''
x = (width / 100.0) * self.width
y = (height / 100.0) * self.height
return x, y
def translate_percent_centered(self, width, height, rect):
'''
translates percentages to screen positions
using the sprite center as point instead of top corner
'''
x, y = self.translate_percent(width, height)
x = x - (rect.width/2.0)
y = y - (rect.height/2.0)
return x, y
#def read_file(self):
# '''Sugar functions to read data from the diary'''
# self.game_state.load()
#def write_file(self):
# '''Sugar functions to write data from the diary'''
# self.game_state.save()
class ScreenBaseClass(BaseHelperClass):
'''
Base class to draw screens it contains
helper methods for screen and click detection
'''
score_surface = None
selected_character = None
lives_sprites = pygame.sprite.Group()
menu_items = pygame.sprite.Group()
current_question = None
ANSWER_TIMEOUT = 20000
exit_button = None
sound = None
split_paragraphs = False
def __init__(self, screen):
self.screen = screen
def show_lives_text(self):
self.show_text(str('VIDAS'), self.text_font,
self.translate_percent(87, 2),
COLORS['white'])
def set_background(self):
'''Sets the background on the screen'''
background = ImageSprite(self.background_src, scale=OLPC_SCREEN_SIZE)
self.screen.blit(background.image, background.rect)
surface = pygame.Surface(OLPC_SCREEN_SIZE)
surface.blit(background.image, background.rect)
self.background = surface
return background
def run(self):
'''This method is executed to start drawing stuff on screen'''
raise NotImplementedError
def play_music(self, audio_path=None, loop=-1):
if self.background_music:
self.stop_music()
pygame.mixer.music.set_volume(0.9)
pygame.mixer.music.load(audio_path or self.background_music)
pygame.mixer.music.play(loop)
def stop_music(self):
if pygame.mixer.music.get_busy():
pygame.mixer.music.stop()
def click_callback(self):
'''This method is executed when detecting a click on items'''
raise NotImplementedError
def answer_expired(self):
self.data.loss()
self.render_lives()
self.stop_sound()
self.play_sound(consts.TIMEOUT_SOUND)
def stop_sound(self):
if self.sound:
self.sound.stop()
def play_sound(self, audio_path, loops=0):
self.sound = pygame.mixer.Sound(audio_path)
self.sound.set_volume(1.0)
self.sound.play(loops)
def hover_callback(self, x):
pass
def exit_hover(self):
pass
def update_score(self, score=None):
pos = self.translate_percent(15, 8)
score = score or self.data.score
if self.score_surface:
rect = self.score_surface.get_rect()
rect.left, rect.top = pos
self.screen.blit(self.background, pos, rect)
self.score_surface = self.show_text(str(score), self.text_font,
pos, COLORS['white'])
def render_lives(self, sprite_path, num=None):
num = num or self.data.current_lives
initial_location = self.translate_percent(85, 8)
self.lives_sprites.clear(self.screen, self.background)
self.lives_sprites.empty()
for x in range(num):
sprite = ImageSprite(sprite_path, initial_location)
self.lives_sprites.add(sprite)
initial_location = (initial_location[0] + 55, initial_location[1])
self.lives_sprites.draw(self.screen)
def render_exit_button(self):
pos = self.translate_percent(95, 93)
self.exit_button = ImageSprite('assets/img/sprites/common/exit.png', pos)
self.screen.blit(self.exit_button.image, pos)
def next_question(self):
self.current_question = self.data.get_random_question()
self.display_reading(self.current_question.get('lectura', ''))
def level_finished_message(self, message, next_screen):
surface = self.show_text_rect(message,
self.small_font, self.box_size,
self.box_pos,
COLORS['grey'], COLORS['white'],
justification=1, alpha=191,
parent_background=COLORS['yellow'],
parent_alpha=191)
pygame.display.update()
pygame.time.set_timer(EVENT_ANSWER_EXPIRED, 0)
pygame.time.wait(consts.GAME_OVER_TIME)
return next_screen(self.screen).run()
def detect_click(self):
'''Event loop to detect clicks'''
while True:
#hack para sugargame
while Gtk.events_pending():
Gtk.main_iteration()
for event in pygame.event.get():
if event.type == QUIT:
try:
pygame.quit()
sys.exit()
return
except Exception, e:
return
elif event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
clicked_sprites = [s for s in self.menu_items \
if s.rect.collidepoint(pos)]
for s in clicked_sprites:
self.click_callback(s)
break
if self.exit_button:
if self.exit_button.rect.collidepoint(pos):
try:
pygame.quit()
sys.exit()
return
except Exception, e:
return
elif event.type == pygame.MOUSEMOTION:
pos = pygame.mouse.get_pos()
clicked_sprites = [s for s in self.menu_items \
if s.rect.collidepoint(pos)]
for s in clicked_sprites:
self.hover_callback(s)
if not clicked_sprites:
self.exit_hover()
elif event.type == EVENT_REFRESH:
pygame.display.update()
elif event.type == EVENT_ANSWER_EXPIRED:
pygame.time.set_timer(EVENT_ANSWER_EXPIRED, 0)
self.answer_expired()
else:
continue
def show_text(self, text, font, pos=(0, 0), color=(255, 255, 255)):
sprite = font.render(text, 1, color)
rect = sprite.get_rect()
rect.left, rect.top = pos
self.screen.blit(sprite, rect)
return sprite
def show_text_rect(self, text, font, size, pos, color,
background, justification=0, alpha=None,
parent_background=None, parent_alpha=None,
margin=20):
rect = pygame.Rect(pos, size)
surface = self._render_textrect(text, font, rect, color,
justification=justification)
if parent_background:
parent_size = (size[0] + margin, size[1] + margin)
parent_pos = (pos[0] - (margin/2), pos[1] - (margin/2))
parent_rect = pygame.Rect(parent_pos, parent_size)
parent_surface = pygame.Surface(parent_size)
parent_surface.fill(parent_background)
parent_surface.set_alpha(parent_alpha)
surface2 = pygame.Surface(rect.size)
surface2.fill(background)
surface2.set_alpha(alpha)
self.screen.blit(self.background, parent_pos, parent_rect)
self.screen.blit(parent_surface, parent_rect)
self.screen.blit(surface2, rect)
else:
self.screen.blit(self.background, pos, rect)
self.screen.blit(surface, rect)
return surface
def _render_textrect(self, string, font, rect,
text_color, background_color=None,
justification=0, alpha=None):
"""Returns a surface containing the passed text string, reformatted
to fit within the given rect, word-wrapping as necessary. The text
will be anti-aliased.
Takes the following arguments:
string - the text you wish to render. \n begins a new line.
font - a Font object
rect - a rectstyle giving the size of the surface requested.
text_color - a three-byte tuple of the rgb value of the
text color. ex (0, 0, 0) = BLACK
background_color - a three-byte tuple of the rgb value of the surface.
justification - 0 (default) left-justified
1 horizontally centered
2 right-justified
Returns the following values:
Success - a surface object with the text rendered onto it.
Failure - raises a TextRectException if the text won't fit onto the surface.
"""
final_lines = []
requested_lines = string.splitlines()
# Create a series of lines that will fit on the provided
# rectangle.
for requested_line in requested_lines:
if font.size(requested_line)[0] > rect.width:
words = requested_line.split(' ')
# if any of our words are too long to fit, return.
for word in words:
if font.size(word)[0] >= rect.width:
raise Exception("The word " + word + " is too long to fit in the rect passed.")
# Start a new line
accumulated_line = ""
for word in words:
test_line = accumulated_line + word + " "
# Build the line while the words fit.
if font.size(test_line)[0] < rect.width:
accumulated_line = test_line
else:
final_lines.append(accumulated_line)
accumulated_line = word + " "
final_lines.append(accumulated_line)
else:
final_lines.append(requested_line)
# Let's try to write the text out on the surface.
if background_color:
surface = pygame.Surface(rect.size)
surface.fill(background_color)
if alpha:
surface.set_alpha(alpha)
else:
surface = pygame.Surface(rect.size, pygame.SRCALPHA, 32)
accumulated_height = 0
for line in final_lines:
if accumulated_height + font.size(line)[1] >= rect.height:
raise Exception("Once word-wrapped, the text string was too tall to fit in the rect.")
if line != "":
tempsurface = font.render(line, 1, text_color)
if justification == 0:
surface.blit(tempsurface, (0, accumulated_height))
elif justification == 1:
surface.blit(tempsurface, ((rect.width - tempsurface.get_width()) / 2, accumulated_height))
elif justification == 2:
surface.blit(tempsurface, (rect.width - tempsurface.get_width(), accumulated_height))
else:
raise Exception("Invalid justification argument: " + str(justification))
accumulated_height += font.size(line)[1]
return surface
def display_reading(self, reading):
#aca set timer
pygame.time.set_timer(EVENT_REFRESH, 1000)
def inner(message):
surface = self.show_text_rect(message,
self.small_font, self.box_size,
self.box_pos,
COLORS['grey'], COLORS['white'],
justification=1, alpha=191,
parent_background=COLORS['yellow'],
parent_alpha=191)
pygame.display.update()
if self.split_paragraphs:
paragraphs = reading.split('\n\n')
else:
paragraphs = [reading]
words = paragraphs.pop(0).split(' ')
text_buffer= words.pop(0)
inner(text_buffer)
time_to_wait = int(self.seconds_per_word * 600)
pygame.time.set_timer(EVENT_SHOW_NEXT_WORD, time_to_wait)
while True:
while Gtk.events_pending():
Gtk.main_iteration()
for event in pygame.event.get():
if event.type == QUIT:
try:
pygame.quit()
except:
pass
sys.exit()
break
if event.type == EVENT_SHOW_NEXT_PARAGRAPH:
words = paragraphs.pop(0).split(' ')
text_buffer = ''
pygame.time.set_timer(EVENT_SHOW_NEXT_PARAGRAPH, 0)
pygame.time.set_timer(EVENT_SHOW_NEXT_WORD, time_to_wait)
if event.type == EVENT_SHOW_NEXT_WORD:
if words:
text_buffer = '%s %s' % (text_buffer, words.pop(0))
inner(text_buffer)
else:
pygame.time.set_timer(EVENT_SHOW_NEXT_WORD, 0)
if len(paragraphs):
pygame.time.set_timer(EVENT_SHOW_NEXT_PARAGRAPH, 1500)
else:
pygame.time.set_timer(EVENT_SHOW_NEXT_QUESTION, time_to_wait * 2)
if event.type == EVENT_SHOW_NEXT_QUESTION:
pygame.time.set_timer(EVENT_SHOW_NEXT_QUESTION, 0)
pygame.time.wait(3000)
self.display_question(self.current_question.get('pregunta'))
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
if self.exit_button:
if self.exit_button.rect.collidepoint(pos):
try:
pygame.quit()
sys.exit()
return
except Exception, e:
return
def display_question(self, question, sprite_dict, pos):
surface = self.show_text_rect(question,
self.small_font, self.box_size,
self.box_pos,
COLORS['grey'], COLORS['white'],
justification=1, alpha=191,
parent_background=COLORS['yellow'],
parent_alpha=191)
#agregar sprites de opcion de menu
#pos = self.translate_percent(30, 40)
for i, option in enumerate(self.current_question.get('opciones')):
checkbox = ImageSprite(sprite_dict['checkbox'], pos, name=str(i))
self.menu_items.add(checkbox)
self.screen.blit(checkbox.image, checkbox.rect)
text_pos = (pos[0]+40, pos[1]-3)
#separamos texto largote
if len(option) > self.max_question_chars:
lines = []
new_option = ''
tmp_len = len(new_option)
for word in option.split(' '):
tmp_len = len(new_option)
if (tmp_len + len(word) + 1) < self.max_question_chars:
new_option += ' ' + word
else:
lines.append(new_option)
new_option = word
lines.append(new_option)
for line in lines:
self.show_text(line, self.small_font, text_pos, COLORS['grey'])
pos = (pos[0], pos[1] + 30)
text_pos = (pos[0]+40, pos[1]-3)
else:
self.show_text(option, self.small_font, text_pos, COLORS['grey'])
pos = (pos[0], pos[1] + 60)
pygame.display.update()
pygame.time.set_timer(EVENT_ANSWER_EXPIRED, self.ANSWER_TIMEOUT)
self.play_sound(consts.CLOCK_SOUND, -1)
self.detect_click()
CURSOR = (
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ",
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ",
"XXX.........................XXXX",
"XXX..........................XXX",
"XXX..........................XXX",
"XXX.........................XXXX",
"XXX.......XXXXXXXXXXXXXXXXXXXXX ",
"XXX........XXXXXXXXXXXXXXXXXXX ",
"XXX.........XXX ",
"XXX..........XXX ",
"XXX...........XXX ",
"XXX....X.......XXX ",
"XXX....XX.......XXX ",
"XXX....XXX.......XXX ",
"XXX....XXXX.......XXX ",
"XXX....XXXXX.......XXX ",
"XXX....XXXXXX.......XXX ",
"XXX....XXX XXX.......XXX ",
"XXX....XXX XXX.......XXX ",
"XXX....XXX XXX.......XXX ",
"XXX....XXX XXX.......XXX ",
"XXX....XXX XXX.......XXX ",
"XXX....XXX XXX.......XXX ",
"XXX....XXX XXX.......XXX ",
"XXX....XXX XXX.......XXX ",
"XXX....XXX XXX.......XXX",
"XXX....XXX XXX......XXX",
"XXX....XXX XXX.....XXX",
"XXX....XXX XXX...XXXX",
" XXX..XXX XXXXXXXX ",
" XXXXXX XXXXXX ",
" XXXX XXXX "
)
COLORS = {
'white': (255, 255, 255),
'black': (0, 0, 0),
'grey': (130, 130, 130),
'yellow': (252, 185, 24),
}