summaryrefslogblamecommitdiff
path: root/game/script.rpy
blob: ee8294b59590c0f506b37a2e4907e39225a0b975 (plain) (tree)
1
2
3
4
5
6
7
8
9


                                               
                                    
 


                           
                                
                                                      
               
                              

                           
                 
 



                                          
           
            
                                                                      
               
                                                                 
                                                                   
                             
 
                                                                   
                          
                    
 

                                       




                                          


                                    




                                   
                          





                           
                                                                            







                                
                                     




                                                            
               
                                                    






                                                                                         


                                                                                                                                                

                                                                                   
                 

                                                             
                                 




                                           

                           
 
                              

                                  
                     





                                            
 




                                                                                                            






                                                                           
                                      


                                     
                                                               
 


                                     
                    





                                                                                                            
 
                                             
               
                           




                                    
                                          








                                                                  

             









                                                                                                              



                                                                                                     
                                     

                                                                








                                                





                                                 
         







                                  
                                            
                            







                                                                      
                            
                 
                                                                                                                                      
 
                                                                



















                                                         
                                 









                                    













                                                                                        

                         
                                         

               

                                     
                    
           


                                 

                                                             



                      
               

                                     
                                   


                












                                  



                         

                     


                                               
# The script of the game goes in this file.
# Declare images
#image bg room = Frame("gfx/bg/port.png", 0, 0)
image banner_ = "gfx/actionarea.png"


# Inform you are now ingame
label start:
    # Begin the initial displays
    # TODO: Use something more fantasy than a spinner?
    scene black
    show spinner at truecenter

    # Initial configuration
    call prestart

    # Run updater
    $ renpy.invoke_in_thread(GAME_UPDATER)

    # Estabilish the connection to server
    python:
        try:
            renpy.invoke_in_thread(supervisor, persistent.ssl_enabled)
        except:
                # Enter in infinite loop, this will never resolve
                stdout("Unrecoverable error, the program is dead.")
                tr_load=False

        # Block the main thread until the socket connection is done
        while not tr_load:
            sdelay()

    $ stdout("Connection established!")

    # FIXME: This be bad for old phones
    # Load all downloaded images to RAM
    # (For a smoother gameplay)
    $ renpy.invoke_in_thread(async_loader)

    # Open game
    scene bg town with Dissolve(0.3)
    pause 0.1
    $ password=persistent.password
    $ email=""

    # Check if we need to register
    if persistent.password is None:
        $ main_menu = True
        call screen welcome
        return

    # Otherwise just login
    jump login

############################################################################
# Login procedures
label login:
    $message=login()
    # TODO=load message
    $ stdout(message)
    python:
        try:
            message=int(message)
            dlcode=copy.copy(message)
        except NameError:
            traceback.print_exc()
            print("AN ERROR HAPPENED AT LOGIN TIME")
            stdout("A NameError has also been encountered.")
            message=-1
        except:
            print("AN ERROR HAPPENED AT LOGIN TIME")
            stdout("Invalid: "+str(message))
            message=-1

    if (message < 5000):
        if (message == ERR_LOGIN_DEFAULT):
            e "Error Code: [message]{fast}\n\nCould not estabilish connection to server."
            jump login
        elif (message == ERR_OUTDATED):
            e "A new update is available!\n\nPlease download it from app store or at {a=https://spheres.tmw2.org/download}spheres.tmw2.org{/a}."
            jump quit
        else:
            e "Error Code: [message]{fast}\n\nCannot login to server. Terminating."
        jump quit

    # Successful login? Update client data and begin routines
    $ stdout("Login successful.")

    # Load game to memory
    python:
        tr_load=False
        renpy.invoke_in_thread(GAME_LOADER)
        #while not tr_load:
        #    sdelay()

    show spinner at truecenter
    $ persistent.password=password
    $ dlcode-=5000
    #$ ping_routine()
    python:
        try:
            renpy.invoke_in_thread(irc_loop)
        except:
            stdout("IRC disabled")
            pass

    ## Are we alive?
    if tr_fatality:
        e "An unexpected error was found and the game will now terminate. Please report this to developers."
        jump quit

    # We're now logged in, load misc data (TODO: What if ERR_ is returned?)
    $ who = -1
    $ inv=get_inventory()
    python:
        for a in inv:
            Player["inv"].append(a)

        # TODO: Run AP Timer if needed

    # Remove some temporary variables
    $ del password
    $ stdout("Waiting for game data to be loaded to memory...")

    # Wait until everything is loaded
    python:
        while not tr_memcheck:
            sdelay()
    hide spinner with None

    ## Are we alive?
    if tr_fatality:
        e "An unexpected error was found and the game will now terminate. Please report this to developers."
        jump quit

    ## If you just registered, go to prologue
    if (email):
        $ main_menu = False
        $ del email
        jump prologue

    # Begin loop
    play music MUSIC_TOWN fadein 0.5
    $ stdout("Game started successfully!")

    # Show news (if they exist and you haven't logged in past day)
    if dlcode:
        if (len(allnews) >= 1):
            call screen show_news
        else:
            $stdout("This server doesn't have a MOTD")
        # TODO: Daily login rewards screen

    jump loop

