示例#1
0
文件: main.py 项目: RonWeber/anyworld
def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH,HEIGHT))

    #Main part is 700 pixels, I guess
    #Line will be 1 px
    #text part is the rest
    textPart = text_part.TextPart(((WIDTH - MAIN_WINDOW_WIDTH - 1), HEIGHT))

    world = World(NODE_COLS, NODE_ROWS, (MAIN_WINDOW_WIDTH / NODE_COLS), (HEIGHT / NODE_ROWS))
    
    running = True
    #Enter main loop
    while running:
        pygame.draw.line(screen, LINE_COLOR, (MAIN_WINDOW_WIDTH + 1, 0),
                         (MAIN_WINDOW_WIDTH + 1, HEIGHT))
        textPart.update_text()
        screen.blit(textPart.get_surface(), (MAIN_WINDOW_WIDTH + 2, 0))
        world.draw(screen)        
        pygame.display.flip()

        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                running = False
                pygame.quit()
                sys.exit(0)
            elif e.type == pygame.MOUSEBUTTONUP:
                textPart.selected_thing = world.underCursor(pygame.mouse.get_pos())
示例#2
0
    def __init__(self, sim):
        """ Printer constructor. It takes care of starting up curses, defining
		the data pages and setting the printer on its initial state.
		"""
        self.__sim = sim
        self.__color_pair_count = 0

        # Initialize curses screen, instruction and proc-element list before
        # other private elements that depend on them.
        self.screen = self.__get_screen()
        self.inst_list = self.__get_inst_list()
        self.proc_elements = self.__get_proc_elements()

        # We can now initialize all other privates.
        self.__main = self.__get_main()
        self.__pages = self.__get_pages()
        self.__minimal = self.__get_minimal()
        self.__main_scroll = 0
        self.__proc_element_scroll = 0
        self.__proc_gene_scroll = 0
        self.__proc_gene_view = False
        self.__common_buffer_scroll = 0
        self.__curs_y = 0
        self.__curs_x = 0
        self.__print_hex = False
        self.size = self.screen.getmaxyx()
        self.current_page = "MEMORY"
        self.selected_proc = 0
        self.selected_proc_data = (c_uint32 * len(self.proc_elements))()
        self.proc_list_scroll = 0
        self.world = World(self, self.__sim)
示例#3
0
 def test_draw_world_in_gui(self):
     world = World({
         Cell(0, 0, 'A'),
         Cell(0, 0, 'B'),
         Cell(0, 0, 'C'),
         Cell(0, 0, 'D'),
     })
     gui = Gui()
     gui.set_args(0, 0, 10, 10)
     gui.draw(world)
示例#4
0
文件: bad.py 项目: Sid1057/life_test
import tkinter as tk
import PIL
import PIL.Image, PIL.ImageTk
import cv2 as cv

world = World({
    Cell(0, 0, 'B'),
    Cell(1, 1, 'B'),
    Cell(1, 2, 'B'),
    Cell(0, 2, 'B'),
    Cell(-1, 2, 'B'),
    Cell(4, 5, 'C'),
    Cell(4, 4, 'C'),
    Cell(2, 4, 'C'),
    Cell(3, 4, 'C'),
    Cell(-1, -1, 'A'),
    Cell(-2, -1, 'A'),
    Cell(0, -1, 'A'),
    Cell(-3, -1, 'D'),
    Cell(-4, -1, 'D'),
    Cell(-5, -1, 'D'),
    Cell(-6, -1, 'D'),

    # Cell(-0, -5, 'A'),
    # Cell(-7, -1, 'A'),
})
gui = Gui(20)


class Application(tk.Frame):
    def __init__(self, master=None):
