summaryrefslogtreecommitdiff
path: root/game/03_init.rpy
blob: 8b31059c550da825cf55e002aa297063ae8b0c9b (plain) (blame)
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
########################################################################################
#     This file is part of Spheres.
#     Copyright (C) 2019  Jesusalva

#     This library is free software; you can redistribute it and/or
#     modify it under the terms of the GNU Lesser General Public
#     License as published by the Free Software Foundation; either
#     version 2.1 of the License, or (at your option) any later version.

#     This library 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
#     Lesser General Public License for more details.

#     You should have received a copy of the GNU Lesser General Public
#     License along with this library; if not, write to the Free Software
#     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
########################################################################################
# Definitions - Music, Graphics, and JSON data
############################################################################
init python:
    def logindata():
        global password
        # TODO: Obtain user id based on device
        return """{
                "passwd": "%s",
                "version": "%s"
                }""" % (password, config.version)


    def recruitdata(t, a):
        return """{
                "tavern": %d,
                "amount": %d,
                "packet": %d
                }""" % (t, a, now())


    def questdata(w, q, p):
        return """{
                "world": "%s",
                "quest_id": %d,
                "party_id": %d,
                "packet": %d
                }""" % (w, q, p, now())


    def battledata(u, s, a):
        return """{
                "unit": %s,
                "sphere": %s,
                "action": %s,
                "packet": %d
                }""" % (json.dumps(u), json.dumps(s), json.dumps(a), now())

    def square_composite(cid, path, ei=False):
        # We need to try to get rarity
        try:
            r=allunits[int(cid)]["rare"]
        except:
            r=4 # FIXME

        # We need to try to get the element
        try:
            e=allunits[int(cid)]["attribute"]
        except:
            e=0

        if not ei:
            return Composite(
                (340, 340),
                (0, 0), "gfx/square/bg.png",
                (0, 0), path,
                (0, 0), "gfx/square/%d.png" % r,
                (0, 0), "gfx/square/ele_%d.png" % e)
        else:
            return Composite(
                (340, 340),
                (0, 0), "gfx/square/bg.png",
                (0, 0), ExtraImage(path),
                (0, 0), "gfx/square/%d.png" % r,
                (0, 0), "gfx/square/ele_%d.png" % e)

    def card_composite(cid, path, ei=False):
        # We need to try to get rarity
        try:
            r=allunits[int(cid)]["rare"]
        except:
            r=4 # FIXME

        # We need to try to get the element
        try:
            e=allunits[int(cid)]["attribute"]
            print(str(e))
        except:
            e=0

        if not ei:
            return Composite(
            (640, 960),
            (0, 0), "gfx/cards/bg.png",
            (0, 0), path,
            (0, 0), "gfx/cards/"+str(r)+".png",
            (0, 0), "gfx/cards/ele/"+str(e)+".png")
        else:
            return Composite(
            (640, 960),
            (0, 0), "gfx/cards/bg.png",
            (0, 0), ExtraImage(path),
            (0, 0), "gfx/cards/"+str(r)+".png",
            (0, 0), "gfx/cards/ele/"+str(e)+".png")
        # size,)

    # TODO: square_ and gfx/square/units
    # Converts regular image filepaths to displayables names and vice-versa
    def img_regex(name, reverse=False):
        if not reverse:
            # Extension is ommited, add them yourself!
            if name.startswith("unit_"):
                return "gfx/units/%s" % name.replace("unit_")
            elif name.startswith("mob_"):
                return "gfx/mobs/%s" % name.replace("mob_")
            elif name.startswith("dialog_"):
                return "gfx/dialog/%s" % name.replace("dialog_")
            elif name.startswith("bg "):
                return "gfx/bg/%s" % name.replace("bg ")
            elif name.startswith("summon_"):
                return "gfx/summons/%s" % name.replace("summon_")
            else:
                print("ERROR: Not a regular filename")
                return name
        else:
            if name.startswith("gfx/units/"):
                return "unit_%s" % name
            elif name.startswith("gfx/mobs/"):
                return "mob_%s" % name
            elif name.startswith("gfx/dialog/"):
                return "dialog_%s" % name
            elif name.startswith("gfx/bg/"):
                return "bg %s" % name
            elif name.startswith("gfx/summons/"):
                return "summon_%s" % name
            else:
                print("ERROR: Not a regular display name")
                return name

    # Loads a sound called VAL
    def get_sfx(val, ext=".mp3"):
        # Search for the sound
        show_img(val, False, ext=ext)

        try:
            valb=dl_search(persistent.allfiles, 0, val)[1]
        except:
            traceback.print_exc()
            valb = ERR_INVALID
        if valb == ERR_INVALID:
            print("Invalid Sound: %s" % (val))
            return RetString("sfx/regnum.mp3").id() # FIXME
        return RetString(valb).id()


    # Load sfx (or rather, register the path)
    for file in renpy.list_files():
        fn=file.replace('sfx/','').replace('/', ' ').replace('.mp3','').replace('.ogg','')
        if file.startswith('sfx/'):
            if file.endswith('.mp3') or file.endswith('.ogg'):
                if not fn in persistent.allfiles:
                    persistent.allfiles.append((fn, file))
                allfiles.append(fn)
                continue
            continue


    # Load sprite images: "unit"
    for file in renpy.list_files():
        fn=file.replace('gfx/units/','').replace('/', ' ').replace('.png','').replace('.webp','')
        if file.startswith('gfx/units/'):
            if file.endswith('.png') or file.endswith('.webp'):
                name = "unit_"+fn
                #renpy.image(name, Image(file, yanchor=1.0))
                renpy.image(name, card_composite(fn, file))

                dl=dl_search(persistent.allfiles, 0, name)
                if dl is ERR_INVALID:
                    persistent.allfiles.append((name, file))
                allfiles.append(name)
                continue
            continue

    # Load sprite images: "mob"
    for file in renpy.list_files():
        fn=file.replace('gfx/mobs/','').replace('/', ' ').replace('.png','').replace('.webp','')
        if file.startswith('gfx/mobs/'):
            if file.endswith('.png') or file.endswith('.webp'):
                name = "mob_"+fn
                renpy.image(name, Image(file, yanchor=1.0))
                if not name in persistent.allfiles:
                    persistent.allfiles.append((name, file))
                allfiles.append(name)
                continue
            continue


    # Load sprite images: "dialog"
    for file in renpy.list_files():
        fn=file.replace('gfx/dialog/','').replace('/', ' ').replace('.png','').replace('.webp','')
        if file.startswith('gfx/dialog/'):
            if file.endswith('.png') or file.endswith('.webp'):
                name = "dialog_"+fn
                renpy.image(name, Image(file, yanchor=1.0))
                dl=dl_search(persistent.allfiles, 0, name)
                if dl is ERR_INVALID:
                    persistent.allfiles.append((name, file))
                allfiles.append(name)
                continue
            continue


    # Load background images: "bg"
    for file in renpy.list_files():
        fn=file.replace('gfx/bg/','').replace('/', ' ').replace('.png','').replace('.webp','')
        if file.startswith('gfx/bg/'):
            if file.endswith('.png') or file.endswith('.webp'):
                name = "bg "+fn
                renpy.image(name, Frame(file, 0, 0))
                dl=dl_search(persistent.allfiles, 0, name)
                if dl is ERR_INVALID:
                    persistent.allfiles.append((name, file))
                allfiles.append(name)
                continue
            continue


    # Load summon images: "summon"
    for file in renpy.list_files():
        fn=file.replace('gfx/summons/','').replace('/', ' ').replace('.png','').replace('.webp','')
        if file.startswith('gfx/summons/'):
            if file.endswith('.png') or file.endswith('.webp'):
                name = "summon_"+fn
                renpy.image(name, Image(file, yanchor=1.0))
                dl=dl_search(persistent.allfiles, 0, name)
                if dl is ERR_INVALID:
                    persistent.allfiles.append((name, file))
                allfiles.append(name)
                continue
            continue


    # Load summon images: "square"
    for file in renpy.list_files():
        fn=file.replace('gfx/square/','').replace('/', ' ').replace('.png','').replace('.webp','')
        if file.startswith('gfx/square/'):
            if file.endswith('.png') or file.endswith('.webp'):
                name = "square_"+fn
                #renpy.image(name, Image(file, yanchor=1.0))
                renpy.image(name, square_composite(fn, file))
                dl=dl_search(persistent.allfiles, 0, name)
                if dl is ERR_INVALID:
                    persistent.allfiles.append((name, file))
                allfiles.append(name)
                continue
            continue

    # TODO: Maybe load images on persistent.allfiles now?
    # I suspect declaring images at runtime might have a memleak
    # Needs investigation


    def star_write(am):
        i, st = 0, ""
        while i < am:
            i+=1
            st+="★"
        return st


    # Overrides renpy.image() method
    def new_img(name, where, isimage=True):
        # d: Downloaded path
        if not isinstance(name, tuple):
            name = tuple(name.split())

        #d = renpy.renpy.easy.displayable(where)
        if isimage:
            d=ExtraImage(where)
        else:
            d = renpy.renpy.easy.displayable(where)
        renpy.renpy.display.image.register_image(name, d)
        return

    # Retrieves Ren'Py displayable name associated to PATH
    def get_img(path):
        # Search for the image name
        val=img_regex(path, True)
        show_img(val, False)

        valb=dl_search(persistent.allfiles, 0, val)[1]
        if valb == ERR_INVALID:
            print("Invalid Image: %s (%s)" % (path, val))
            return "gfx/spinner.png"
        return valb

    # Overrides renpy.show() and renpy.image() methods
    # Missing: transient=False, munge_name=True
    # FIXME: Does not saves properly in Windows
    def show_img(img, show=True, at_list=[ ], tag=None, zorder=None, behind=[ ], atl=None, what=None, layer=None, ext=".webp"):
        global tr_loading
        # Image exists, display it
        if img in allfiles:
            if show:
                renpy.show(img, at_list=at_list, tag=tag, zorder=zorder, behind=behind, atl=atl, what=what, layer=layer)
            return

        # Have we downloaded this image previously?
        path=dl_search(persistent.allfiles, 0, img)
        print(str(path))

        # Image doesn't exists, we must download it
        while (path == ERR_INVALID):
            tr_loading=True
            # Latest version converts these formats to WebP
            if ext in [".png", ".jpg", ".jpeg"]:
                ext=".webp"
            # Otherwise, preserve extension.
            if True or renpy.android:
                addr="extra_%s%s" % (img.replace(" ", "_"), ext)
            else:
                addr="extra/%s%s" % (img.replace(" ", "_"), ext)

            f=open(get_path(addr), "wb")
            stdout("Downloading additional file: %s" % img.replace(" ", "_"))
            try:
                x=requests.get("%s://%s/assets/%s?token=%s" % (ifte(persistent.ssl_enabled, "https", "http"), HOST, img.replace(" ", "_"), get_token()), verify=False) # , timeout=8.0  Need to handle sudden death
            except:
                # Oh noes - something went *terribly* wrong
                traceback.print_exc()
                x=requests.Response()
                x.status_code=403

            if x.status_code == 200:
                f.write(x.content)
                f.close()
                # Android needs paths to be saved by full
                # But audio hates it, so.
                if ext not in [".mp3", ".ogg"]:
                    addr=get_path(addr)
                path=((img, addr))
                persistent.allfiles.append(path)
            else:
                stdout("ERROR FOR: %s://%s/assets/%s?token=%s" % (ifte(persistent.ssl_enabled, "https", "http"), HOST, img.replace(" ", "_"), get_token()))
                try:
                    retry=renpy.call_screen("confirm", "Error downloading file.\nError Code: %d\n\nRetry?" % x.status_code, Return(True), Return(False))
                    if not retry:
                        if tag is None:
                            tag=img
                        path=None
                        if show:
                            if tag is None:
                                tag=img
                            print("tag is %s" % str(tag))
                            renpy.show("spinner", at_list=at_list, tag=tag, zorder=zorder, behind=behind, atl=atl, what=what, layer=layer) # TODO Show error
                        tr_loading=False
                        return
                    # TODO: Retry?
                except:
                    print("Failed, trying again in half second...")
                    time.sleep(0.5)

        # Image exists, but wasn't loaded yet
        if (path != ERR_INVALID and path is not None):
            print("Detected not loaded image: %s" % path[0])
            # Valid Image Extensions: PNG, JPG, JPEG, GIF, WEBP
            if ext in [".png", ".jpg", ".jpeg", ".gif", ".webp"]:
                # Maybe it is an unit
                if img.startswith("unit_"):
                    new_img(img, card_composite(img.replace("unit_", ""), path[1], ei=True), isimage=False)
                elif img.startswith("square_"):
                    new_img(img, square_composite(img.replace("square_", ""), path[1], ei=True), isimage=False)
                else:
                    new_img(img, path[1])

            stdout("registered image: "+path[1])
            allfiles.append(img)
            if show:
                renpy.show(img, at_list=at_list, tag=tag, zorder=zorder, behind=behind, atl=atl, what=what, layer=layer)
            tr_loading=False
            return

        # Something went wrong
        stdout("show_img reached abnormal ending")
        return

    ##########################################################
    # Other Music
    #MUSIC_OPENING => Init Block -3
    #MUSIC_TOWN => Init Block -3
    MUSIC_BATTLE=RetString("sfx/bgm03.mp3")
    MUSIC_BOSS=RetString("sfx/bgm04.mp3")
    MUSIC_PARTY=RetString("sfx/bgm05.ogg")
    MUSIC_VICTORY=RetString("sfx/bgm06.mp3")
    MUSIC_WORLDMAP=RetString("sfx/bgm07.mp3")
    #MUSIC_WORLDMAP=ExecuteOnCall(get_sfx, "sfx_bgm07", ".mp3")
    MUSIC_PROLOGUE01=RetString("sfx/regnum.mp3")
    MUSIC_PROLOGUE02=RetString("sfx/prologue.mp3")
    MUSIC_PROLOGUE03=RetString("sfx/shining.mp3")

init 1 python:
    def unitsquare(uid, atl=czoom_70):
        show_img("square_%d" % uid, False)
        try:
            btn=At("square_%d" % uid, atl)
        except:
            btn=At("square_0", atl)
            traceback.print_exc()
            stdout("[ERROR] ATCODE FOR square_%d is INVALID" % uid)
        return btn