label loop:
    # Delete predictions, if possible
    $ renpy.free_memory()

    # Maybe we're in combat? If we are, you cannot go to town
    if (Player["status"] >= ST_QUEST):
        window hide None
        $ renpy.call_screen("msgbox", "{b}Battle{/b}\n\nYou are in battle. You'll be brought back to combat.")
        #window show None
        $ Battle=reload_battle()
        python:
            try:
                TMP_BACKG=dl_search(allquests[Battle["world"]], "quest_id", Battle["quest_id"])["bg"]
            except:
                traceback.print_exc()
                stdout("Invalid background for reloaded battle")
                pass
        # TODO: Handle errors
        if (Battle in [ERR_JSONDECODER]):
            e "Unknown Error: [ERR_JSONDECODER]"
            jump loop
        play music MUSIC_BATTLE.id() fadein 0.5
        jump combat


    $ hud_show()

    ## Maybe you still haven't done the prologue?
    if (persistent.nickname is None):
        jump prologue

    ## Main loop
    menu:
        "World Map":
            jump quest_select
        "Manage Party":
            jump party_lobby_enter
        "Show inventory":
            jump inventory
        "Visit tavern":
            jump tavern
        "IRC Chat" if persistent.irc_enable:
            # TODO FIXME PUB
            if persistent.nickname is not None:
                python:
                    while True:
                        _return=renpy.call_screen("pub")
                        if _return != "":
                            res=irc_send(persistent.nickname, _return)
                        else:
                            break
                jump restore
            else:
                "ERROR" "You are not authorized to complete this operation.\n\nERR_NICK" # ??? I thought you choose one at prologue???

        "Logout" if renpy.variant("pc") or renpy.variant("web"):
            #$message=send_packet("logout")
            jump quit
            #"Server replies:" "[message]"
            #return

    if (message == OFFLINEMSG):
        "Server replies:" "[message]\n\nYou are offline?"
        return

    if (message not in [ERR_OK, OKMSG, True]):
        "Server replies:" "[message]"

    jump loop
    # This ends the game.
    return


label restore:
    # Restore town view
    scene bg town
    $ renpy.hide_screen("battle")
    play music MUSIC_TOWN fadein 0.5
    $ hud_show()
    jump loop


label prologue:
    $ hud_story()
    call SQ00001_prologue
    # Automatically begin quest
    $ Battle=loadquest(1)
    python:
        try:
            quest=dl_search(allquests["Main"], "quest_id", 1)
            TMP_MUSIC=get_sfx(quest["music"])
            TMP_BACKG=quest["bg"]
            update_ap()
        except:
            traceback.print_exc()
    # Check for error
    if (Battle in [FAILUREMSG, OFFLINEMSG, ERR_JSONDECODER, ERR_LOGIN_DEFAULT]):
        $ renpy.call_screen("msgbox", "Error:\n\n%s\nYou'll be taken to town." % Battle)
        jump restore

    play music TMP_MUSIC fadein 0.5
    $ renpy.free_memory()
    window hide
    $ renpy.stop_predict_screen("battle")
    jump combat

label quit:
    $ stdout("Received quit signal!")
    $ CLOSING = True
    python:
        # If needed, logout
        try:
            token=Player["token"]
            renpy.invoke_in_thread(send_packet_now, "logout")
            sdelay(0.5)
            del Player
        except:
            pass

        # FIXME
        # If needed, close the socket
        try:
            ws.close(reason="Quit")
        except:
            pass

        # Delete variables
        try:
            del allunitsbase
            del allunits
            del header
            del allnews
            del allstory
            del allworld
            del alltaverns
        except:
            pass

        # Terminate IRC connection
        try:
            irc_kill()
        except NameError:
            pass

    # Data cleaned up
    $ print("Sockets closed and data flushed!")
    return