示例#5
0
class App:
    player = None

    def __init__(self):
        # override the standard sys output to redirect the typical built-in print() command
        sys.stdout.write = self.print_redirect

        self.next_method = None
        self.action = None
        self.tag = None

        ########### SETUP THE GAME WINDOW FRAME #############
        # Initialize the tkinter object
        self.root = Tk()
        # set window opacity
        self.root.attributes('-alpha', 0.90)
        self.root.geometry("900x650+0+0")
        # set the application title
        self.root.title("The Europa Protocol - Adventure Game")

        # bind an event exection on the "enter" key user event
        self.root.bind('<Return>', self.inputText)

        # Set the frame background, font color, and size of the text window
        self.mainframe = Text(self.root, bg='black', fg='white')
        self.mainframe.grid(column=0, row=0, sticky=(N, W, E, S))

        # The "columnconfigure"/"rowconfigure" bits just tell Tk that if the main window is resized, the frame should expand to take up the extra space.
        self.mainframe.columnconfigure(0, weight=1)
        self.mainframe.rowconfigure(0, weight=1)

        ### Create the textbox for inputting commands
        # Declare the textbox variable
        self.inputline = StringVar()
        # initialize the textbox widget
        self.inputline_entry = Entry(self.root, textvariable=self.inputline)
        self.inputline_entry.grid(sticky=(W, E, S))

        # focus the cursor in the inputline action box
        self.inputline_entry.focus_set()

        # make the application window expandable
        self.root.grid_columnconfigure(0, weight=1)
        self.root.grid_rowconfigure(0, weight=1)

        # initialize all the Text widget tag configurations to be used to change colors later
        BgColors(self.mainframe)

        # check to see if there is an update available for the game data
        self.check_state()

    def check_state(self):
        ########### CHECK IF THERE GAME NEEDS UPDATING ##########
        if Connection.is_connected():
            up_to_date, self.download_url = Check.is_up_to_date()
            if not up_to_date:
                # this means the game version is outdated, we need to update it
                print(
                    BgColors.HEADER +
                    'An update is available, would you like to download? [y/n]: '
                    + BgColors.ENDC)
                self.next_method = self.do_update_game
            else:
                self.begin_intro()
        else:
            self.begin_intro()

    def do_update_game(self, input):
        # if the answer is yes, the user wants to update the game data
        if input.lower() == 'y':
            try:
                # fire the method to get the game updates from the remote server
                Update.get_updates(self.root, self.download_url)
                # copy the game contents from the newly extracted temp dir to the installation dir
                Update.copy_contents(self.root)
                # remove the temp dir from the system to prevent unnecessary harddrive usage
                Update.destroy_env(self.root)
                print(BgColors.OKGREEN + "Update successful." + BgColors.ENDC)
                print("Restarting game...")
                self.root.update()
                # wait long enough for the user to read all the log entries from the update
                time.sleep(3)
                # reload the game so the new version is being used
                Update.reload_game()
                # exit current version
                sys.exit()

            except Exception as e:
                print(BgColors.FAIL +
                      "Updated failed, check service logs for details." +
                      BgColors.ENDC)
                self.root.update()

        self.begin_intro()

    def begin_intro(self):
        self.print_intro()
        # attempt to load previous game state, or create new game state if no previous is found
        self.load_game_state()

    def inputText(self, event, player=None):
        if (self.player and Health.is_alive(self.player)) or not player:
            # get the text from the input box
            i = self.inputline.get().lower().strip()
            # delete the contents from the input box
            self.inputline_entry.delete(0, 'end')
            # send the contents of the input box to the print function
            print("\n" + BgColors.NORMAL + "Your Action: " + i)
            # execute the next method in line, set by previous call
            self.next_method(i)

    def print_redirect(self, inputStr):
        # set an empty tag tuple
        #tag = ('NORMAL',)
        tag = None
        if BgColors.HEADER in inputStr:
            tag = ('HEADER', )
        elif BgColors.OKBLUE in inputStr:
            tag = ('OKBLUE', )
        elif BgColors.SKYBLUE in inputStr:
            tag = ('SKYBLUE', )
        elif BgColors.CADETBLUE in inputStr:
            tag = ('CADETBLUE', )
        elif BgColors.OKGREEN in inputStr:
            tag = ('OKGREEN', )
        elif BgColors.WARNING in inputStr:
            tag = ('WARNING', )
        elif BgColors.FAIL in inputStr:
            tag = ('FAIL', )
        elif BgColors.NORMAL in inputStr:
            tag = ('NORMAL', )
        elif BgColors.ENDC in inputStr:
            tag = ()

        if not tag and self.tag:
            tag = self.tag

        self.tag = tag

        # replace reference to [color] and [endc] identifier in text string
        inputStr = re.sub(r'(\[!\w+!])', '', inputStr)
        # add the text to the window widget
        self.mainframe.configure(state='normal')
        self.mainframe.insert("end-1c", inputStr, tag)
        self.mainframe.configure(state='disabled')
        # automtically scroll to the end of the mainframe window
        self.mainframe.see(END)

    def load_game_state(self):
        # check if there is a game save file with a previously saved state
        if os.path.exists('gsave.pkl'):
            # prompt the user to answer if they want to load from a saved state
            #action_input = input( BgColors.HEADER + 'Load Saved Game? [y/n]: ' + BgColors.ENDC).lower()
            print(BgColors.HEADER + 'Load Saved Game? [y/n]: ' + BgColors.ENDC)
            self.next_method = self.load_game_state_check
        # otherwise a save file was not found
        else:
            # create the world state from scratch
            self.create_new_world()

    def load_game_state_check(self, input):
        # if the answer is yes, they want to load from the previous save, then attempt to load
        if input.lower() == 'y':
            # open the save state file
            with open('gsave.pkl', 'r') as output:
                # assign player object as the pickled object, decoded
                self.player = jsonpickle.decode(output.read())
                # assign the world object as the player.world property
                self.world = self.player.world

            self.load_starting_position()
        # if the user answered no, they do not want to load from saved state, then start a new game and load all objects with original states
        elif input.lower() == 'n':
            self.create_new_world()

        # if the user didn't answer with a yes or no response, then loop again with an error message
        elif input.lower() not in ['y', 'n']:
            print("{}You must provide a [y/n] answer!{}".format(
                BgColors.FAIL, BgColors.ENDC))
            self.load_game_state()

    def create_new_world(self):
        self.world = World()
        self.player = Player(self.world)

        self.load_starting_position()

    def load_starting_position(self):
        # These lines load the starting room and display the text
        self.player.room = self.world.tile_exists(self.player.location_x,
                                                  self.player.location_y)

        # print the room intro text
        #print(re.sub(r'(^[ \t]+|[ \t]+(?=:))', '', "\n" + BgColors.NORMAL + self.player.room.intro_text() + BgColors.ENDC, flags=re.M))
        print(BgColors.NORMAL + "─" * 70)
        print(BgColors.NORMAL + "\n" + self.player.room.intro_text() +
              BgColors.ENDC)
        self.world.tile_exists(self.player.location_x,
                               self.player.location_y).visited = True

        # start the main play execution sequence
        self.play()

    def play(self):
        # check if the player is alive, end game if not
        if not Health.is_alive(self.player):
            State.game_end()

        # if player is alive, and has not achieved victory, then continue with main logic
        elif not self.player.victory:
            # The first thing the loop does is find out what room the player is in and then executes the behavior for that room.
            self.player.room = self.world.tile_exists(self.player.location_x,
                                                      self.player.location_y)

            if not (isinstance(
                    self.action,
                (actions.ItemAction, actions.HiddenAction))) and (
                    (issubclass(self.player.room.__class__, tiles.EnemyRoom)
                     and isinstance(self.action, actions.Attack))
                    or issubclass(self.player.room.__class__,
                                  tiles.LeaveCaveRoom)):
                self.player.room.modify_player(self.player)

            # display the mini help options for available options (not extended help view)
            #if not isinstance(self.action, actions.HiddenAction):
            #self.player.help()
            kwargs = {
                'actions':
                actions,
                'available_actions':
                self.player.room.available_actions(self.player)
            }
            aHelp.help(**kwargs)

            # prompt the user to input an action
            #print(BgColors.HEADER + '\n\nAction: ' + BgColors.ENDC, end='')
            self.next_method = self.do_action_check
            self.inputline_entry.focus()

    def do_action_check(self, input):
        # get the available actions for the room from the available actions method in each tile class
        available_actions = self.player.room.available_actions(self.player)

        action_found = False
        for action in available_actions:
            #  If the human player provided a matching hotkey, then we execute the associated action using the do_action method.
            if input.strip().split(' ')[0] in action.hotkey:
                action_found = True
                # if there is a space in the command input, then split the content on the space, and use the second item as the key/index passed to the action command
                if len(input.split(' ', 1)) > 1:
                    action.kwargs.update({'item': input.split(' ')[1]})

                    # this must mean an additional argument was passed, like a keycode to follow the usage of a keypad
                    if len(input.split(' ')) > 2:
                        action.kwargs.update({'code': input.split(' ')[2]})

                action.kwargs.update({
                    'player':
                    self.player,
                    'actions':
                    actions,
                    'actions_list':
                    actions.Action.get_actions(),
                    'available_actions':
                    self.player.room.available_actions(self.player),
                    'tiles':
                    tiles
                })

                # set the instance action attribute for use in other class methods
                self.action = action
                print("\n" + BgColors.NORMAL + "─" * 70)

                #self.player.do_action(action, **action.kwargs)

                # Now we need to allow the Player class to take an Action and run the action`s internally-bound method.
                #def do_action(self, action, *args, **kwargs):
                #action_method = getattr(self, action.method.__name__)
                #if action_method:
                #action_method(*args, **kwargs)
                action.method(**action.kwargs)

                break
        # if the action was not found in the available action list
        if not action_found:
            self.action = None
            print("\n" + BgColors.NORMAL + "─" * 70)
            print(
                "{}You can't do that! Choose an action from the list below.\nExample: '[command] [#]' to interact with an item.{}"
                .format(BgColors.FAIL, BgColors.ENDC))

            #self.player.help()
        # execute the self.play() iteration again to maintain the loop
        self.play()

    def print_intro(self):
        print("""
 _____ _            _____                              ____            _                  _ 
|_   _| |__   ___  | ____|   _ _ __ ___  _ __   __ _  |  _ \ _ __ ___ | |_ ___   ___ ___ | |
  | | | '_ \ / _ \ |  _|| | | | '__/ _ \| '_ \ / _` | | |_) | '__/ _ \| __/ _ \ / __/ _ \| |
  | | | | | |  __/ | |__| |_| | | | (_) | |_) | (_| | |  __/| | | (_) | || (_) | (_| (_) | |
  |_| |_| |_|\___| |_____\__,_|_|  \___/| .__/ \__,_| |_|   |_|  \___/ \__\___/ \___\___/|_|
                                        |_|                                                 
{}Copyright (C) 2015  Corey Farmer

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 3 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.

Type '?' to view a full list of available actions and ways to 
interact within the game.
""".format(BgColors.CADETBLUE))
示例#6
0
    def create_new_world(self):
        self.world = World()
        self.player = Player(self.world)

        self.load_starting_position()
