-
Notifications
You must be signed in to change notification settings - Fork 0
/
pynscr_pygame.py
executable file
·875 lines (598 loc) · 25 KB
/
pynscr_pygame.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pynscr_pygame.py
#
# Copyright 2011,2012 Mark Kolloros <uvthenfuv@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
from __future__ import division, print_function, unicode_literals
import sys
import os
import pygame
import itertools
import matrix
import pool
import images
import onscr_interpreter
SCRIPT_NAME = "0.txt"
CLICK_BUTTON = 1
RBUTTON = 3
SKIP_KEY = pygame.K_s
FULLSCREEN_KEY = pygame.K_f
# View
RESOLUTION = (640, 480)
BORDER_WIDTH_MULTIPLIER = 0.8
DIR_FONT = "default.ttf"
FONT_SIZE = 17
OUTLINE_COLOR = b"#000000"
TEXT_COLOR = b"#ffffff"
# etc
DEBUG_MODE = False
class TextlessInterpreter(onscr_interpreter.VarKeeper):
MAX_FPS = 60
VIEW_UPDATE_FREQ = 1
def __init__(self, filename):
super(TextlessInterpreter, self).__init__(filename)
# graphics
self.bg = pygame.Surface(self.resolution)
self.standing_pictures = dict() # valid keys are: 'l', 'c' and 'r'
self.sprites = dict() # valid keys are numbers in the range 0-999
self.view_cycle = itertools.cycle( xrange(self.VIEW_UPDATE_FREQ) )
self.clock = pygame.time.Clock()
# pools
self.colors = pool.Pool(pygame.Color)
self.images = pool.Pool( images.image_loader(".") )
self.spritepool = pool.Pool( self.load_sprite )
# setup
self.running = False
self.skip_mode = False
# audio
self.wavesound = None
def set_surface(self, surface):
self._surface = surface
def run(self):
self.running = True
while self.running:
self.update()
def update(self):
if self.waiting:
if next(self.view_cycle) == 0:
self.update_view()
self.user_update()
else:
self.step()
def user_update(self):
# Events
for event in pygame.event.get():
self.check_event(event)
# Skip mode
if self.skip_mode:
self.waiting = False
def check_event(self, event):
if self.exit_event_check(event):
self.running = False
elif event.type == pygame.KEYDOWN:
if event.key in (pygame.K_SPACE, pygame.K_RETURN):
self.waiting = False
self.skip_mode = False
elif event.key == SKIP_KEY:
self.skip_mode = not self.skip_mode
elif event.key == FULLSCREEN_KEY:
self.toggle_fullscreen()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == CLICK_BUTTON:
self.waiting = False
self.skip_mode = False
def exit_event_check(self, event):
# returns True if the program should exit
# and False otherwise
if event.type == pygame.QUIT:
return True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
return True
return False
def update_view(self):
self.clock.tick(self.MAX_FPS)
self.draw_everything()
pygame.display.update()
def draw_everything(self):
# background
self._surface.blit( self.bg, (0, 0) )
# sprites
for topleft, img in self.sprites.itervalues():
self._surface.blit(img, topleft)
# standing pictures
for topleft, img in self.standing_pictures.itervalues():
self._surface.blit(img, topleft)
def localize_path(self, path):
s = self.unstr(path)
path = os.path.join( *s.split("\\") )
if DEBUG_MODE:
path = os.path.join("arc", path)
return path.lower()
def do_end(self):
self.running = False
def do_play(self, name):
name = self.unstr(name)
try:
tracknum = int(name[1:])
except ValueError:
self.error("Music track with name " + name + " not supported!")
return
namebase = "CD/Track{0:02}".format(tracknum)
tracknames = [namebase+".mp3", namebase+".ogg"]
for name in tracknames:
#~ print("Try", name)
if os.path.exists(name):
#~ print("Gotcha!")
pygame.mixer.music.load(name)
pygame.mixer.music.play(-1)
break
@onscr_interpreter.variable_loader
def do_waveloop(self, path):
self.do_wavestop()
path = self.localize_path(path)
self.wavesound = pygame.mixer.Sound(path)
self.wavesound.play(-1)
@onscr_interpreter.variable_loader
def do_wave(self, path):
self.do_wavestop()
path = self.localize_path(path)
self.wavesound = pygame.mixer.Sound(path)
self.wavesound.play()
def do_stop(self):
self.do_playstop()
self.do_wavestop()
def do_playstop(self):
pygame.mixer.music.stop()
def do_wavestop(self):
if self.wavesound != None:
self.wavesound.stop()
@onscr_interpreter.variable_loader
def do_bg(self, something, effect, *args):
self.do_cl("a")
if something in ('black', '"black"'):
self.error("Doing the ugly bg \"black\" hack due to a script error")
something = b"#000000"
if something in ('white', '"white"'):
self.error("Doing the ugly bg \"white\" hack due to a script error")
something = b"#ffffff"
if self.is_color(something):
color = self.colors[something]
self.bg.fill(color)
elif self.is_str(something):
path = self.localize_path(something)
self.bg.blit(self.images[path], (0, 0))
else:
self.error("This kind of BG is not supported currently: " + str(something) )
if len(args) > 0:
self.error("bg with superfluous arguments")
@onscr_interpreter.variable_loader
def do_ld(self, pos, description, effect):
if type(description) == int:
self.error("ld int description... {0} {1} {2}".format(pos, description, effect))
if description in self.sprites:
sprite = self.sprites[description]
else:
return
else:
sprite = self.spritepool[description]
pos = self.unstr(pos)
# precalculate sprite positions
x, y = sprite.get_size()
topleft = [ (self.resolution[0]-x)//2+1, self.resolution[1]-y ]
mod = self.resolution[0]//4
if pos == "l":
topleft[0] -= mod
elif pos == "r":
topleft[0] += mod
# add it
self.standing_pictures[pos] = (topleft, sprite)
@onscr_interpreter.variable_loader
def lsp(self, spriteno, description, x, y, opacity=255):
if opacity != 255:
e = "Sprite transparency isn't supported yet"
info = "; called with {0} {1}".format(description, opacity)
self.error(e+info)
# load sprite and add it
sprite = self.spritepool[description]
topleft = (x, y)
self.sprites[spriteno] = (topleft, sprite)
def load_sprite(self, description):
description = self.unstr(description)
alpha, path = description.split(";")
path = self.localize_path(path)
# we're not using self.images 'cause it shouldn't remember it
img = pygame.image.load(path)
if alpha == ":c":
# just the image; hurray
sprite = img
elif alpha == ":a":
# the right side of the image is an alpha mask
x, y = img.get_size()
img_x = x//2
sprite_size = (img_x, y)
sprite = pygame.Surface(sprite_size, pygame.SRCALPHA)
sprite.blit( img, (0, 0) )
alpha = pygame.surfarray.pixels_alpha(sprite)
mask_area = pygame.Rect((img_x, 0), sprite_size)
mask = img.subsurface(mask_area)
mask_array = pygame.surfarray.array2d(mask)
# set alpha to distance from (255, 255, 255)
white_surface = pygame.Surface( mask_area.size )
white_surface.fill( pygame.Color(b"#ffffff") )
full_white = pygame.surfarray.array2d(white_surface)
alpha[:] = full_white-mask_array
del alpha # otherwise we can't touch the sprite
else:
self.error("Unsupported image name: " + description)
placeholder = pygame.Surface( (200, 200) )
return placeholder
return sprite
@onscr_interpreter.variable_loader
def do_cl(self, pos, effect = None, *args):
pos = self.unstr(pos)
if pos == "a":
self.standing_pictures = {}
else:
if pos in self.standing_pictures:
del self.standing_pictures[pos]
else:
self.error("!? Asked to delete nonexistent picture.")
if len(args) > 0:
self.error("cl with superfluous arguments")
@onscr_interpreter.variable_loader
def do_csp(self, spriteno):
if spriteno == -1:
self.sprites = {}
else:
#~ del self.sprites[spriteno]
got = self.sprites.pop(spriteno, None)
if got == None:
self.error( "csp'd nonexistent sprite " + str(spriteno) )
def do_fileexist(self, var, path):
# maybe we should also load this
path = self.localize_path(path)
result = int( os.path.exists(path) )
self.error("fileexist result: " + str(result) )
self.do_mov(var, result)
def do_caption(self, s):
pygame.display.set_caption( self.unstr(s) + " (pynscr)" )
class PygameInterpreter(TextlessInterpreter):
#~ DARKENING_INC = 1
#~ DARKENING_MAX = 80
def __init__(self, filename):
super(PygameInterpreter, self).__init__(filename)
# Font
if os.path.exists(DIR_FONT):
font_name = DIR_FONT
else:
self.error( "No {0}. Falling back to pygame default font.".format(DIR_FONT) )
font_name = None # pygame default
self.font = pygame.font.Font(font_name, FONT_SIZE)
# pixel positioning
self.text_height = self.font.get_linesize()
border_width = int(self.text_height*BORDER_WIDTH_MULTIPLIER)
self.text_topleft = [border_width]*2
txt_area_size = matrix.sub( self.resolution, matrix.mul(self.text_topleft, [2, 2]) )
self.row_length = txt_area_size[0]
# text placing
self.linenumber = 0
self.remaining_row = self.row_length
self.text = []
self.text_states = []
# setup
self.clearwait = False
#~ # black filter
#~ self.darkening = 0
# buttons
self.buttons = []
# menu
self.rmenu = None
# saving
# normally this should be read in from the savenumber command
self.savenumber = 20
self.saves = dict()
def check_event(self, event):
super(PygameInterpreter, self).check_event(event)
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == RBUTTON:
self.open_rmenu()
def step(self):
if self.clearwait:
self.clear()
self.clearwait = False
super(PygameInterpreter, self).step()
def draw_everything(self):
super(PygameInterpreter, self).draw_everything()
#~ if self.waiting and self.darkening < self.DARKENING_MAX:
#~ self.darkening += self.DARKENING_INC
#~
#~ # black filter behind text
#~ black = pygame.Surface(self.resolution)
#~ black.set_alpha(self.darkening)
#~ self._surface.blit( black, (0, 0) )
# text display
for topleft, s in self.text:
text_size = self.font.size(s)
text_area = pygame.Rect(topleft, text_size)
# once in black, to outline it
outline_topleft = matrix.add(topleft, [1, 1])
text = self.font.render(s, True, self.colors[OUTLINE_COLOR])
self._surface.blit( text, outline_topleft )
# and once normally
text = self.font.render(s, True, self.colors[TEXT_COLOR])
self._surface.blit( text, topleft )
@onscr_interpreter.variable_loader
def do_rmenu(self, *args):
# definition of the right-click menu
args = (self.unstr(a) for a in args)
# (names, functionality)
self.rmenu = unpack_args(args)
def open_rmenu(self):
if self.rmenu != None:
# rmenu mode
# temporarily remove text
self.swapout_text()
choices, funcs = self.rmenu
result = self.text_menu(choices, True)
# uses internal counting
if result >= 0:
f = funcs[result]
if f == "skip":
self.skip_mode = True
elif f == "save":
self.open_save_menu()
elif f == "load":
#~ self.open_load_menu()
pass
elif f == "end":
self.do_end()
else:
self.error("Menu function not implemented yet:"+f)
# return
self.swapin_text()
def open_save_menu(self):
self.swapout_text()
# This could state data about the save
slot_name = "Slot {0}"
choices = [ slot_name.format(i) for i in xrange(self.savenumber) ]
result = self.text_menu(choices, True)
# uses internal counting
if result >= 0:
# save to the given slot
self.save_state(result)
self.swapin_text()
def open_load_menu(self):
pass
def save_state(self, slot):
pass
#~
#~ self.saves[slot] = save_data
def do_bg(self, *args, **kwargs):
super(PygameInterpreter, self).do_bg(*args, **kwargs)
self.darkening = 0
def do_text(self, s):
if " " in s and s != " ":
for part in s.partition(" "):
if part == "":
pass
else:
self.do_text(part)
else:
# words and spaces
self.add_word(s)
def swapout_text(self):
# This and swapin_text act like a stack
state = (self.text, self.linenumber, self.remaining_row)
self.clear()
self.text_states.append(state)
def swapin_text(self):
self.clear()
state = self.text_states.pop()
self.text, self.linenumber, self.remaining_row = state
def do_br(self):
# a linefeed
self._next_line()
def add_word(self, s):
needed = self.font.size(s)[0]
if needed > self.remaining_row:
self._next_line()
topleft = self.get_pixelpos(self.linenumber, self.remaining_row)
topleft = matrix.add(topleft, self.text_topleft)
self.text.append( (topleft, s) )
self.remaining_row -= needed
def _next_line(self):
self.linenumber += 1
self.remaining_row = self.row_length
def clear(self):
#~ self.text_surface.fill( self.colors[b"#000000"] )
self.linenumber = 0
self.remaining_row = self.row_length
self.text = []
def do_EOP(self):
self.waiting = True
self.clearwait = True
def do_select(self, *args):
self.do_goto( self.selection(args) )
self.clear()
def do_selgosub(self, *args):
self.do_gosub( self.selection(args) )
self.clear()
def selection(self, args):
texts, results = unpack_args(args)
# User choice
got = self.text_menu(texts)
return results[got]
def text_menu(self, choices, accept_rclick = False):
areas = []
for choice in choices:
self._next_line()
areas.append( self.render_text_with_area(choice) )
while True: # loop and a half
result = self.button_choice(areas)
# internally we count the choices from 0
if result >= 0 or accept_rclick:
break
return result
def render_text_with_area(self, text):
before_linenumber = self.linenumber
before_row = self.remaining_row
self.do_text(text)
return self.area_between_positions(before_linenumber, \
before_row, self.linenumber, self.remaining_row)
def area_between_positions(self, line_a, row_a, line_b, row_b):
# This is messy. Maybe I should refactor this.
def global_rect(topleft, width):
# They have to be global positions
return pygame.Rect( matrix.add(self.text_topleft, topleft), width )
# line_a, row_a has to be before line_b, row_b
area = []
# first line
topleft = self.get_pixelpos(line_a, row_a)
if line_a == line_b:
width = row_a-row_b
else:
width = row_a
rect = global_rect( topleft, (width, self.text_height) )
area.append(rect)
# intermediate lines
for line in xrange(line_a, line_b-1):
topleft = self.get_pixelpos(line)
size = (self.row_length, self.text_height)
rect = global_rect(topleft, size)
area.append(rect)
# final line
if line_a != line_b:
topleft = self.get_pixelpos(line_b)
size = (self.row_length-row_b, self.text_height)
rect = global_rect(topleft, size)
area.append(rect)
return area
def get_pixelpos(self, line, row = None):
if row == None:
x = 0
else:
x = self.row_length-row
y = line*self.text_height
return (x, y)
def do_btndef(self, name):
# currently we don't do anything with the name
del self.buttons[:]
def do_btn(self, num, x, y, w, h, xshift, yshift):
# Note: xshift and yshift are not implemented
self.buttons.append( (num, (x, y), (w, h)) )
def do_exbtn_d(self, s):
pass
def do_exbtn(self, sprite, btn, s):
pass
def do_btnwait(self, var, clear=True):
areas = [ [pygame.Rect(topleft, size)] for num, topleft, size in self.buttons ]
result = self.button_choice(areas)
# internally the choices are one less than the ones we return
if result >= 0:
# the user clicked on a button
result = self.buttons[result][0] # the zeroth value is the num
if clear:
del self.buttons[:]
else:
# right-click or other exit
result += 1
self.do_mov(var, result)
def do_btnwait2(self, var):
self.do_btnwait(var, clear=False)
def button_choice(self, areas):
# button mode
self.skip_mode = False
areacount = len(areas)
while True: # there's a return statement inside
for event in pygame.event.get():
if self.exit_event_check(event):
exit(0)
elif event.type == pygame.KEYDOWN:
# Hopefully pygame will keep the numbers of
# K_0, K_1, ... K_9 sequential
if pygame.K_1 <= event.key <= pygame.K_9:
# player choices are indexed from 1,
# but our area return values are indexed from 0
i = event.key-pygame.K_1
if i < areacount:
return i
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == CLICK_BUTTON:
for i in xrange( areacount ):
area = areas[i]
pos = event.pos
if is_in_area(area, pos):
return i
return -1
elif event.button == RBUTTON:
# internally we return -2 instead of -1 for right-clicking
return -2
self.update_view()
class StandaloneInterpreter(PygameInterpreter):
def __init__(self, resolution, filename):
pygame.init()
self.resolution = resolution
self.fullscreen_mode = True
self.toggle_fullscreen()
super(StandaloneInterpreter, self).__init__(filename)
def toggle_fullscreen(self):
if self.fullscreen_mode:
self.fullscreen_mode = False
self.set_surface( pygame.display.set_mode(self.resolution) )
elif pygame.display.mode_ok(self.resolution, pygame.FULLSCREEN):
self.fullscreen_mode = True
self.set_surface( pygame.display.set_mode(self.resolution, pygame.FULLSCREEN) )
else:
self.error("Can't switch to fullscreen mode!")
def is_in_area(area, pos):
for rect in area:
if rect.collidepoint(pos):
return True
return False
def unpack_args(seq):
seq = list(seq)
a = []
b = []
for i in xrange( len(seq)//2 ):
a.append( seq[(i*2)] )
b.append( seq[i*2+1] )
return a, b
def main():
if len(sys.argv) == 2:
directory = sys.argv[1]
elif len(sys.argv) == 1:
directory = os.curdir
else:
print("Usage: pynscr_pygame.py [DIRECTORY]")
exit(1)
if not os.path.exists(directory):
print("Specified directory doesn't seem to exist. Exiting.")
exit(2)
# maybe chdir isn't the best way, but right now it's not important
os.chdir(directory)
if not os.path.exists(SCRIPT_NAME):
print("No script found. Exiting.")
exit(3)
interpreter = StandaloneInterpreter(RESOLUTION, SCRIPT_NAME)
interpreter.run()
if __name__ == '__main__':
main()