示例#7
0
 def test_set_arggs_method(self):
     world = World()
     gui = Gui()
     gui.set_args(0, 0, 10, 10)
示例#8
0
class Printer:
    ESCAPE_KEY = 27

    def __init__(self, sim):
        """ Printer constructor. It takes care of starting up curses, defining
		the data pages and setting the printer on its initial state.
		"""
        self.__sim = sim
        self.__color_pair_count = 0

        # Initialize curses screen, instruction and proc-element list before
        # other private elements that depend on them.
        self.screen = self.__get_screen()
        self.inst_list = self.__get_inst_list()
        self.proc_elements = self.__get_proc_elements()

        # We can now initialize all other privates.
        self.__main = self.__get_main()
        self.__pages = self.__get_pages()
        self.__minimal = self.__get_minimal()
        self.__main_scroll = 0
        self.__proc_element_scroll = 0
        self.__proc_gene_scroll = 0
        self.__proc_gene_view = False
        self.__common_buffer_scroll = 0
        self.__curs_y = 0
        self.__curs_x = 0
        self.__print_hex = False
        self.size = self.screen.getmaxyx()
        self.current_page = "MEMORY"
        self.selected_proc = 0
        self.selected_proc_data = (c_uint32 * len(self.proc_elements))()
        self.proc_list_scroll = 0
        self.world = World(self, self.__sim)

    def __del__(self):
        """ Printer destructor exits curses.
		"""
        curses.endwin()

    def get_color_pair(self, fg, bg=-1):
        """ We use this method to set new color pairs, keeping track of the
		number of pairs already set. We return the new color pair ID.
		"""
        self.__color_pair_count += 1
        curses.init_pair(self.__color_pair_count, fg, bg)
        return self.__color_pair_count

    def get_cmd(self):
        """ This returns the pressed key from the curses handler. It's called
		during the simulation's main loop. Flushing input is important when in
		non-blocking mode.
		"""
        ch = self.screen.getch()
        curses.flushinp()
        return ch

    def set_nodelay(self, nodelay):
        """ Toggles between blocking and non-blocking mode on curses.
		"""
        self.screen.nodelay(nodelay)

    def toggle_hex(self):
        """ Toggle between decimal or hexadecimal printing of all simulation
		state elements.
		"""
        self.__print_hex = not self.__print_hex

    def on_resize(self):
        """ Called whenever the terminal window gets resized.
		"""
        self.size = self.screen.getmaxyx()
        self.scroll_main()
        self.world.zoom_reset()

    def flip_page(self, offset):
        """ Change data page by given offset (i.e. '1' for next page or '-1'
		for previous one).
		"""
        pidx = list(self.__pages.keys()).index(self.current_page)
        pidx = (pidx + offset) % len(self.__pages)
        self.current_page = list(self.__pages.keys())[pidx]
        self.scroll_main()

    def scroll_main(self, offset=0):
        """ Scrolling is allowed whenever the current page does not fit inside
		the terminal window. This method gets called, with no offset, under
		certain situations, like changing pages, just to make sure the screen
		gets cleared and at least some of the data is always scrolled into
		view.
		"""
        self.screen.clear()
        len_main = len(self.__main)
        len_page = len(self.__pages[self.current_page])
        max_scroll = (len_main + len_page + 5) - self.size[0]
        self.__main_scroll += offset
        self.__main_scroll = max(0, min(self.__main_scroll, max_scroll))

    def proc_scroll_left(self):
        """ Scroll process data elements or genomes (on PROCESS view) to the
		left.
		"""
        if self.current_page == "PROCESS":
            if self.__proc_gene_view:
                self.__proc_gene_scroll -= 1
                self.__proc_gene_scroll = max(0, self.__proc_gene_scroll)
            else:
                self.__proc_element_scroll -= 1
                self.__proc_element_scroll = max(0, self.__proc_element_scroll)

    def proc_scroll_right(self):
        """ Scroll process data elements or genomes (on PROCESS view) to the
		right.
		"""
        if self.current_page == "PROCESS":
            if self.__proc_gene_view:
                self.__proc_gene_scroll += 1
            else:
                self.__proc_element_scroll += 1
                max_scroll = len(self.proc_elements) - 1
                self.__proc_element_scroll = min(max_scroll,
                                                 self.__proc_element_scroll)

    def comm_scroll_left(self):
        """ Scroll buffers (on COMMON view) to the left.
		"""
        if self.current_page == "COMMON":
            self.__common_buffer_scroll -= 1
            self.__common_buffer_scroll = max(0, self.__common_buffer_scroll)

    def comm_scroll_right(self):
        """ Scroll buffers (on COMMON view) to the right.
		"""
        if self.current_page == "COMMON":
            self.__common_buffer_scroll += 1

    def proc_scroll_down(self, fast=False):
        """ Scroll process data table (on PROCESS view) up.
		"""
        if self.current_page == "PROCESS":
            if fast:
                len_page = len(self.__main) + len(self.__pages["PROCESS"]) + 6
                scroll = max(0, self.size[0] - len_page)
            else:
                scroll = 1

            self.proc_list_scroll = max(0, self.proc_list_scroll - scroll)

    def proc_scroll_up(self, fast=False):
        """ Scroll process data table (on PROCESS view) down.
		"""
        if self.current_page == "PROCESS":
            if fast:
                len_page = len(self.__main) + len(self.__pages["PROCESS"]) + 6
                scroll = max(0, self.size[0] - len_page)
            else:
                scroll = 1

            self.proc_list_scroll = min(
                self.__sim.lib.sal_proc_get_capacity() - 1,
                self.proc_list_scroll + scroll)

    def proc_scroll_to(self, proc_id):
        """ Scroll process data table (on PROCESS view) to a specific position.
		"""
        if self.current_page == "PROCESS":
            if proc_id < self.__sim.lib.sal_proc_get_capacity():
                self.proc_list_scroll = proc_id
            else:
                raise RuntimeError("Error: scrolling to invalid process")

    def proc_scroll_vertical_reset(self):
        """ Scroll process data table (on PROCESS view) back to top.
		"""
        if self.current_page == "PROCESS":
            self.proc_list_scroll = 0

    def proc_scroll_horizontal_reset(self):
        """ Scroll process data or genome table (on PROCESS view) back to the
		left.
		"""
        if self.current_page == "PROCESS":
            if self.__proc_gene_view:
                self.__proc_gene_scroll = 0
            else:
                self.__proc_element_scroll = 0

    def comm_scroll_horizontal_reset(self):
        """ Scroll common in and out buffers back to the left.
		"""
        if self.current_page == "COMMON":
            self.__common_buffer_scroll = 0

    def proc_select_prev(self):
        """ Select previous process.
		"""
        if self.current_page in ["PROCESS", "WORLD"]:
            self.selected_proc -= 1
            self.selected_proc %= self.__sim.lib.sal_proc_get_capacity()

    def proc_select_next(self):
        """ Select next process.
		"""
        if self.current_page in ["PROCESS", "WORLD"]:
            self.selected_proc += 1
            self.selected_proc %= self.__sim.lib.sal_proc_get_capacity()

    def proc_select_first(self):
        """ Select first process on reaper queue.
		"""
        if self.current_page in ["PROCESS", "WORLD"]:
            if self.__sim.lib.sal_proc_get_count():
                self.selected_proc = self.__sim.lib.sal_proc_get_first()

    def proc_select_last(self):
        """ Select last process on reaper queue.
		"""
        if self.current_page in ["PROCESS", "WORLD"]:
            if self.__sim.lib.sal_proc_get_count():
                self.selected_proc = self.__sim.lib.sal_proc_get_last()

    def proc_select_by_id(self, proc_id):
        """ Select process from given ID.
		"""
        if proc_id < self.__sim.lib.sal_proc_get_capacity():
            self.selected_proc = proc_id
        else:
            raise RuntimeError("Error: attempting to select non-existing proc")

    def proc_scroll_to_selected(self):
        """ Scroll WORLD or PROCESS page so that selected process becomes
		visible.
		"""
        if self.current_page == "PROCESS":
            self.proc_list_scroll = self.selected_proc
        elif self.current_page == "WORLD":
            if not self.__sim.lib.sal_proc_is_free(self.selected_proc):
                index = self.proc_elements.index("mb1a")
                address = self.selected_proc_data[index]
                self.world.scroll_to(address)

    def proc_toggle_gene_view(self):
        """ Toggle between data element or genome view on PROCESS page.
		"""
        if self.current_page == "PROCESS":
            self.__proc_gene_view = not self.__proc_gene_view

    def run_cursor(self):
        """ We can toggle a visible cursor on WORLD view to aid us in selecting
		processes.
		"""
        if self.current_page == "WORLD" and self.size[1] > World.PADDING:
            curses.curs_set(True)

            while True:
                self.__curs_y = max(0, min(self.__curs_y, self.size[0] - 1))
                self.__curs_x = max(World.PADDING,
                                    min(self.__curs_x, self.size[1] - 1))
                self.screen.move(self.__curs_y, self.__curs_x)
                cmd = self.screen.getch()

                if cmd in [ord("c"), curses.KEY_RESIZE, self.ESCAPE_KEY]:
                    self.on_resize()
                    break
                elif cmd == curses.KEY_LEFT:
                    self.__curs_x -= 1
                elif cmd == curses.KEY_RIGHT:
                    self.__curs_x += 1
                elif cmd == curses.KEY_DOWN:
                    self.__curs_y += 1
                elif cmd == curses.KEY_UP:
                    self.__curs_y -= 1
                elif cmd == ord("\n"):
                    self.__proc_select_by_cursor()
                    break

            curses.curs_set(False)

    def run_console(self):
        """ Run the Salis console. You can use the console to control all main
		aspects of the simulation, like compiling genomes into memory, creating
		or killing organisms, setting auto-save interval, among other stuff.
		"""
        # Print a pythonic prompt.
        self.__print_line(self.size[0] - 1, ">>> ", scroll=False)
        self.screen.refresh()

        # Create the console child window. We turn it into a Textbox object in
        # order to allow line-editing and extract output easily.
        console = curses.newwin(1, self.size[1] - 5, self.size[0] - 1, 5)
        textbox = curses.textpad.Textbox(console, insert_mode=True)
        textbox.stripspaces = True

        # Grab a copy of the console history and instantiate a pointer to the
        # last element.
        history = self.__sim.handler.console_history + [""]
        pointer = len(history) - 1

        # Nested method reinserts recorded commands from history into console.
        def access_history(cmd):
            nonlocal pointer

            if pointer == len(history) - 1:
                history[-1] = console.instr().strip()

            if cmd == "up" and pointer != 0:
                pointer -= 1
            elif cmd == "down" and pointer < len(history) - 1:
                pointer += 1

            console.clear()
            console.addstr(0, 0, history[pointer])
            console.refresh()

        # Declare custom validator to control special commands.
        def validator(cmd):
            EXIT = 7

            if cmd in [curses.KEY_RESIZE, self.ESCAPE_KEY]:
                console.clear()
                return EXIT
            # Provide general code for back-space key, in case it's not
            # correctly defined.
            elif cmd in [127, curses.KEY_BACKSPACE]:
                return curses.KEY_BACKSPACE
            elif cmd == curses.KEY_UP:
                access_history("up")
            elif cmd == curses.KEY_DOWN:
                access_history("down")
            else:
                return cmd

        # Run the Textbox object with our custom validator.
        curses.curs_set(True)
        output = textbox.edit(validator)
        curses.curs_set(False)

        # Finally, extract data from console and send to handler. Respond to
        # any possible resize event here.
        self.__sim.handler.handle_console(output)
        self.screen.clear()
        self.on_resize()

    def show_console_error(self, message):
        """ Shows Salis console error messages, if any. These messages might
		contain actual python exception output.
		"""
        self.__print_line(self.size[0] - 1, ">>>",
                          curses.color_pair(self.__pair_error) | curses.A_BOLD)
        self.screen.refresh()

        # We also use a Textbox object, just so that execution gets halted
        # until a key gets pressed (even on non-blocking mode).
        console = curses.newwin(1, self.size[1] - 5, self.size[0] - 1, 5)
        textbox = curses.textpad.Textbox(console)

        # Curses may raise an exception if printing on the edge of the screen;
        # we can just ignore it.
        try:
            console.addstr(
                0, 0, message,
                curses.color_pair(self.__pair_error) | curses.A_BOLD)
        except curses.error:
            pass

        # Custom validator simply exits on any key.
        def validator(cmd):
            EXIT = 7
            return EXIT

        textbox.edit(validator)
        self.screen.clear()
        self.on_resize()

    def print_page(self):
        """ Print current page to screen. We use the previously generated
		'__pages' dictionary to easily associate a label to a Salis function.
		"""
        # If in minimal mode, print only minial widget.
        if self.__sim.minimal:
            self.__print_minimal()
            return

        # Update selected proc data if in WORLD view.
        if self.current_page == "WORLD":
            self.__sim.lib.sal_proc_get_proc_data(
                self.selected_proc,
                cast(self.selected_proc_data, POINTER(c_uint32)))

        # Print MAIN simulation data.
        self.__print_line(
            1, "SALIS[{}]".format(self.__sim.args.file),
            curses.color_pair(self.__pair_header) | curses.A_BOLD)
        self.__print_widget(2, self.__main)

        # Print data of currently selected page.
        main_lines = len(self.__main) + 3
        self.__print_header(main_lines, self.current_page)
        self.__print_widget(main_lines + 1, self.__pages[self.current_page])

        # Print special widgets (WORLD view and PROCESS list).
        if self.current_page == "WORLD":
            self.world.render()
        elif self.current_page == "PROCESS":
            self.__print_proc_list()
        elif self.current_page == "COMMON":
            self.__print_common_data()

    ###############################
    # Private methods
    ###############################

    def __set_colors(self):
        """ Define the color pairs for the data printer.
		"""
        curses.start_color()
        curses.use_default_colors()
        self.__pair_header = self.get_color_pair(curses.COLOR_BLUE)
        self.__pair_selected = self.get_color_pair(curses.COLOR_YELLOW)
        self.__pair_error = self.get_color_pair(curses.COLOR_RED)

    def __get_screen(self):
        """ Prepare and return the main curses window. We also set a shorter
		delay when responding to a pressed escape key.
		"""
        # Set a shorter delay to the ESCAPE key, so that we may use it to exit
        # Salis.
        os.environ.setdefault("ESCDELAY", "25")

        # Prepare curses screen.
        screen = curses.initscr()
        curses.noecho()
        curses.cbreak()
        screen.keypad(True)
        curses.curs_set(False)

        # We need color support in order to run the printer module.
        if curses.has_colors():
            self.__set_colors()
        else:
            raise RuntimeError("Error: no color support.")

        return screen

    def __get_inst_list(self):
        """ Parse instruction set from C header file named 'instset.h'. We're
		using the keyword 'SALIS_INST' to identify an instruction definition,
		so be careful not to use this keyword anywhere else on the headers.
		"""
        inst_list = []
        inst_file = os.path.join(self.__sim.path, "../include/instset.h")

        with open(inst_file, "r") as f:
            lines = f.read().splitlines()

        for line in lines:
            if line and line.split()[0] == "SALIS_INST":
                inst_name = line.split()[1][:4]
                inst_symb = line.split()[3]
                inst_list.append((inst_name, inst_symb))

        return inst_list

    def __get_proc_elements(self):
        """ Parse process structure member variables from C header file named
		'process.h'. We're using the keyword 'SALIS_PROC_ELEMENT' to identify
		element declarations, so be careful not to use this keyword anywhere
		else on the headers.
		"""
        proc_elem_list = []
        proc_elem_file = os.path.join(self.__sim.path, "../include/process.h")

        with open(proc_elem_file, "r") as f:
            lines = f.read().splitlines()

        for line in lines:
            if line and line.split()[0] == "SALIS_PROC_ELEMENT":
                proc_elem_name = line.split()[2].split(";")[0]

                if proc_elem_name == "stack[8]":
                    # The stack is a special member variable, an array. We
                    # translate it by returning a list of stack identifiers.
                    proc_elem_list += ["stack[{}]".format(i) for i in range(8)]
                else:
                    # We can assume all other struct elements are single
                    # variables.
                    proc_elem_list.append(proc_elem_name)

        return proc_elem_list

    def __get_main(self):
        """ Generate main set of data fields to be printed. We associate, on a
		list object, a label to each Salis function to be called. The following
		elements get printed on all pages.
		"""
        return [
            ("e", "cycle", self.__sim.lib.sal_main_get_cycle),
            ("e", "epoch", self.__sim.lib.sal_main_get_epoch),
            ("e", "state", lambda: self.__sim.state),
            ("e", "autosave", lambda: self.__sim.autosave),
        ]

    def __get_pages(self):
        """ Generate data fields to be printed on each page. We associate, on a
		list object, a label to each Salis function to be called. Each list
		represents a PAGE. We initialize all pages inside an ordered dictionary
		object.
		"""
        # The following comprehensions build up widgets to help up print sets
        # of data elements. The use of nested lambdas is needed to receive
        # updated values.
        # Instruction counter widget:
        inst_widget = [
            ("e", inst[0],
             (lambda j: (lambda: self.__sim.lib.sal_mem_get_inst_count(j)))(i))
            for i, inst in enumerate(self.inst_list)
        ]

        # Evolver module state widget:
        state_widget = [("e", "state[{}]".format(i),
                         (lambda j:
                          (lambda: self.__sim.lib.sal_evo_get_state(j)))(i))
                        for i in range(4)]

        # Selected process state widget:
        selected_widget = [
            ("p", element, (lambda j: (lambda: self.selected_proc_data[j]))(i))
            for i, element in enumerate(self.proc_elements)
        ]

        # With the help of the widgets above, we can declare the PAGES
        # dictionary object.
        return OrderedDict([
            ("MEMORY", [
                ("e", "order", self.__sim.lib.sal_mem_get_order),
                ("e", "size", self.__sim.lib.sal_mem_get_size),
                ("e", "allocated", self.__sim.lib.sal_mem_get_allocated),
                ("s", ""),
                ("h", "INSTRUCTIONS"),
            ] + inst_widget),
            ("EVOLVER", [
                ("e", "last", self.__sim.lib.sal_evo_get_last_changed_address),
                ("e", "calls", self.__sim.lib.sal_evo_get_calls_on_last_cycle),
            ] + state_widget),
            ("PROCESS", [
                ("e", "count", self.__sim.lib.sal_proc_get_count),
                ("e", "capacity", self.__sim.lib.sal_proc_get_capacity),
                ("e", "first", self.__sim.lib.sal_proc_get_first),
                ("e", "last", self.__sim.lib.sal_proc_get_last),
                ("e", "selected", lambda: self.selected_proc),
            ]),
            ("COMMON", [
                ("e", "in", lambda: len(self.__sim.common.in_buffer)),
                ("e", "out", lambda: len(self.__sim.common.out_buffer)),
                ("e", "max", lambda: self.__sim.common.max_buffer_size),
            ]),
            ("WORLD", [
                ("e", "position", lambda: self.world.pos),
                ("e", "zoom", lambda: self.world.zoom),
                ("e", "selected", lambda: self.selected_proc),
                ("s", ""),
                ("h", "SELECTED PROC"),
            ] + selected_widget),
        ])

    def __print_line(self, ypos, line, attrs=curses.A_NORMAL, scroll=True):
        """ Print a single line on screen only when it's visible.
		"""
        if scroll:
            ypos -= self.__main_scroll

        if 0 <= ypos < self.size[0]:
            # Curses raises an exception each time we print on the screen's
            # edge. We can just catch and ignore it.
            try:
                line = line[:self.size[1] - 1]
                self.screen.addstr(ypos, 1, line, attrs)
            except curses.error:
                pass

    def __print_header(self, ypos, line):
        """ Print a bold header.
		"""
        header_attr = curses.A_BOLD | curses.color_pair(self.__pair_header)
        self.__print_line(ypos, line, header_attr)

    def __print_value(self, ypos, element, value, attr=curses.A_NORMAL):
        """ Print a label:value pair.
		"""
        if type(value) == int:
            if value == ((2**32) - 1):
                # In Salis, UINT32_MAX is used to represent NULL. We print NULL
                # as three dashes.
                value = "---"
            elif self.__print_hex:
                value = hex(value)

        line = "{:<10} : {:>10}".format(element, value)
        self.__print_line(ypos, line, attr)

    def __print_proc_element(self, ypos, element, value):
        """ Print elements of currently selected process. We highlight in
		YELLOW if the selected process is running.
		"""
        if self.__sim.lib.sal_proc_is_free(self.selected_proc):
            attr = curses.A_NORMAL
        else:
            attr = curses.color_pair(self.__pair_selected)

        self.__print_value(ypos, element, value, attr)

    def __print_widget(self, ypos, widget):
        """ Print a widget (data PAGE) on screen.
		"""
        for i, element in enumerate(widget):
            if element[0] == "s":
                continue
            elif element[0] == "h":
                self.__print_header(i + ypos, element[1])
            elif element[0] == "e":
                self.__print_value(i + ypos, element[1], element[2]())
            elif element[0] == "p":
                self.__print_proc_element(i + ypos, element[1], element[2]())

    def __clear_line(self, ypos):
        """ Clear the specified line.
		"""
        if 0 <= ypos < self.size[0]:
            self.screen.move(ypos, 0)
            self.screen.clrtoeol()

    def __data_format(self, x):
        """ Print all proc IDs and elements in decimal or hexadecimal format,
		depending on hex-flag being set.
		"""
        if self.__print_hex:
            return hex(x)
        else:
            return x

    def __print_proc_data_list(self):
        """ Print list of process data elements in PROCESS page. We can toggle
		between printing the data elements or the genomes by pressing the 'g'
		key.
		"""
        # First, print the table header, by extracting element names from the
        # previously generated proc element list.
        ypos = len(self.__main) + len(self.__pages["PROCESS"]) + 5
        header = " | ".join(["{:<10}".format("pidx")] + [
            "{:>10}".format(element)
            for element in self.proc_elements[self.__proc_element_scroll:]
        ])
        self.__clear_line(ypos)
        self.__print_header(ypos, header)
        ypos += 1
        proc_id = self.proc_list_scroll

        # Lastly, iterate all lines and print as much process data as it fits.
        # We can scroll the process data table using the 'wasd' keys.
        while ypos < self.size[0]:
            self.__clear_line(ypos)

            if proc_id < self.__sim.lib.sal_proc_get_capacity():
                if proc_id == self.selected_proc:
                    # Always highlight the selected process.
                    attr = curses.color_pair(self.__pair_selected)
                else:
                    attr = curses.A_NORMAL

                # Retrieve a copy of the selected process state and store it in
                # a list object.
                proc_data = (c_uint32 * len(self.proc_elements))()
                self.__sim.lib.sal_proc_get_proc_data(
                    proc_id, cast(proc_data, POINTER(c_uint32)))

                # Lastly, assemble and print the next table row.
                row = " | ".join(
                    ["{:<10}".format(self.__data_format(proc_id))] + [
                        "{:>10}".format(self.__data_format(element))
                        for element in proc_data[self.__proc_element_scroll:]
                    ])
                self.__print_line(ypos, row, attr)

            proc_id += 1
            ypos += 1

    def __print_proc_gene_block(self, ypos, gidx, xpos, mbs, mba, ip, sp,
                                pair):
        """ Print a sub-set of a process genome. Namely, on of its two memory
		blocks.
		"""
        while gidx < mbs and xpos < self.size[1]:
            gaddr = mba + gidx

            if gaddr == ip:
                attr = curses.color_pair(self.world.pair_sel_ip)
            elif gaddr == sp:
                attr = curses.color_pair(self.world.pair_sel_sp)
            else:
                attr = curses.color_pair(pair)

            # Retrieve instruction from memory and transform it to correct
            # symbol.
            inst = self.__sim.lib.sal_mem_get_inst(gaddr)
            symb = self.inst_list[inst][1]

            # Curses raises an exception each time we print on the screen's
            # edge. We can just catch and ignore it.
            try:
                self.screen.addstr(ypos, xpos, symb, attr)
            except curses.error:
                pass

            gidx += 1
            xpos += 1

        return xpos

    def __print_proc_gene(self, ypos, proc_id):
        """ Print a single process genome on the genome table. We use the same
		colors to represent memory blocks, IP and SP of each process, as those
		used to represent the selected process on WORLD view.
		"""
        # There's nothing to print if process is free.
        if self.__sim.lib.sal_proc_is_free(proc_id):
            return

        # Process is alive. Retrieve a copy of the current process state and
        # store it in a list object.
        proc_data = (c_uint32 * len(self.proc_elements))()
        self.__sim.lib.sal_proc_get_proc_data(
            proc_id, cast(proc_data, POINTER(c_uint32)))

        # Let's extract all data of interest.
        mb1a = proc_data[self.proc_elements.index("mb1a")]
        mb1s = proc_data[self.proc_elements.index("mb1s")]
        mb2a = proc_data[self.proc_elements.index("mb2a")]
        mb2s = proc_data[self.proc_elements.index("mb2s")]
        ip = proc_data[self.proc_elements.index("ip")]
        sp = proc_data[self.proc_elements.index("sp")]

        # Always print MAIN memory block (mb1) first (on the left side). That
        # way we can keep most of our attention on the parent.
        xpos = self.__print_proc_gene_block(ypos, self.__proc_gene_scroll, 14,
                                            mb1s, mb1a, ip, sp,
                                            self.world.pair_sel_mb1)

        # Reset gene counter and print child memory block, if it exists.
        if mb1s < self.__proc_gene_scroll:
            gidx = self.__proc_gene_scroll - mb1s
        else:
            gidx = 0

        self.__print_proc_gene_block(ypos, gidx, xpos, mb2s, mb2a, ip, sp,
                                     self.world.pair_sel_mb2)

    def __print_proc_gene_list(self):
        """ Print list of process genomes in PROCESS page. We can toggle
		between printing the genomes or the data elements by pressing the 'g'
		key.
		"""
        # First, print the table header. We print the current gene-scroll
        # position for easy reference. Return back to zero scroll with the 'A'
        # key.
        ypos = len(self.__main) + len(self.__pages["PROCESS"]) + 5
        header = "{:<10} | genes {} -->".format(
            "pidx", self.__data_format(self.__proc_gene_scroll))
        self.__clear_line(ypos)
        self.__print_header(ypos, header)
        ypos += 1
        proc_id = self.proc_list_scroll

        # Iterate all lines and print as much genetic data as it fits. We can
        # scroll the gene data table using the 'wasd' keys.
        while ypos < self.size[0]:
            self.__clear_line(ypos)

            if proc_id < self.__sim.lib.sal_proc_get_capacity():
                if proc_id == self.selected_proc:
                    # Always highlight the selected process.
                    attr = curses.color_pair(self.__pair_selected)
                else:
                    attr = curses.A_NORMAL

                # Assemble and print the next table row.
                row = "{:<10} |".format(self.__data_format(proc_id))
                self.__print_line(ypos, row, attr)
                self.__print_proc_gene(ypos, proc_id)

            proc_id += 1
            ypos += 1

    def __print_buffer(self, ypos, buff):
        """ Print contents of a network buffer as a list of instruction
		symbols.
		"""
        if not ypos < self.size[0]:
            return

        if not len(buff):
            self.__print_line(ypos, "---")
            return

        xpos = 1
        bpos = self.__common_buffer_scroll
        self.__clear_line(ypos)

        while xpos < self.size[1] - 1 and bpos < len(buff):
            symbol = self.inst_list[int(buff[bpos])][1]
            self.screen.addstr(ypos, xpos, symbol)
            xpos += 1
            bpos += 1

    def __print_common_widget(self,
                              ypos_s,
                              ypos_b,
                              head_s,
                              head_b,
                              sockets,
                              buff,
                              sources=False):
        """ Print data pertaining input or output network buffers, sources and
		targets.
		"""
        self.__print_header(ypos_s, head_s)

        # Socket info is stored differently for input and output.
        if sources:
            fmt_sock = lambda s: "{} {}".format(*s.getsockname())
        else:
            fmt_sock = lambda s: "{} {}".format(*s)

        # Print active socket list.
        if sockets:
            for socket in sockets:
                ypos_s += 1
                self.__print_line(ypos_s, fmt_sock(socket))
        else:
            self.__print_line(ypos_s + 1, "---")

        # Print current contents of the network buffer.
        self.__clear_line(ypos_b)
        self.__print_header(
            ypos_b, "{:<10} | {} -->".format(
                head_b, self.__data_format(self.__common_buffer_scroll)))
        self.__clear_line(ypos_b + 1)
        self.__print_buffer(ypos_b + 1, buff)

    def __print_common_data(self):
        """ Print active socket list and network buffer data.
		"""
        ypos_src = len(self.__main) + len(self.__pages["COMMON"]) + 5
        ypos_tgt = ypos_src + max(3, len(self.__sim.common.sources) + 2)
        ypos_ibf = ypos_tgt + max(3, len(self.__sim.common.targets) + 2)
        ypos_obf = ypos_ibf + 3
        self.__print_common_widget(
            ypos_src,
            ypos_ibf,
            "SOURCES",
            "IN BUFFER",
            self.__sim.common.sources,
            self.__sim.common.in_buffer,
            sources=True,
        )
        self.__print_common_widget(
            ypos_tgt,
            ypos_obf,
            "TARGETS",
            "OUT BUFFER",
            self.__sim.common.targets,
            self.__sim.common.out_buffer,
        )

    def __print_proc_list(self):
        """ Print list of process genomes or process data elements in PROCESS
		page. We can toggle between printing the genomes or the data elements
		by pressing the 'g' key.
		"""
        if self.__proc_gene_view:
            self.__print_proc_gene_list()
        else:
            self.__print_proc_data_list()

    def __proc_select_by_cursor(self):
        """ Select process located on address under cursor, if any exists.
		"""
        # First, calculate address under cursor.
        ypos = self.__curs_y
        xpos = self.__curs_x - World.PADDING
        line_size = self.size[1] - World.PADDING
        address = self.world.pos + ((
            (ypos * line_size) + xpos) * self.world.zoom)

        # Now, iterate all living processes and try to find one that owns the
        # calculated address.
        if self.__sim.lib.sal_mem_is_address_valid(address):
            for proc_id in range(self.__sim.lib.sal_proc_get_capacity()):
                if not self.__sim.lib.sal_proc_is_free(proc_id):
                    proc_data = (c_uint32 * len(self.proc_elements))()
                    self.__sim.lib.sal_proc_get_proc_data(
                        proc_id, cast(proc_data, POINTER(c_uint32)))
                    mb1a = proc_data[self.proc_elements.index("mb1a")]
                    mb1s = proc_data[self.proc_elements.index("mb1s")]
                    mb2a = proc_data[self.proc_elements.index("mb2a")]
                    mb2s = proc_data[self.proc_elements.index("mb2s")]

                    if (mb1a <= address < (mb1a + mb1s) or mb2a <= address <
                        (mb2a + mb2s)):
                        self.selected_proc = proc_id
                        break

    def __get_minimal(self):
        """ Generate set of data fields to be printed on minimal mode.
		"""
        return [
            ("cycle", self.__sim.lib.sal_main_get_cycle),
            ("epoch", self.__sim.lib.sal_main_get_epoch),
            ("procs", self.__sim.lib.sal_proc_get_count),
        ]

    def __print_minimal(self):
        """ Print minimal mode data fields.
		"""
        self.__print_line(1, "Salis - Mini mode")

        for i, field in enumerate(self.__minimal):
            field_1 = self.__data_format(field[1]())
            self.__print_line(i + 3, "{}: {:>10}".format(field[0], field_1))