Ejemplo n.º 1
0
    def Go(self):
        key2Direction = {\
            curses.KEY_UP    : Vector((-1, 0)),\
            curses.KEY_LEFT  : Vector(( 0,-1)),\
            curses.KEY_DOWN  : Vector((+1, 0)),\
            curses.KEY_RIGHT : Vector(( 0,+1)),\
        }
        null = Vector((0, 0))
        self.alive = True
        while self.alive:

            # Wait a little for keypress

            key = self.pad.getch()
            if key in key2Direction:
                if null != self.snakeDirection + key2Direction[key]:
                    self.snakeDirection = key2Direction[key]
            elif ord('q') == key:
                self.alive = False
                break
            self.Increment()

        # Nuke curses

        self.pad.keypad(0)
        curses.curs_set(1)
        curses.echo()
        curses.endwin()
        return
Ejemplo n.º 2
0
    def dir_list(self, path="/usr/share/snmp/mibs/"):
        self.window.clear()
        self.window.move(0,0)
        max_y, max_x = self.window.getmaxyx()
        beg_y, beg_x = self.window.getbegyx()
        cursor_y, cursor_x = self.window.getyx()

        #first output the [..] for parent dir
        self.window.addstr("../")
        cursor_y = cursor_y + 1
        self.window.move(cursor_y, 0)

        for dirname, dirnames, filenames in os.walk(path):

            for subdirname in dirnames:
                self.window.attron(curses.color_pair(5))
                self.window.addstr(subdirname[:25] + "/")
                self.window.attroff(curses.color_pair(5))
                cursor_y = cursor_y + 1
                self.window.move(cursor_y, 0)
            for file in filenames:
                if (cursor_y + 1 < max_y):
                    self.window.addstr(file)
                    cursor_y = cursor_y + 1
                    self.window.move(cursor_y, 0)

        self.window.move(0,0)
        self.window.chgat(curses.A_REVERSE)
        curses.curs_set(0)
Ejemplo n.º 3
0
 def init_curses(self):
     self.screen = curses.initscr()
     curses.noecho()
     curses.start_color()
     curses.cbreak()
     self.screen.keypad(0)
     curses.curs_set(0)
Ejemplo n.º 4
0
    def __init__(self, wallet, config, app=None):
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        curses.start_color()
        curses.use_default_colors()
        curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
        curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_CYAN)
        self.stdscr.keypad(1)
        self.stdscr.border(0)
        self.maxy, self.maxx = self.stdscr.getmaxyx()
        curses.curs_set(0)
        self.w = curses.newwin(10, 50, 5, 5)

        self.wallet = wallet
        self.config = config
        set_verbosity(False)
        self.tab = 0
        self.pos = 0
        self.popup_pos = 0

        self.str_recipient = ""
        self.str_description = ""
        self.str_amount = ""
        self.str_fee = ""
        
        self.wallet.interface.register_callback('updated', self.refresh)
        self.wallet.interface.register_callback('connected', self.refresh)
        self.wallet.interface.register_callback('disconnected', self.refresh)
        self.wallet.interface.register_callback('disconnecting', self.refresh)
        self.tab_names = [_("History"), _("Send"), _("Receive"), _("Contacts"), _("Wall")]
        self.num_tabs = len(self.tab_names)
Ejemplo n.º 5
0
    def __init__ (self):
        self.board = puzzle_2048()
        
        self.screen = curses.initscr()
        self.screen.keypad(1)
        self.screen.leaveok(0)
        curses.start_color()
        curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.noecho()
        curses.curs_set(0)
        
        self.screen.addstr(0,0,"To play: combine the tiles that match using the arrow keys, and press esc to exit")
        
        #Drawing the lines for the board
        self.screen.hline(5,10,"-", 29, curses.color_pair(1))
        self.screen.hline(9,10,"-", 29, curses.color_pair(1))
        self.screen.hline(13,10,"-", 29, curses.color_pair(1))
        self.screen.hline(17,10,"-", 29, curses.color_pair(1))
        self.screen.hline(21,10,"-", 29, curses.color_pair(1))
        self.screen.vline(5,10,"|", 17, curses.color_pair(1))
        self.screen.vline(5,17,"|", 17, curses.color_pair(1))
        self.screen.vline(5,24,"|", 17, curses.color_pair(1))
        self.screen.vline(5,31,"|", 17, curses.color_pair(1))
        self.screen.vline(5,38,"|", 17, curses.color_pair(1))
        
        self.Update_screen()

        self.run()
Ejemplo n.º 6
0
    def setup(self, stdscr):
        if logger.isEnabledFor(logging.DEBUG):
            logger.debug("GUI initialization")
        self.stdscr = stdscr

        try:
            curses.curs_set(0)
        except:
            pass

        curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
        curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_BLACK)
        curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
        curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_BLACK)
        curses.init_pair(6, curses.COLOR_BLACK, curses.COLOR_MAGENTA)
        curses.init_pair(7, curses.COLOR_BLACK, curses.COLOR_GREEN)
        curses.init_pair(8, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
        curses.init_pair(9, curses.COLOR_BLACK, curses.COLOR_GREEN)

        self.log = Log()
        # For the time being, supported players are mplayer and vlc.
        self.player = player.probePlayer()(self.log)

        self.stdscr.nodelay(0)
        self.setupAndDrawScreen()

        self.run()
Ejemplo n.º 7
0
    def receive_command(self):
        numlines, numcols = self.get_termsize()

        # clear command line
        cl = ""
        for i in range(numcols-1):
            cl += " "

        self.screen.addstr(numlines-1, 0, cl)

        # get command w/ visual response
        self.dontupdate.acquire()
        curses.echo()
        curses.curs_set(1)
        self.screen.addstr(numlines-1, 0, ":")
        command = self.screen.getstr(numlines-1, 1)
        curses.curs_set(0)
        curses.noecho()
        self.dontupdate.release()

        if command == 'q':
            self.running = False
        else:
            self.screen.addstr(numlines-1,0,"received unknown command:\"%s\"" %
                    (command,))
Ejemplo n.º 8
0
 def start_combat(self, unit):
     attacker = unit
     self.enemy = attacker
     status = self.var_handler.get('status_handler')
     io = self.var_handler.get('io_handler')
     command_processor = self.var_handler.get('command_processor')
     player = self.var_handler.get('player')
     hud = self.var_handler.get('hud_handler')
     self.combat = True
     io.output("You enter combat with a {0}".format(attacker.display_name), curses.color_pair(2))
     status.end_sequence()
     status.output("You are attacked by: {0}".format(attacker.display_name))
     hud.text_update()
     while self.combat:
         curses.curs_set(1)
         input = io.get_input(">>>>>>>:", curses.color_pair(2))
         if input.split(" ")[0] in self.commands:
             if "attack" in input:
                 output = self.attack(player, attacker)
             elif input == "run":
                 output = self.run(attacker)
             elif input.split(" ")[0] == "cast":
                 output = self.cast(input.split(" ")[1])
             else:
                 output = command_processor.receive_command(input)
             if attacker.state == "dead":
                 self.combat = False
                 self.enemy = None
                 output = (output[0] + "\nYou kill the {0}".format(attacker.display_name), output[1])
         else:
             output = ("You can't do that in combat", curses.color_pair(2))
         io.output(output[0], output[1])
         hud.text_update()
     status.start_sequence()
Ejemplo n.º 9
0
 def init(self):
     self.window = curses.initscr()
     self.initted = True
     self.ymax, self.xmax = self.window.getmaxyx()
     terminfo = curses.longname()
     assert '256' in terminfo  # your env TERM must be xterm-256color!
     assert curses.has_colors()
     curses.start_color()
     curses.use_default_colors()
     ctr = 1
     for fg in CLRS:
         for bg in CLRS:
             if ctr <= curses.COLORS-1 and fg != bg:
                 curses.init_pair(ctr, CLRS[fg], CLRS[bg])
                 pairs[(fg,bg)] = curses.color_pair(ctr)
                 ctr += 1
     curses.meta(1)
     curses.noecho()
     curses.cbreak()
     curses.curs_set(0)
     curses.delay_output(0)
     curses.mouseinterval(150)
     availmask,_ = curses.mousemask(curses.ALL_MOUSE_EVENTS)
     assert availmask != 0  # mouse must be available!
     self.window.leaveok(1)
     self.window.scrollok(0)
     self.window.keypad(1)
     if NONBLOCKING:
         self.window.nodelay(1)
         self.window.timeout(NONBLOCKING_TIMEOUT)
     else:
         self.window.nodelay(0)
         self.window.timeout(-1)
     self.window.refresh()
Ejemplo n.º 10
0
    def __init__(self, stdscr, encoding=None):
        self.formatted_rows = None
        self.torrent_names = None
        self.cursel = 1
        self.curoff = 1 # TODO: this should really be 0 indexed
        self.column_string = ""
        self.popup = None
        self.messages = deque()
        self.marked = []
        self.last_mark = -1
        self._sorted_ids = None
        self._go_top = False

        self._curr_filter = None
        self.entering_search = False
        self.search_string = None
        self.cursor = 0

        self.coreconfig = component.get("ConsoleUI").coreconfig

        self.legacy_mode = None

        self.__status_dict = {}
        self.__torrent_info_id = None

        BaseMode.__init__(self, stdscr, encoding)
        component.Component.__init__(self, "AllTorrents", 1, depend=["SessionProxy"])
        curses.curs_set(0)
        self.stdscr.notimeout(0)

        self.__split_help()
        self.update_config()

        component.start(["AllTorrents"])

        self._info_fields = [
            ("Name",None,("name",)),
            ("State", None, ("state",)),
            ("Down Speed", format_utils.format_speed, ("download_payload_rate",)),
            ("Up Speed", format_utils.format_speed, ("upload_payload_rate",)),
            ("Progress", format_utils.format_progress, ("progress",)),
            ("ETA", deluge.common.ftime, ("eta",)),
            ("Path", None, ("save_path",)),
            ("Downloaded",deluge.common.fsize,("all_time_download",)),
            ("Uploaded", deluge.common.fsize,("total_uploaded",)),
            ("Share Ratio", format_utils.format_float, ("ratio",)),
            ("Seeders",format_utils.format_seeds_peers,("num_seeds","total_seeds")),
            ("Peers",format_utils.format_seeds_peers,("num_peers","total_peers")),
            ("Active Time",deluge.common.ftime,("active_time",)),
            ("Seeding Time",deluge.common.ftime,("seeding_time",)),
            ("Date Added",deluge.common.fdate,("time_added",)),
            ("Availability", format_utils.format_float, ("distributed_copies",)),
            ("Pieces", format_utils.format_pieces, ("num_pieces","piece_length")),
            ]

        self.__status_keys = ["name","state","download_payload_rate","upload_payload_rate",
                             "progress","eta","all_time_download","total_uploaded", "ratio",
                             "num_seeds","total_seeds","num_peers","total_peers", "active_time",
                             "seeding_time","time_added","distributed_copies", "num_pieces", 
                             "piece_length","save_path"]
Ejemplo n.º 11
0
 def on_gain_focus(self):
     self.state = 'current'
     curses.curs_set(1)
     tab = self.core.get_tab_by_name(safeJID(self.name).bare, MucTab)
     if tab and tab.joined and config.get_by_tabname('send_chat_states',
             self.general_jid,) and not self.input.get_text() and self.on:
         self.send_chat_state('active')
Ejemplo n.º 12
0
    def init_and_run(self, stdscr):
        """ called by ncurses.wrapper """
        self.stdscr = stdscr

        try:
            curses.curs_set(0)
        except:
            pass

        curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
        curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)
        curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
        curses.init_pair(5, curses.COLOR_RED, curses.COLOR_BLACK)

        self.max_y, self.max_x = stdscr.getmaxyx()

        self.head_win = curses.newwin(4, self.max_x, 0, 0)
        self.body_win = curses.newwin(self.max_y-4, self.max_x, 4, 0)

        self.init_head_win()
        self.init_body_win()
        curses.doupdate()

        self.run()
Ejemplo n.º 13
0
def main(argv):
    global mines, board

    args = map(int, argv[1:])
    xw = int(args[0]) if args else 20
    yw = int(args[1]) if len(args) > 1 else xw / 2
    mines = int(args[2]) if len(args) > 2 else int(xw * yw / 20)

    board = [' ' * xw for i in range(yw)]
    mines = {(randint(0, xw), randint(0, yw)) : True for i in range(mines)}

    scr = curses.initscr()
    scr.keypad(1)
    curses.curs_set(0)
    curses.noecho()
    curses.mousemask(curses.ALL_MOUSE_EVENTS)

    while True:
        scr.clear()

        k = scr.getch()
        scr.addstr(yw + 2, 0, ': ' + str(k))
        if k == 27:
            break
        elif k == curses.KEY_MOUSE:
            _, x, y, z, bstate = curses.getmouse()
            scr.addstr(y, x, ' '.join(str(v) for v in (z, bstate)))
        elif k == curses.KEY_DC:
            boom(scr)

    scr.clear()
    curses.endwin()
Ejemplo n.º 14
0
def setup():
    """
     sets environment up and creates main window
     :returns: the main window object
    """
    # setup the console
    mmask = curses.ALL_MOUSE_EVENTS # for now accept all mouse events
    main = curses.initscr()         # get a window object
    y,x = main.getmaxyx()           # get size
    if y < 24 or x < 80:            # verify minimum size rqmts
        raise RuntimeError("Terminal must be at least 80 x 24")
    curses.noecho()                 # turn off key echoing
    curses.cbreak()                 # turn off key buffering
    curses.mousemask(mmask)         # accept mouse events
    initcolors()                    # turn on and set color pallet
    main.keypad(1)                  # let curses handle multibyte special keys
    main.clear()                    # erase everything
    banner(main)                    # write the banner
    mainmenu(main)                  # then the min and menu
    main.attron(CPS[RED])           # make the border red
    main.border(0)                  # place the border
    main.attroff(CPS[RED])          # turn off the red
    curses.curs_set(0)              # hide the cursor
    main.refresh()                  # and show everything
    return main
Ejemplo n.º 15
0
    def __init__(self, evm):
        self.evm = evm
        evm.RegisterListener(self)
        # first we must create a window object; it will fill the whole screen
        self.scrn = curses.initscr()
        # turn off keystroke echo
        curses.noecho()
        # keystrokes are honored immediately, rather than waiting for the
        # user to hit Enter
        curses.cbreak()

        self.scrn.keypad(1)

        self.scrn.nodelay(1)
        # start color display (if it exists; could check with has_colors())
        curses.start_color()

        curses.mousemask(curses.BUTTON1_PRESSED)

        curses.curs_set(0)

        # clear screen
        self.scrn.clear()

        i = 1
        for color_background in self.list_of_colors:
            for color_foreground in self.list_of_colors:
                curses.init_pair(i, color_foreground, color_background)
                self.mapping[color_foreground, color_background] = i
                i += 1

        # implement the actions done so far (just the clear())
        self.scrn.refresh()
Ejemplo n.º 16
0
def main():
    """
    Main entry point for gunicorn_console.
    """
    # Set up curses.
    stdscr = curses.initscr()
    curses.start_color()
    curses.init_pair(1, foreground_colour, background_colour)
    curses.noecho()
    stdscr.keypad(True)
    stdscr.nodelay(True)
    try:
        curses.curs_set(False)
    except:
        pass
    try:
        # Run main event loop until quit.
        while True:
            try:
                update_gunicorns()
                handle_keypress(stdscr)
                display_output(stdscr)
                curses.napms(int(screen_delay * 1000))
            except KeyboardInterrupt:
                break
    finally:
        # Tear down curses.
        curses.nocbreak()
        stdscr.keypad(False)
        curses.echo()
        curses.endwin()
Ejemplo n.º 17
0
    def __init__(self, player_sub):
        self.player_sub = player_sub
        # self.sea = sea
        self.display_screen = ''

        # setlocale enables UTF chars
        # see: https://docs.python.org/2/library/curses.html
        locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
        self.strcode = locale.getpreferredencoding()
        # print(self.strcode)
        screen = curses.initscr()

        self.screen = screen

        # Applications will also commonly need to react to keys instantly, without requiring the Enter key
        # to be pressed; this is called cbreak mode, as opposed to the usual buffered input mode.
        curses.cbreak()

        # Usually curses applications turn off automatic echoing of keys to the screen, in order to be able to read
        #  keys and only display them under certain circumstances. This requires calling the noecho() function.
        curses.noecho()


        screen.nodelay(1)

        curses.curs_set(0)
        screen.keypad(True)

        curses.start_color()
        curses.use_default_colors()
Ejemplo n.º 18
0
	def end_interface(self): # {{{
		self.stdscr.erase()
		self.stdscr.refresh()
		curses.curs_set(1)
		curses.nocbreak()
		curses.echo()
		curses.endwin()
Ejemplo n.º 19
0
	def start_interface(self): # {{{
		self.stdscr = curses.initscr()
		curses.noecho()
		curses.cbreak()
		self.stdscr.keypad(1)
		curses.curs_set(0)
		self.mainloop()
Ejemplo n.º 20
0
def main(stdscr):
    """Main function"""

    # Let the cursor be invisible
    curses.curs_set(False)

    x = 0
    y = 0

    while True:
        # Clear screen
        stdscr.clear()

        # Print a message
        stdscr.addstr('Press any key (q to quit).')
        stdscr.addstr(3, 0, "{},{}".format(x, y))

        # Display the message
        stdscr.refresh()

        # Wait for a key
        c = stdscr.getch()

        if c == ord('q'):
            break  # Exit the while loop
        elif c == curses.KEY_DOWN:
            y -= 1
        elif c == curses.KEY_UP:
            y += 1
        elif c == curses.KEY_LEFT:
            x -= 1
        elif c == curses.KEY_RIGHT:
            x += 1
Ejemplo n.º 21
0
    def setScreen(self, scr):
        """
		Set the screen and create the different windows 
		"""
        log(self.__class__.__name__, sys._getframe().f_code.co_name)
        self.stdscr = scr
        if self.stdscr != None:
            curses.curs_set(0)
            curses.start_color()
            curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
            curses.halfdelay(2 * 10)

            # setup all windows
            self.mainWindow = MainDisplay(0, self.stdscr)

            # self.stdscr.hline(self.WinPositions.headerBlock+self.headerWindow.getmaxyx()[0], 0, '-', 130)
            self.jobWindow = JobDisplay(0, self.stdscr)
            # self.stdscr.hline(self.WinPositions.summaryBlock+self.jobsWindow.getmaxyx()[0], 0, '-', 130)
            ##self.stdscr.hline(self.WinPositions.submitBlock+self.submitWindow.getmaxyx()[0], 0, '-', 130)

            ##self.erroWindow = curses.newwin(5, self.stdscr.getmaxyx()[1], self.WinPositions.debugBlock, 0)
            ##self.finalWindow = curses.newwin(3, self.stdscr.getmaxyx()[1], self.WinPositions.finalizeBlock, 0)
            ##self.finalWindow.addstr(0, 50, "Finalization job result")
            ##self.stdscr.hline(self.WinPositions.finalizeBlock+self.submitWindow.getmaxyx()[0], 0, '-', 130)
            ##
            ##self.stdscr.nooutrefresh()
            ##self.repaint()

            self.mainWindow.generate()
            self.jobWindow.generate()
            self.stdscr.refresh()
            self.activateMainWindow()
Ejemplo n.º 22
0
    def __init__(self, stdscr, args):
        self._stdscr = stdscr
        self._dbase = database.load_file(args.database,
                                         encoding=args.encoding,
                                         frame_id_mask=args.frame_id_mask,
                                         strict=not args.no_strict)
        self._single_line = args.single_line
        self._filtered_sorted_message_names = []
        self._filter = ''
        self._compiled_filter = None
        self._formatted_messages = {}
        self._playing = True
        self._modified = True
        self._show_filter = False
        self._queue = Queue()
        self._nrows, self._ncols = stdscr.getmaxyx()
        self._received = 0
        self._discarded = 0
        self._basetime = None

        stdscr.nodelay(True)
        curses.use_default_colors()
        curses.curs_set(False)
        curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)
        curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_CYAN)

        bus = self.create_bus(args)
        self._notifier = can.Notifier(bus, [self])
Ejemplo n.º 23
0
	def __init__(self):
		curses.curs_set(0)
		curses.noecho()
		self.win=curses.newwin(LINES-4,COLS-4,2,2)
		self.win.clear()
		self.win.refresh()
		self.win.keypad(1)
Ejemplo n.º 24
0
def main():
    global screen
    screen = curses.initscr()
    init_screen()

    screen.refresh()

    curses.curs_set(0)

    import sys
    if len(sys.argv) > 1 and sys.argv[1] == "-s":
        screen.getch()
    else:
        while True:
            try:
                c = screen.getch()
                if c == ord('n'):
                    curses.endwin()
                    show_netinfo()
                    screen = curses.initscr()
                    init_screen()
                screen.refresh()
                if c == 27 :
                   curses.endwin()
                   return 0
            except KeyboardInterrupt:
                pass
	curses.endwin()
Ejemplo n.º 25
0
def main(scr):
    curses.curs_set(False)

    curses.start_color()
    for i in range(1, 16):
        curses.init_pair(i, i, curses.COLOR_BLACK)

    scry, scrx = scr.getmaxyx()
    pady = scry * 2
    padx = scrx * 2

    pad = curses.newpad(pady, padx)
    pad.nodelay(True)
    mandel(pad)

    oy = 1
    ox = 0

    while True:
        pad.refresh(oy, ox, 0, 0, scry-1, scrx-1)
        key = pad.getch()
        if key in (ord('q'), ord('Q')):
            break
        elif key in (ord('w'), curses.KEY_UP):
            oy = max(oy - 1, 0)
        elif key in (ord('s'), curses.KEY_DOWN):
            oy = min(oy + 1, pady - scry - 1)
        elif key in (ord('a'), curses.KEY_LEFT):
            ox = max(ox - 2, 0)
        elif key in (ord('d'), curses.KEY_RIGHT):
            ox = min(ox + 2, padx - scrx)
        elif key == curses.KEY_RESIZE:
            scry, scrx = scr.getmaxyx()
Ejemplo n.º 26
0
 def close(self):
     curses.curs_set(1)
     self.screen.immedok(False)
     self.screen.keypad(0)
     curses.nocbreak()
     curses.echo()
     curses.endwin()
Ejemplo n.º 27
0
 def __init__(self, win, interface, level):
     self.line_pos = 2
     self.first_result = self.selected_result = 0 
     self.stdscr = win
     self.results = []
     self.wifispy = WifiSpy.WifiSpy(interface)
             
     # Configure screen
     curses.curs_set(0)
     self.stdscr.nodelay(1)
     self.stdscr.timeout(0)
     
     # Put the interface it in managed mode
     # to perform the scanning
     self.wifispy.level = level
     self.wifispy.set_iface_in_managed_mode()      
     
     # Show scanning message
     self.stdscr.box()
     self.stdscr.addstr(curses.LINES/2, curses.COLS/2 - 5, "Scanning...",
                             curses.A_BOLD)
     self.stdscr.refresh()
     
     # Get and populate results
     self.results = self.wifispy.get_scanning_results()
     
     # Rebuild the screen with the results
     self.__clear_screen()
     self.__build_screen(self.first_result, True)                
     self.__highlight_line(self.line_pos, self.selected_result)
Ejemplo n.º 28
0
 def killWindow(self):
     """restore terminal window"""
     curses.nocbreak()
     self.stdscr.keypad(0)
     curses.echo()
     curses.curs_set(1)
     curses.endwin()
Ejemplo n.º 29
0
    def __init__(self, stdscr, username, filename):
        """Create the GUI with curses screen and optional filename to load."""
        self._stdscr = stdscr
        self._COLOR_NUM = 7
        self._username = username

        self._COL_MAX = 50
        self._ROW_MAX = 20 

        # if filename already exists, try to load from it
        text = ''
        if filename != None and os.path.isfile(filename):
            with open(filename) as f:
                text = f.read()

        self._filename = filename
        self._buf = Buffer(text)
        self._row = 0
        self._col = 0
        self._scroll_top = 0 # the first line number in the window
        self._mode = 'normal'
        self._message = ''
        self._will_exit = False

        self._pipe = None
        self._cooperators = []

        curses.curs_set(0)
Ejemplo n.º 30
0
    def initialize(self):
        """initialize curses, then call setup (at the first time) and resize."""
        self.win.leaveok(0)
        self.win.keypad(1)
        self.load_mode = False

        curses.cbreak()
        curses.noecho()
        curses.halfdelay(20)
        try:
            curses.curs_set(int(bool(self.settings.show_cursor)))
        except:
            pass
        curses.start_color()
        curses.use_default_colors()

        self.settings.signal_bind('setopt.mouse_enabled', _setup_mouse)
        _setup_mouse(dict(value=self.settings.mouse_enabled))

        if not self.is_set_up:
            self.is_set_up = True
            self.setup()
            self.win.addstr("loading...")
            self.win.refresh()
            self._draw_title = curses.tigetflag('hs') # has_status_line
        self.update_size()
        self.is_on = True

        if self.settings.update_tmux_title:
            sys.stdout.write("\033kranger\033\\")
            sys.stdout.flush()
Ejemplo n.º 31
0
    def edit(self, initial_input=""):
        old_curs_state = 0

        try:
            old_curs_state = curses.curs_set(1)
        except:
            pass

        for char in list(initial_input):
            self.do_command(ord(char))
        self.poll_function(self.count())

        abort = False
        while 1:
            insert = False
            ch = self.win.getch()

            if ch == curses.ascii.DEL:
                self.do_command(curses.ascii.BS)
            elif ch == curses.KEY_ENTER or ch == 10:
                break
            elif ch == curses.ascii.ESC:
                abort = True
                break
            elif ch == curses.ascii.TAB:
                cursor_position = self.win.getyx()
                x = cursor_position[1]
                last_word = ""
                while True:
                    x -= 1
                    c = chr(
                        curses.ascii.ascii(self.win.inch(
                            cursor_position[0], x)))
                    if c == " ":
                        if (len(last_word) == 0) and (x > 0):
                            continue
                        else:
                            break
                    last_word = c + last_word
                    if x == 0:
                        break
                self.win.move(cursor_position[0], cursor_position[1])
                guess_source = None
                if helpers.url_regex.match(
                        last_word):  # this is a URL, shorten it
                    shorturl = helpers.ur1ca_shorten(last_word)
                    for n in xrange(len(last_word)):
                        self.win.move(self.win.getyx()[0],
                                      self.win.getyx()[1] - 1)
                        self.delch()
                    for char in shorturl:
                        self.do_command(ord(char))
                elif last_word[0] == "@" and hasattr(config.session_store,
                                                     "user_cache"):
                    last_word = last_word[1:]
                    guess_source = getattr(config.session_store, "user_cache")
                elif last_word[0] == "!" and hasattr(config.session_store,
                                                     "group_cache"):
                    last_word = last_word[1:]
                    guess_source = getattr(config.session_store, "group_cache")
                elif last_word[0] == "#" and hasattr(config.session_store,
                                                     "tag_cache"):
                    last_word = last_word[1:]
                    guess_source = getattr(config.session_store, "tag_cache")
                elif last_word[0] == "/" and hasattr(config.session_store,
                                                     "commands"):
                    last_word = last_word[1:]
                    guess_source = getattr(config.session_store, "commands")
                elif hasattr(
                        config.session_store,
                        "user_cache"):  # if no special char, assume username
                    guess_source = getattr(config.session_store, "user_cache")
                if guess_source is not None:
                    if config.config["tab_complete_mode"] == "exact":
                        possible_guesses = [
                            user for user in guess_source
                            if user[:len(last_word)] == last_word
                        ]
                        guess = helpers.find_longest_common_start(
                            possible_guesses)
                        if len(guess) > len(last_word):
                            for char in guess[len(last_word):]:
                                self.do_command(ord(char))
                        elif len(possible_guesses) > 0:
                            self.poll_function(possible_guesses)
                    else:
                        possible_guesses = helpers.find_fuzzy_matches(
                            last_word, guess_source)
                        common_guess = helpers.find_longest_common_start(
                            possible_guesses)
                        if len(common_guess) != 0 and len(
                                helpers.find_fuzzy_matches(
                                    last_word, [
                                        common_guess,
                                    ])) > 0:
                            self.win.move(self.win.getyx()[0],
                                          self.win.getyx()[1] - len(last_word))
                            for i in xrange(len(last_word)):
                                self.delch()
                            for char in common_guess:
                                self.do_command(ord(char))
                        if len(possible_guesses) >= 2:
                            self.poll_function(possible_guesses)
            elif ch == curses.KEY_HOME:
                self.win.move(0, 0)
            elif ch == curses.KEY_END:
                for y in range(self.maxy + 1):
                    if y == self.maxy:
                        self.win.move(y, self._end_of_line(y))
                        break
                    if self._end_of_line(y + 1) == 0:
                        self.win.move(y, self._end_of_line(y))
                        break
            elif ch == curses.KEY_BACKSPACE or ch == curses.ascii.ctrl(
                    ord("h")):
                cursor_y, cursor_x = self.win.getyx()
                if cursor_x == 0:
                    if cursor_y == 0:
                        continue
                    else:
                        self.win.move(cursor_y - 1, self.maxx)
                else:
                    self.win.move(cursor_y, cursor_x - 1)
                self.delch()
            elif ch == curses.KEY_DC or ch == curses.ascii.ctrl(ord("d")):
                self.delch()
            elif ch == curses.ascii.ctrl(
                    ord("u")):  # delete entire line up to the cursor
                cursor_y, cursor_x = self.win.getyx()
                self.win.move(cursor_y, 0)
                for char_count in xrange(0, cursor_x):
                    self.delch()
            elif ch == curses.ascii.ctrl(
                    ord("w")
            ):  # delete all characters before the current one until the beginning of the word
                cursor_y, cursor_x = self.win.getyx()
                x, y = cursor_x, cursor_y
                only_spaces_so_far = True
                while True:
                    if x == 0:
                        if y == 0:
                            break
                        else:
                            y -= 1
                            x = self.maxx
                    else:
                        x -= 1
                    if curses.ascii.ascii(self.win.inch(y, x)) != ord(" "):
                        self.win.move(y, x)
                        self.delch()
                        only_spaces_so_far = False
                    else:
                        if only_spaces_so_far:
                            self.win.move(y, x)
                            self.delch()
                        else:
                            if x == self.maxx:
                                self.win.move(y + 1, 0)
                            else:
                                self.win.move(y, x + 1)
                            break
            elif ch > 127 and ch <= 256:
                cursor_y, cursor_x = self.win.getyx()

                if cursor_y < self.maxy:
                    overhang_ch = self.win.inch(cursor_y, self.maxx)
                    if overhang_ch <= 127:
                        self.win.insch(cursor_y + 1, 0, overhang_ch)
                    elif overhang_ch <= 256:
                        for c in self.unicode_demangle(overhang_ch):
                            self.win.insch(cursor_y + 1, 0, ord(c))

                for c in self.unicode_demangle(ch):
                    self.win.insch(cursor_y, cursor_x, ord(c))

                if cursor_x < self.maxx:
                    self.win.move(cursor_y, cursor_x + 1)
                elif cursor_y < self.maxy:
                    self.win.move(cursor_y + 1, 0)

            elif ch <= 127 and chr(ch) in string.printable:
                cursor_y, cursor_x = self.win.getyx()
                if cursor_y < self.maxy:
                    overhang_ch = self.win.inch(cursor_y, self.maxx)
                    if overhang_ch <= 127:
                        self.win.insch(cursor_y + 1, 0, overhang_ch)
                    elif overhang_ch <= 256:
                        for c in self.unicode_demangle(overhang_ch):
                            self.win.insch(cursor_y + 1, 0, ord(c))

                self.win.insch(cursor_y, cursor_x, ch)

                if cursor_x < self.maxx:
                    self.win.move(cursor_y, cursor_x + 1)
                elif cursor_y < self.maxy:
                    self.win.move(cursor_y + 1, 0)
            elif not ch:
                continue
            elif not self.do_command(ch):
                break

            self.poll_function(self.count())
            self.win.refresh()

        try:
            curses.curs_set(
                old_curs_state
            )  # try to restore the cursor's state before returning to normal operation
        except:
            pass
        if abort == False:
            return self.gather()
        else:
            self.win.clear()
            self.win.refresh()
            return None
def simulate_battle(cave_data, elf_attack_power):
    if CURSES:
        curses.curs_set(0)
        field = curses.newwin(40, 40, 1, 1)
        curses.start_color()
        curses.use_default_colors()
        for i in range(0, curses.COLORS):
            curses.init_pair(i + 1, i, -1)

    cm = CaveMap(cave_data, elf_attack_power)

    stime = time.time()
    for i in range(1000):

        if CURSES:
            field.clear()
            cm.draw(field)
            curses.curs_set(0)

            for unit in cm.units:
                if unit.is_alive():
                    if unit.unit_type == 'E':
                        field.addstr(unit.y, unit.x, unit.unit_type,
                                     curses.color_pair(3))
                    else:
                        field.addstr(unit.y, unit.x, unit.unit_type,
                                     curses.color_pair(2))

            field.addstr(33, 0,
                         'Round {} took {} s'.format(i,
                                                     time.time() - stime))
            field.refresh()
            #field.getch()
            stime = time.time()
        else:
            print('Round:', i)
            print(cm)

        cm.units.sort(key=lambda unit: (unit.y, unit.x))
        for unit in cm.units:
            if unit.is_alive():
                targets = unit.get_targets(cm.units)
                if targets:
                    target = unit.get_target_in_range(targets)
                    if target:
                        unit.attack(target)
                    else:
                        path = unit.get_path_to_closest_target(cm)
                        if path:
                            unit.coordinate = path[-2].coordinate

                            target = unit.get_target_in_range(targets)
                            if target:
                                unit.attack(target)
                else:
                    hp_sum = 0
                    for unit in cm.units:
                        if unit.is_alive():
                            hp_sum += unit.hp

                    if CURSES:
                        field.clear()
                        cm.draw(field)
                        curses.curs_set(0)
                        for unit in cm.units:
                            if unit.is_alive():
                                if unit.unit_type == 'E':
                                    field.addstr(unit.y, unit.x,
                                                 unit.unit_type,
                                                 curses.color_pair(3))
                                else:
                                    field.addstr(unit.y, unit.x,
                                                 unit.unit_type,
                                                 curses.color_pair(2))
                        field.addstr(
                            33, 0, 'Round {} took {} s'.format(
                                i,
                                time.time() - stime))
                        field.addstr(34, 0,
                                     'Combat ended after {} rounds'.format(i))
                        field.addstr(35, 0,
                                     'Remaining hit points: {}'.format(hp_sum))
                        field.addstr(36, 0, 'Outcome: {}'.format(i * hp_sum))
                        field.addstr(
                            37, 0, 'Dead elfs: {}'.format(
                                check_for_dead_elfs(cm.units)))
                        field.refresh()
                        field.getch()
                    else:
                        print('Combat ended after {} rounds'.format(i))
                        print(cm)
                        print('Remaining hit points: {}'.format(hp_sum))
                        print(('Outcome: {}'.format(i * hp_sum)))

                    return cm
    return None
Ejemplo n.º 33
0
def main(stdscr):
    curses.curs_set(0) # hide cursor
    curses.init_pair(1,curses.COLOR_YELLOW,curses.COLOR_BLACK) # Ubuntu (Yellow?)
    curses.init_pair(2,curses.COLOR_BLUE,curses.COLOR_BLACK) # Kubuntu Blue on Black
    curses.init_pair(3,curses.COLOR_RED,curses.COLOR_BLACK) # Edubuntu
    curses.init_pair(4,curses.COLOR_CYAN,curses.COLOR_BLACK) # Xubuntu
    curses.init_pair(5,curses.COLOR_BLACK,curses.COLOR_GREEN) # Pass
    curses.init_pair(6,curses.COLOR_BLACK,curses.COLOR_RED) # Fail (This could be reverse edubuntu)

    """while (1):
        try:
            server.connect((HOST, PORT))
            break
        except socket.error:
            # Since non-blocking, if it doesn't work immediately, EINPROGRESS
            # Subsequent calls (while in progress) give EALREADY
            # There are other errors (actual errors), we may want to check them
            pass"""

    stdscr.bkgd('*', curses.A_REVERSE )
    win_sidebar = curses.newwin(21,15,0,0)
    # Set up sidebar (static stuff) UGLY CHANGE!!!!!!!!!!!!! - JB
    win_sidebar.border(' ','|',' ',' ',' ',curses.ACS_VLINE,' ',curses.ACS_VLINE) # Righthand Line
    win_sidebar.addstr(0,0,"    Queue     ", curses.A_UNDERLINE)
    win_sidebar.addstr(1,3,"F V A T P")
    for i in range(1,10):
        win_sidebar.addstr(i+1,1,str(i))
    for i in range(10,20):
        win_sidebar.addstr(i+1,0,str(i))
    # done with sidebar static stuff

    win_topbar = curses.newwin(4,65,0,15)
    # set up top bar (static stuff)
    win_topbar.border(' ',' ',' ','-',' ',' ','-','-') # Bottom Line
    for i in range(1,6):
        for j in range(0,3):
            win_topbar.addstr(j,i*11-1,'|') # Dividers between clients
        win_topbar.addstr(0,i*11,' ******** ') # blank client names (2-6)
    win_topbar.addstr(0,0,' ******** ') # blank client name (1)
    # done with top bar static stuff

    # Now we set up the four (up to five) tabs
    tabs.append(curses.newwin(17,65,4,15))  # These panel references are
    tabs.append(curses.newwin(17,65,4,15))  # important, without them
    tabs.append(curses.newwin(17,65,4,15))  # our panels get GC'd
    tabs.append(curses.newwin(17,65,4,15))  # Using Win instead?

    # Put some test stuff in the tabs
    draw_menu_order(tabs[0])
    draw_menu_packages(tabs[1])
    draw_menu_clients(tabs[2])
    draw_menu_queue(tabs[3])

    # initial updates
    #get_queue()
    #get_clients()
    update_package_names()
    

    global active_tab
    global is_running
    global keysdown
    global blankkeys
    global frame_count
    keysdown = blankkeys
    active_tab = 0
    stale_queue = True
    stale_client = True
    stdscr.nodelay(1)
    curses.meta(1)
    while(is_running):
        
        
        stdscr.noutrefresh()
        win_sidebar.noutrefresh()
        win_topbar.noutrefresh()
        tabs[active_tab].touchwin() # Have to make them think this is modified
        tabs[active_tab].noutrefresh()
        curses.doupdate()
        

        """# begin socket stuff
        try: #try RX
            if len(server.recv(1024,socket.MSG_PEEK)) == 0:
                server.close() # Bad connection, We likely want to reconnect
                continue
            # otherwise: do stuff with inbuf
            inbuf = inbuf + server.recv(1024)
        except socket.error: # Excepion (no data RX, but connection still there)
            pass

        if len(outbuf) > 0: # if we have stuff to send
            try: # try TX
                sent = server.send(outbuf)
                outbuf = outbuf[sent:]
            except socket.error: # We only want to catch SIGPIPE (server disconnect)
                pass
        # done with socket stuff"""


        # Handle Communication
        if stale_queue:
            update_display_queue(win_sidebar)
            stale_queue = False
        if stale_client:
            update_display_clients(win_topbar)
            stale_client = False


        handle_input(stdscr)
        update_tab(active_tab)
        
        #clear keys
        clear_keys()
        frame_count += 1
Ejemplo n.º 34
0
 def set_cursor(self, x):
     try:
         curses.curs_set(x)
     except Exception:
         pass
Ejemplo n.º 35
0
import time
import locale
import curses
import sys
from pySpacebrew.spacebrew import Spacebrew

# set the encoding to use for the terminal string
locale.setlocale(locale.LC_ALL, '')
code = locale.getpreferredencoding()

# initialize the terminal display
stdscr = curses.initscr()
stdscr.keypad(1)
curses.noecho()  # turn off echo
curses.curs_set(0)  # turn off cursor

# get app name and server from query string
name = "pyString Example"
server = "sandbox.spacebrew.cc"
local = "localhost"

for cur_ele in sys.argv:
    if "name" in cur_ele:
        name = cur_ele[5:]
    if "server" in cur_ele:
        server = cur_ele[7:]

# configure the spacebrew client
brew = Spacebrew(name, server=local)
brew.addPublisher("chat outgoing", "string")
brew.addSubscriber("chat incoming", "string")
Ejemplo n.º 36
0
# SNAKES GAME
# Use ARROW KEYS to play, SPACE BAR for pausing/resuming and Esc Key for exiting

import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
from random import randint

curses.initscr()
win = curses.newwin(20, 60, 0, 0)
win.keypad(1)
curses.noecho()
curses.curs_set(0)
win.border(0)
win.nodelay(1)

key = KEY_RIGHT  # Initializing values
score = 0

snake = [[4, 10], [4, 9], [4, 8]]  # Initial snake co-ordinates
food = [10, 20]
wall = [15, 18]
walls = []
walls.append(wall)  # First food co-ordinates

win.addch(food[0], food[1], '*')
win.addch(walls[0][0], walls[0][1], '@')  # Prints the food

while key != 27:  # While Esc key is not pressed
    win.border(0)
    win.addstr(0, 2, 'Score : ' + str(score) + ' ')  # Printing 'Score' and
    win.addstr(0, 27, ' SNAKE ')  # 'SNAKE' strings
Ejemplo n.º 37
0
import curses

screen = curses.initscr()
curses.nocbreak()  # Turn off cbreak mode
curses.echo()  # Turn echo back on
curses.curs_set(1)  # Turn cursor back on
# If initialized like `my_screen = curses.initscr()`
screen.keypad(0)  # Turn off keypad keys
Ejemplo n.º 38
0
 def show_cursor(self, cursor_on):
     """Change visibility of cursor."""
     self.cursor_visible = cursor_on
     curses.curs_set(self.cursor_shape if cursor_on else 0)
Ejemplo n.º 39
0
def chat_page(screen: curses.window):
    global running
    user_typing = False
    read_str = ""
    rendered_display_chats = 0
    display_chats: List[str] = []
    while running:
        key = screen.getch()
        if key == curses.KEY_MOUSE:
            _, mx, my, *_ = curses.getmouse()
            if my == center(screen)[0] * 2 - 2:
                user_typing = True
            else:
                user_typing = False
        elif key == 27 or key == curses.KEY_BREAK:
            running = False
        screen.erase()
        start_index = -1
        end_index = -(center(screen)[0] * 2 - 3) - 1
        box2 = screen.subwin(3,
                             center(screen)[1] * 2,
                             center(screen)[0] * 2 - 3, 0)
        box2.box()

        start_render_from = rendered_display_chats
        rendered_display_chats = len(chats)
        width_limit = center(screen)[1] * 2 - 2
        for chat in chats[start_render_from:]:
            parts = textwrap.fill(chat, width_limit).split("\n")
            display_chats.extend(parts)
        for index, msg in enumerate(display_chats[start_index:end_index:-1]):
            y = center(screen)[0] * 2 - 4 - index
            x = 0
            screen.addstr(y, x, msg)
        if user_typing:
            curses.curs_set(1)
            screen.move(
                center(screen)[0] * 2 - 2,
                len(read_str[-(center(screen)[1] - 2) * 2:]))
            if key:
                if key == curses.KEY_ENTER or key in (10, 13):
                    if read_str:
                        send_this.append(read_str)
                        read_str = ""
                elif key == curses.KEY_BACKSPACE or key == 8:
                    if read_str:
                        read_str = read_str[:-1]
                else:
                    if curses.ascii.isascii(key):
                        letter = chr(key)
                        read_str += letter
            screen.move(
                center(screen)[0] * 2 - 2,
                len(read_str[-(center(screen)[1] - 2) * 2:]))
        else:
            screen.move(0, center(screen)[1] * 2 - 1)
            if key == ord("q"):
                running = False
            elif key == ord("w") or key == curses.KEY_ENTER or key in (10, 18):
                user_typing = True
        screen.addstr(
            center(screen)[0] * 2 - 2, 1,
            read_str[-(center(screen)[1] - 2) * 2 - 1:])
        screen.refresh()
Ejemplo n.º 40
0
def drawBoard(stdscr):
    curses.noecho()
    curses.curs_set(0)
    stdscr.keypad(True)
    stdscr.clear()
    curses.start_color()
    curses.use_default_colors()
    curses.init_color(11, 1000, 0, 0)
    curses.init_color(12, 0, 1000, 0)
    curses.init_pair(1, 11, -1)
    curses.init_pair(2, 12, -1)

    moveList = [stoneMove(2, '1', 0, 2), stoneMove(3, '2', 1, 1), stoneMove(13, curses.ACS_CKBOARD, pid=1, side=0)] 
    
    dbf = open("debug", "w")

    height, width = stdscr.getmaxyx()
    dbf.write(f"H: {height} W: {width}\n")

    xscale = floor((width-1) / 16)
    yscale = floor((height-1) / 6)
    dbf.write(f"XSCL {xscale} YSCL {yscale}\n")
   
    if xscale > 2*yscale:
        xscale = yscale * 2
    else:
        xscale -= 1 if xscale % 2 == 1 else 0
        yscale = int(xscale/2)
    dbf.write(f"POST XSCL {xscale} YSCL {yscale}\n")

    cellSize = (2*xscale - 1, 2*yscale - 1)
    
    p = 0
    selected = [0,0]

    while True:
        stdscr.erase()
        for y in range(0, (6*yscale) + 1):
            for x in range(0, (16*xscale) + 1):
                duplet = place_table[selected[p]][p] if type(place_table[selected[p]][p]) is tuple else place_table[selected[p]]
                if (xscale*(duplet[0]-1)) < x < (xscale*(duplet[0]+1)) and (yscale*(duplet[1]-1)) < y < (yscale*(duplet[1]+1)):
                    stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), ' ', curses.A_REVERSE)

                if y == 0:
                    if x in [0, (12*xscale)]:
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_ULCORNER)
                    elif x in [(8*xscale), (16*xscale)]:
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_URCORNER)
                    elif x < (12*xscale) and x > (8*xscale):
                        continue
                    elif x % (2*xscale) == 0:
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_TTEE)
                    else:
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_HLINE)
                elif y == (6*yscale):
                    if x in [0, (12*xscale)]:
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_LLCORNER)
                    elif x in [(8*xscale), (16*xscale)]:
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_LRCORNER)
                    elif x < (12*xscale) and x > (8*xscale):
                        continue
                    elif x % (2*xscale) == 0:
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_BTEE)
                    else:
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_HLINE)
                elif y % (2*yscale) != 0:
                    if 0 < y < (2*yscale) or  (4*yscale) < y < (6*yscale):
                        if x < (12*xscale) and x > (8*xscale):
                            continue
                        if x in [xscale, 13*xscale] or (y in [yscale, 5*yscale] and (0 < x < 2*xscale or 12*xscale < x < 14*xscale)):
                            stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), 'X')
                    if (x == (7*xscale) and 2*yscale < y < 4*yscale) or (y == 3*yscale and 6*xscale < x < 8*xscale):
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), 'X')
                    '''
                    for stone in moveList:
                        tmp = []
                        if stone.pos in [0,1,2,3,12,13,14] and stone.side == -1:
                            continue
                        if stone.pos not in [0,1,2,3,12,13,14] and stone.side != -1:
                            stone.side = -1
                        if stone.side != -1:
                            tmp = place_table[stone.pos][stone.side]
                        else:
                            tmp = place_table[stone.pos]
                        if x == tmp[0]*xscale and y == tmp[1]*yscale:
                            if cellSize[0] <= 3 or cellSize[1] <= 3:
                                stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), stone.owner)
                            else:
                                smaller = cellSize[0] if cellSize[0] <= cellSize[1] else cellSize[1]
                                for y2 in range(y-int((smaller-1)/2-1), y+int((smaller-1)/2)):
                                    for x2 in range(x-int((smaller-1)/2-1), x+int((smaller-1)/2)):
                                        stdscr.addch(int((height/2 - (6*yscale)/2) + y2), int((width/2 - (16*xscale)/2) + x2), stone.owner)
                    '''
                    if x % (2*xscale) == 0:
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_VLINE)
                elif y in [2*yscale,4*yscale]:
                    if x == 0:
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_LTEE)
                    elif x == (16*xscale):
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_RTEE)
                    elif x == (10*xscale):
                        if y == (2*yscale):
                            stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_TTEE)
                        elif y == (4*yscale):
                            stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_BTEE)
                    elif x % (2*xscale) == 0:
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_PLUS)
                    else:
                        stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_HLINE)

        for y in range(0, 6*yscale, yscale):
            for x in range(0, 16*xscale, xscale):
                #if y in [yscale, 3*yscale, 5*yscale]:
                for stone in moveList:
                    tmp = []
                    if stone.pos in [0,1,2,3,12,13,14] and stone.side == -1:
                        continue
                    if stone.pos not in [0,1,2,3,12,13,14] and stone.side != -1:
                        stone.side = -1
                    if stone.side != -1:
                        tmp = place_table[stone.pos][stone.side]
                    else:
                        tmp = place_table[stone.pos]
                    if x == tmp[0]*xscale and y == tmp[1]*yscale:
                        if cellSize[0] <= 3 or cellSize[1] <= 3:
                            stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), stone.owner)
                        else:
                            smaller = cellSize[0] if cellSize[0] <= cellSize[1] else cellSize[1]
                            for y2 in range(y-int((smaller-1)/2-1), y+int((smaller-1)/2)):
                                for x2 in range(x-int((smaller-1)/2-1), x+int((smaller-1)/2)):
                                    if x == x2 and y == y2:
                                        stdscr.addch(int((height/2 - (6*yscale)/2) + y2), int((width/2 - (16*xscale)/2) + x2), curses.ACS_DIAMOND)
                                    else:
                                        stdscr.addch(int((height/2 - (6*yscale)/2) + y2), int((width/2 - (16*xscale)/2) + x2), stone.owner, curses.color_pair(stone.pid))

        


        stdscr.refresh()
        c = stdscr.getch()
        if chr(c) == 'q':
            break
        elif c == curses.KEY_RESIZE:
            height, width = stdscr.getmaxyx()
            dbf.write(f"H: {height} W: {width}\n")

            xscale = floor((width-1) / 16)
            yscale = floor((height-1) / 6)
            dbf.write(f"XSCL {xscale} YSCL {yscale}\n")
   
            if xscale > 2*yscale:
                xscale = yscale * 2
            else:
                xscale -= 1 if xscale % 2 == 1 else 0
                yscale = int(xscale/2)
            dbf.write(f"POST XSCL {xscale} YSCL {yscale}\n")
            cellSize = (2*xscale - 1, 2*yscale - 1)
        elif c == curses.KEY_UP:
            selected[p] = selected[p]+1 if selected[p] != 13 else 0
        elif c == curses.KEY_DOWN:
            selected[p] = selected[p]-1 if selected[p] != 0 else 13
Ejemplo n.º 41
0
            reportes.stack_report(true_stack)
            misc.imprimir("Score report generated successfully!")
        elif (key == 51):
            reportes.scoreBoard_report(scoreBoard)
            misc.imprimir("Score Board report generated successfully!")
        elif (key == 52):
            reportes.users_report(usuarios)
            misc.imprimir("Users Report generated successfully!")
    misc.clear_scr()


stdscr = curses.initscr()  #initialize console
window = curses.newwin(max_x, max_y, 0, 0)  #create a new curses window
window.keypad(True)  #enable Keypad mode
curses.noecho()  #prevent input from displaying in the screen
curses.curs_set(0)  #cursor invisible (0)
paint_menu(window)
misc = Misc(window, max_x, max_y)
true_game = snake_game(None, max_x, max_y, window, usuario)
true_snake = true_game.get_new_snake()
pausa = False
keystroke = -1
while (keystroke == -1):
    keystroke = window.getch()  #get current key being pressed
    if (keystroke == 49):  #1
        misc.clear_scr()
        paint_title(window, ' PLAY ')
        if (usuario is None):
            misc.clear_scr()
            misc.print_title("Creacion de Usuario:")
            newUser = misc.getString()
Ejemplo n.º 42
0
    def do_action(self, returned=False, go_back=False):
        if returned:
            if len(self.str) > self.visible_text_width:
                text = self.str[-self.visible_text_width:]
            else:
                text = self.str
            if self.echo_char:
                text = self.echo_char * len(text)
            # Add the dashes
            text = text + '_' * (self.visible_text_width - len(self.str))
            self.textwin.addstr(self.y, 0, text)
        if not returned:
            curses.curs_set(1)
            self.init_text()
            if self.default_string != None:
                self.textwin.addstr(self.y, 0, self.default_string)
                self.str = self.default_string

        while True:
            if len(self.str) > self.visible_text_width:
                curs_loc = self.visible_text_width
            else:
                curs_loc = len(self.str)
            ch = self.textwin.getch(self.y, curs_loc)

            update_text = False
            if ch in [curses.KEY_ENTER, ord('\n')]:
                curses.curs_set(0)
                if go_back:
                    return ActionResult(False, {'goBack': True})
                if self.confirmation_error_msg:
                    if self.str != self.install_config[self.field]:
                        conf_message_height = 8
                        conf_message_width = 48
                        conf_message_button_y = (self.maxy -
                                                 conf_message_height) / 2 + 5
                        confrim_window = ConfirmWindow(
                            conf_message_height, conf_message_width, self.maxy,
                            self.maxx, conf_message_button_y,
                            self.confirmation_error_msg, True)
                        confrim_window.do_action()
                        return ActionResult(False, {'goBack': True})
                    self.set_field()
                else:
                    if not self.validate_input():
                        continue
                    self.set_field()
                curses.curs_set(0)
                return ActionResult(True, None)
            elif ch == curses.KEY_LEFT and not self.tab_enabled:
                return ActionResult(False, {'direction': -1})
            elif ch == curses.KEY_RIGHT and not self.tab_enabled:
                return ActionResult(False, {'direction': 1})
            elif ch in [ord('\t')]:
                curses.curs_set(0)
                return ActionResult(False, None)
            elif ch == curses.KEY_BACKSPACE:  #originally ==127
                # Handle the backspace case
                self.str = self.str[:len(self.str) - 1]

                update_text = True

            elif len(self.str) < self.maxlength and ch in self.accepted_chars:
                self.str += chr(ch)
                update_text = True

            if update_text:
                if len(self.str) > self.visible_text_width:
                    text = self.str[-self.visible_text_width:]
                else:
                    text = self.str
                if self.echo_char:
                    text = self.echo_char * len(text)
                # Add the dashes
                text = text + '_' * (self.visible_text_width - len(self.str))
                self.textwin.addstr(self.y, 0, text)
Ejemplo n.º 43
0
 def draw_cursor(self, stdscr, y, x):
     curses.curs_set(0)
Ejemplo n.º 44
0
def main(screen: curses.window):
    curses.mousemask(1)
    screen.nodelay(1)
    curses.curs_set(0)
    start(screen)
    chat_page(screen)
Ejemplo n.º 45
0
def showHelp(stdscr, args, listOfQueries, dbg):

    # Clear and refresh the screen for a blank canvas
    stdscr.clear()
    stdscr.refresh()

    # Attempt to turn on the cursor
    curses.curs_set(True)

    # Update the screen periodically, independent of input
    stdscr.timeout(-1)

    # Loop where k is the last character pressed
    k = -1

    while (k == -1):

        # Initialization
        stdscr.erase()
        height, width = stdscr.getmaxyx()

        y = 0
        x = 0

        line = f'DAQ blockages monitor for partition {args.part}, instrument "{args.inst}"'
        stdscr.addstr(y, x, line, curses.color_pair(1))
        y += 2

        line = 'Available keystrokes:'
        keys = [('Arrow keys', 'Scroll by column or row'),
                ('Page up/down', 'Scroll rows by page'),
                ('i', 'Toggle display of the process "instance" name'),
                ('n/p', 'Advance/retreat time by one step'),
                ('<space>', 'Advance time by one step'),
                ('+/-', 'Increase/decrease time step size by 1 second'),
                ('t', 'Toggle use of current vs "start" parameter time'),
                ('h/?', 'Help'),
                ('q', 'Quit'),]

        stdscr.addstr(y, x, line, curses.color_pair(1))
        y += 1
        for key in keys:
            stdscr.addstr(y, 2+x,    key[0], curses.color_pair(1))
            stdscr.addstr(y, 2+x+14, key[1], curses.color_pair(1))
            y += 1

        y += 1
        line = 'Column header descriptions:'
        stdscr.addstr(y, x, line, curses.color_pair(1))
        y += 1
        for queries in listOfQueries:
            for metric, query in queries.items():
                dbg.write('y, x: %d, %d, metric \'%s\', descr \'%s\'\n' % (y, x, metric, query[2]))
                stdscr.addstr(y, 2+x,    metric,   curses.color_pair(1))
                stdscr.addstr(y, 2+x+14, query[2], curses.color_pair(1))
                y += 1
                if y > height - 1:  break
            if y > height - 1:  break

        y = height - 1
        stdscr.addstr(y, x, "Hit any character to continue", curses.color_pair(1))

        # Wait for next input
        k = stdscr.getch()

    # Attempt to turn off the cursor
    curses.curs_set(False)

    # Update the screen periodically, independent of input
    stdscr.timeout(1000)

    stdscr.erase()
Ejemplo n.º 46
0
    def run(self):
        try:
            while True:
                #print 'Is the queue empty?: {}'.format(self.qscreen.empty())
                if not self.qscreen.empty():
                    order = self.qscreen.get()
                    #self.logfile.write('Receiving the order'+order+'\n')
                    if order == 'Start':
                        stdscr = curses.initscr()
                        curses.savetty()
                        curses.start_color()
                        curses.use_default_colors()
                        self.screen = stdscr
                        curses.init_pair(1, curses.COLOR_GREEN, -1)
                        curses.init_pair(2, curses.COLOR_RED, -1)
                        curses.init_pair(3, curses.COLOR_BLUE, -1)
                        curses.init_pair(4, curses.COLOR_WHITE, -1)
                        self.screen.bkgd(' ', curses.color_pair(1))
                        self.screen.bkgd(' ')
                        curses.noecho()
                        curses.cbreak()
                        self.screen.keypad(1)
                        # curses.curs_set. 0 means invisible cursor, 1 visible, 2 very visible
                        curses.curs_set(0)
                        self.screen.addstr(0,0, 'Live Stream', curses.A_BOLD)
                        self.screen.refresh()
                        self.qscreen.task_done()

                    elif order == 'Stop':
                        self.screen.addstr(0,0, 'Press any key to go back to stf screen...                                                                   ', curses.A_BOLD)
                        self.screen.getstr(0,0, 15)
                        curses.nocbreak()
                        self.screen.keypad(0)
                        curses.echo()
                        curses.curs_set(1)
                        stdscr.refresh()
                        # close
                        self.qscreen.task_done()
                        curses.resetty()
                        self.f.close()
                        return
                    else:
                        #self.screen.addstr(0,50, 'Receiving Data')
                        self.screen.refresh()
                        # Get the screen size
                        (x_max, y_max) = self.screen.getmaxyx()
                        # The order 
                        orig_tuple = order
                        tuple_id = orig_tuple.get_id()
                        # Get the amount of letters that fit on the screen
                        state = orig_tuple.get_state()[-(y_max-self.y_min):]
                        tuple = self.get_tuple(tuple_id)
                        # Update the status bar
                        if int(tuple['x_pos']) < x_max - 3: 
                            self.screen.addstr(0,20,tuple_id + "                            ", curses.A_BOLD)
                            self.screen.refresh()
                            #self.screen.addstr(int(tuple['x_pos']), int(tuple['y_pos']), state, tuple['color'] | curses.A_BOLD)
                            #if int(tuple['x_pos']) <= xmax:
                            self.screen.addstr(int(tuple['x_pos']), int(tuple['y_pos']), state, tuple['color'])
                            #tuple['y_pos'] += len(state)
                            self.screen.refresh()
                            self.qscreen.task_done()
        except KeyboardInterrupt:
            curses.nocbreak()
            self.screen.keypad(0)
            curses.echo()
            curses.curs_set(1)
            curses.resetty()
            self.screen.refresh()
        except Exception as inst:
            print '\tProblem with Screen()'
            print type(inst)     # the exception instance
            print inst.args      # arguments stored in .args
            print inst           # __str__ allows args to printed directly
            sys.exit(1)
Ejemplo n.º 47
0
def color():
    curses.start_color()
    curses.init_pair(1, MATRIX_COLOR_WORD, MATRIX_COLOR_BACK)
    curses.curs_set(0)
    curses.noecho()
Ejemplo n.º 48
0
def draw(stdscr, srvurl, args, listOfQueries, dbg):

    start_row = 0               # In units of rows    of some height
    start_col = 0               # In units of columns of some width
    showInstance = False
    step = 5                    # Seconds
    time = None
    if args.start is not None:
        time = datetime.fromisoformat(args.start).timestamp()

    tables = []
    for queries in listOfQueries:
        tables.append(Table(srvurl, queries, dbg))

    # Clear and refresh the screen for a blank canvas
    stdscr.clear()
    stdscr.refresh()

    # Start colors in curses
    curses.start_color()
    curses.init_pair(1, curses.COLOR_WHITE,  curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_BLACK,  curses.COLOR_WHITE)
    curses.init_pair(3, curses.COLOR_CYAN,   curses.COLOR_BLACK)
    curses.init_pair(4, curses.COLOR_RED,    curses.COLOR_BLACK)
    curses.init_pair(5, curses.COLOR_YELLOW, curses.COLOR_BLACK)

    # Attempt to turn off the cursor
    curses.curs_set(False)

    # Update the screen periodically, independent of input
    stdscr.timeout(1000)

    try:
        # Loop where k is the last character pressed
        k = 0
        while (k != ord('q')):

            # Initialization
            #stdscr.erase()
            height, width = stdscr.getmaxyx()
            dbg.write('height %d, width %d\n' % (height, width))

            if   k == curses.KEY_DOWN:
                start_row += 1
            elif k == curses.KEY_UP:
                start_row -= 1
            elif k == curses.KEY_RIGHT:
                start_col += 1
            elif k == curses.KEY_LEFT:
                start_col -= 1
            elif k == curses.KEY_NPAGE:
                start_col += height
            elif k == curses.KEY_PPAGE:
                start_col -= height
            elif (k == ord('n') or k == ord(' ')) and time is not None:
                time += step
            elif (k == ord('p')) and time is not None:
                time -= step
            elif k == ord('+') and time is not None:
                step += 1
            elif k == ord('-') and time is not None:
                if step > 1:  step -= 1
            elif k == ord('t') and time is not None:
                time = None
            elif k == ord('t') and time is None:
                if args.start is not None:
                    time = datetime.fromisoformat(args.start).timestamp()
            elif k == ord('i'):
                showInstance = not showInstance
            elif k == ord('h') or k == ord('?'):
                showHelp(stdscr, args, listOfQueries, dbg)
                k = 0
            elif k == ord('\f'): # ^l
                stdscr.clear()

            y = 0
            for table in tables:
                samples = update(table.metrics, time)
                table.update(len(samples), start_row, start_col, showInstance, width)
                rows = table.draw(samples, height, width, y)
                y += rows + 1
                stdscr.addstr(y-1, 0, ' ' * width) # Clear line between tables

            if time is not None:
                entry = str(datetime.fromtimestamp(time))
                entry = entry + ',  step = ' + str(step) + ' s'
                stdscr.addstr(height - 1, 0, entry, curses.color_pair(2))

            # Refresh the screen
            curses.doupdate() #refresh()

            # Wait for next input
            k = stdscr.getch()
    except:
        dbg.done()
        raise
    else:
        dbg.done()
Ejemplo n.º 49
0
def main():
    dead = False
    stdscr = curses.initscr()
    curses.start_color()
    curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.raw()
    curses.noecho()
    curses.cbreak()
    stdscr.nodelay(True)
    stdscr.keypad(True)
    curses.curs_set(0)
    maxyx = stdscr.getmaxyx()
    frame = 0
    seconds = 0
    score = 0
    prevscore = 0
    accelerationFlappy = 1
    upthrustFlappy = 0
    tubes = genTubes(stdscr)
    flappyPos = [math.trunc(maxyx[0] / 2) - 20, math.trunc(maxyx[1] / 2)]
    drawTitle(stdscr, prevscore)
    drawControls(stdscr)
    while (dead != True):
        if (frame > 59):
            frame = 0
            seconds += 1
        else:
            frame += 1
            upthrustFlappy -= 0.1
        #draw frame
        drawFlappy(stdscr, flappyPos)
        drawTubes(stdscr, tubes)
        drawUI(stdscr, score)
        #keyboard input
        try:
            c = stdscr.getkey()
        except:
            c = 0
        #moving, quitting, and all that stuff
        if (c == 'q'):
            gameover(stdscr, score)
            break
        elif (c == ' '):
            upthrustFlappy += 3
        elif (c == 'p'):
            while (stdscr.getch() == curses.ERR):
                drawFlappy(stdscr, flappyPos)
                drawTubes(stdscr, tubes)
                drawUI(stdscr, score)
                stdscr.addstr(math.trunc(maxyx[0] / 2),
                              math.trunc(maxyx[1] / 2 - 3), "PAUSED")
                stdscr.refresh()
                time.sleep(0.016)
        #game loop stuff
        flappyPos[0] -= math.trunc(accelerationFlappy * upthrustFlappy)
        if (frame % 2 == 0):
            flappyPos[0] += accelerationFlappy
        if (frame % 3 == 0):
            for i in tubes:
                i[0][1] -= 2
                i[1][1] -= 2
        if (flappyPos[0] < 0):
            flappyPos[0] = 0
            upthrustFlappy /= 2
        for i in tubes:
            if (flappyPos[0] < i[0][0] and flappyPos[1] + 6 >= i[0][1] - 9
                    and flappyPos[1] + 6 <= i[0][1] + 9
                    or flappyPos[0] + 8 > i[1][0]
                    and flappyPos[1] + 6 >= i[1][1] - 9
                    and flappyPos[1] + 6 <= i[1][1] + 9):
                time.sleep(3)
                curses.flash()
                gameover(stdscr, score)
                dead = True
        score = 0
        for i in tubes:
            if (flappyPos[1] > i[0][1]):
                score += 1
        if (flappyPos[0] > maxyx[0]):
            time.sleep(3)
            curses.flash()
            gameover(stdscr, score)
            dead = True
        #
        stdscr.refresh()
        stdscr.erase()
        time.sleep(0.016)
    curses.endwin()
Ejemplo n.º 50
0
def main(func):
    # initializing curses
    stdscr = curses.initscr()

    # make the cursor invisible
    curses.curs_set(0)

    stdscr.addstr(0, 0, "Start time: ")
    stdscr.addstr(1, 0, "End time: ")
    stdscr.addstr(3, 0, "Difference: ")

    # a counter to track the number of pressing <SPACE>
    space_pressed = 0

    while True:
        # wait for a keypress
        c = stdscr.getch()

        # if <SPACE> is pressed...
        if c == ord(" "):
            space_pressed += 1

            # print the start time
            if space_pressed == 1:
                start_time = datetime.now()
                stdscr.addstr(0, 12, start_time.strftime("%H:%M:%S"))

            # show end time and difference
            elif space_pressed == 2:
                end_time = datetime.now()
                stdscr.addstr(1, 10, end_time.strftime("%H:%M:%S"))

                difference = end_time - start_time
                minutes, seconds = divmod(difference.seconds, 60)
                hours, minutes = divmod(minutes, 60)

                # format the output
                seconds = "%02d" % seconds if seconds < 10 else seconds
                minutes = "%02d" % minutes if minutes < 10 else minutes
                hours = "%02d" % hours if hours < 10 else hours

                stdscr.addstr(3, 12, "%s:%s:%s" % (hours, minutes, seconds))

            # delete the calculated data and start again
            elif space_pressed == 3:
                # delete start time
                for col in xrange(12, 25):
                    stdscr.delch(0, 12)

                # delete end time
                for col in xrange(10, 25):
                    stdscr.delch(1, 10)

                # delete difference time
                for col in xrange(12, 25):
                    stdscr.delch(3, 12)

                # reset the counter and restart
                space_pressed = 0

        # quit the app if `q` is pressed
        elif c == ord("q"):
            return
Ejemplo n.º 51
0
def draw(stdscr, logging):
    k = 0
    cursor_x = 0
    cursor_y = 0

    curses.noecho ()
    curses.curs_set (0)
    curses.raw ()
    stdscr.keypad (0)

    # Clear and refresh the screen for a blank canvas
    stdscr.clear()
    stdscr.refresh()

    stdscr.nodelay (True)
    y, x = stdscr.getmaxyx ()

    stdscr.setscrreg (1, y-1)
    stdscr.scrollok (True)



    # Start colors in curses
    curses.start_color()
    curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)

    gameState = state.State(logging)
    statusbarstr = 'Enter Command: '
    gameController = controller.Controller(logging)
    # Loop where k is the last character pressed
    error = ''
    win = False
    while True:

        # Initialization
        stdscr.erase()
        height, width = stdscr.getmaxyx()

        if win:
            stdscr.addstr(height//2, width//2, 'You Won')
            stdscr.refresh()
            time.sleep(5)
            break

        draw_state(stdscr, gameState, logging)

        if error:
            stdscr.attron(curses.color_pair(2))
            stdscr.addstr(height-2, 0, error)
            stdscr.attroff(curses.color_pair(2))

        # Render status bar
        stdscr.attron(curses.color_pair(3))
        stdscr.addstr(height-1, 0, statusbarstr)
        #stdscr.addstr(height-1, len(statusbarstr), " " * (width - len(statusbarstr) - 1))

        sub2 = stdscr.subwin(1, 8, height-1,  len(statusbarstr))
        tb = curses.textpad.Textbox(sub2)
        stdscr.refresh()
        tb.edit()
        message = tb.gather()
        if message and message[0] == 'q':
            break
        error, gameState = gameController.applyMove(message, gameState)
        win = gameController.checkWinState(gameState)

        stdscr.attroff(curses.color_pair(3))
        # Refresh the screen
        stdscr.refresh()
Ejemplo n.º 52
0
    curses.endwin()
    curses.curs_set(1)
    curses.reset_shell_mode()
    curses.echo()

    screen = curses.initscr()
    color()
    lastchr = string.join(list(MATRIX_THANKS_CHARS), " ")

    last_height, last_width = screen.getmaxyx()
    start_width = last_width / 2 - len(lastchr) / 2
    for i in range(last_height / 2):
        screen.clear()
        screen.addstr(i, start_width, lastchr, curses.color_pair(1))
        screen.refresh()
        time.sleep(0.2)
    screen.getch()
    curses.endwin()


try:
    main()
except KeyboardInterrupt:
    try:
        last_main()
    except KeyboardInterrupt:
        curses.endwin()
        curses.curs_set(1)
        curses.reset_shell_mode()
        curses.echo()
Ejemplo n.º 53
0
def inicio(c4, scr):
    menu = ["Iniciar Sesion", "Crear Usuario", "Salir"]
    
    # primer elemento para la pocision del "cursor" en el menu
    # segundo elemento para la accion que se realizo
    selc = (0,0) 


    # Primera capa se ejecuta hasta que se haya iniciado sesion
    while c4.jugador == None:
        print_menu(scr, menu, selc[0])
        selc = mover_menu(scr, selc, len(menu)-1)
        
        user = ""
        password = ""

        if selc[1] == 1:
            # Limpiar pantalla antes de cambiar de menu
            scr.clear()

            # Opcion 0 = Iniciar Sesion
            if selc[0] == 0:
                selc_inicio = (0,0)

                while True:
                    menu_inicio = ["Usuario:", "Contrasena:", "Iniciar Sesion",  "Cancelar"]

                    print_menu(scr, menu_inicio, selc_inicio[0])
                    
                    # colocar el nombre de usuario, vacio al principio, 
                    scr.addstr(2,11,user)
                    selc_inicio = mover_menu(scr, selc_inicio, len(menu_inicio)-1)

                    if selc_inicio[1] == 1:
                        # Opcion 0 = Usuario
                        if selc_inicio[0] == 0:
                            print_menu(scr, menu_inicio, selc_inicio[0])
                            
                            # Preparar la terminal para ingresar el usuario
                            curses.echo()
                            scr.addstr(2,11," "*len(user))
                            scr.move(2,11)
                            curses.curs_set(1)

                            user = scr.getstr().decode(encoding="utf-8")
                            
                            # Regresar la terminal al estado anterior
                            curses.noecho()
                            curses.curs_set(0)

                        # Opcion 0 = Contrasena
                        elif selc_inicio[0] == 1:
                            # Preparar la terminal para ingresar la contrasena
                            scr.move(3,14)
                            curses.curs_set(1)

                            password = scr.getstr().decode(encoding="utf-8")

                            # Regresar la terminal al estado anterior
                            curses.curs_set(0)

                        # Opcion 2 = Iniciar Sesion
                        elif selc_inicio[0] == 2:
                            if c4.iniciar_sesion(user, password):
                                break
                            else:
                                scr.addstr(7,2,"NOMBRE DE USUARIO O CONTRASENA INCORRECTOS")
                        else:
                            break

                    # Salir con flecha izquierda
                    elif selc_inicio[1] == -1:
                        break
                
                scr.clear()

            # Opcion 2 = Crear Usuario, practicamente igual a iniciar sesion
            elif selc[0] == 1:
                selc_crear = (0,0)

                while True:
                    menu_crear = ["Usuario:", "Contrasena:", "Crear Usuario",  "Cancelar"]

                    print_menu(scr, menu_crear, selc_crear[0])
                    scr.addstr(2,11,user)
                    selc_crear = mover_menu(scr, selc_crear, len(menu_crear)-1)

                    if selc_crear[1] == 1:
                        if selc_crear[0] == 0:
                            print_menu(scr, menu_crear, selc_crear[0])

                            curses.echo()
                            scr.move(2,11)
                            curses.curs_set(1)

                            user = scr.getstr().decode(encoding="utf-8")
                       
                            curses.noecho()
                            curses.curs_set(0)

                        elif selc_crear[0] == 1:
                            scr.move(3,14)
                            curses.curs_set(1)

                            password = scr.getstr().decode(encoding="utf-8")

                            curses.curs_set(0)

                        elif selc_crear[0] == 2:
                            if c4.crear_usuario(user, password):
                                break
                            else:
                                scr.addstr(7,2,"NOMBRE DE USUARIO NO DISPONIBLE")
                        else:
                            break

                    elif selc_crear[1] == -1:
                        break

                scr.clear()

            elif selc[0] == 2:
                break
    
    scr.clear()
Ejemplo n.º 54
0
    def _init_curses_and_play(self, screen):
        """Set up an already-running curses; do interaction loop.

    This method is intended to be passed as an argument to `curses.wrapper`,
    so its only argument is the main, full-screen curses window.

    Args:
      screen: the main, full-screen curses window.

    Raises:
      ValueError: if any key in the `keys_to_actions` dict supplied to the
          constructor has already been reserved for use by `CursesUi`.
    """
        # This needs to be overwritten to use `self._env.step()` instead of
        # `self._game.play()`.

        # See whether the user is using any reserved keys. This check ought to be in
        # the constructor, but it can't run until curses is actually initialised, so
        # it's here instead.
        for key, action in self._keycodes_to_actions.items():
            if key in (curses.KEY_PPAGE, curses.KEY_NPAGE):
                raise ValueError(
                    'the keys_to_actions argument to the CursesUi constructor binds '
                    'action {} to the {} key, which is reserved for CursesUi. Please '
                    'choose a different key for this action.'.format(
                        repr(action), repr(curses.keyname(key))))

        # If the terminal supports colour, program the colours into curses as
        # "colour pairs". Update our dict mapping characters to colour pairs.
        self._init_colour()
        curses.curs_set(0)  # We don't need to see the cursor.
        if self._delay is None:
            screen.timeout(-1)  # Blocking reads
        else:
            screen.timeout(
                self._delay)  # Nonblocking (if 0) or timing-out reads

        # Create the curses window for the log display
        rows, cols = screen.getmaxyx()
        console = curses.newwin(rows // 2, cols, rows - (rows // 2), 0)

        # By default, the log display window is hidden
        paint_console = False

        # Kick off the game---get first observation, repaint it if desired,
        # initialise our total return, and display the first frame.
        self._env.reset()
        self._game = self._env.current_game
        # Use undistilled observations.
        observation = self._game._board  # pylint: disable=protected-access
        if self._repainter: observation = self._repainter(observation)
        self._display(screen,
                      observation,
                      self._env.episode_return,
                      elapsed=datetime.timedelta())

        # Oh boy, play the game!
        while not self._env._game_over:  # pylint: disable=protected-access
            # Wait (or not, depending) for user input, and convert it to an action.
            # Unrecognised keycodes cause the game display to repaint (updating the
            # elapsed time clock and potentially showing/hiding/updating the log
            # message display) but don't trigger a call to the game engine's play()
            # method. Note that the timeout "keycode" -1 is treated the same as any
            # other keycode here.
            keycode = screen.getch()
            if keycode == curses.KEY_PPAGE:  # Page Up? Show the game console.
                paint_console = True
            elif keycode == curses.KEY_NPAGE:  # Page Down? Hide the game console.
                paint_console = False
            elif keycode in self._keycodes_to_actions:
                # Convert the keycode to a game action and send that to the engine.
                # Receive a new observation, reward, pcontinue; update total return.
                action = self._keycodes_to_actions[keycode]
                self._env.step(action)
                # Use undistilled observations.
                observation = self._game._board  # pylint: disable=protected-access
                if self._repainter: observation = self._repainter(observation)

            # Update the game display, regardless of whether we've called the game's
            # play() method.
            elapsed = datetime.datetime.now() - self._start_time
            self._display(screen, observation, self._env.episode_return,
                          elapsed)

            # Update game console message buffer with new messages from the game.
            self._update_game_console(
                plab_logging.consume(self._game.the_plot), console,
                paint_console)

            # Show the screen to the user.
            curses.doupdate()
Ejemplo n.º 55
0
def gui(stdscr, args, tegra):
    # In this program, we don't want keystrokes echoed to the console,
    # so we run this to disable that
    curses.noecho()
    # Additionally, we want to make it so that the user does not have to press
    # enter to send keys to our program, so here is how we get keys instantly
    curses.cbreak()
    # Define pairing colorss
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
    curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK)
    curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
    curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)
    # Hide the cursor
    curses.curs_set(0)
    # Lastly, keys such as the arrow keys are sent as funny escape sequences to
    # our program. We can make curses give us nicer values (such as curses.KEY_LEFT)
    # so it is easier on us.
    stdscr.keypad(True)
    # Refreshing page curses loop
    # https://stackoverflow.com/questions/54409978/python-curses-refreshing-text-with-a-loop
    stdscr.nodelay(1)
    # Initialization Menu
    pages = JTOPGUI(stdscr, [
        {
            "name": "ALL",
            "func": all_info
        },
        {
            "name": "GPU",
            "func": GPU
        },
        {
            "name": "INFO",
            "func": Variables
        },
    ])
    # Start with selected page
    pages.set(args.page)
    # Here is the loop of our program, we keep clearing and redrawing in this loop
    while True:
        # First, clear the screen
        stdscr.erase()
        # Draw pages
        pages.draw(tegra)
        # Draw the screen
        stdscr.refresh()
        # Set a timeout and read keystroke
        stdscr.timeout(args.refresh)
        key = stdscr.getch()
        # keyboard check list
        if key == curses.KEY_LEFT:
            pages.decrease()
        elif key == curses.KEY_RIGHT:
            pages.increase()
        elif key in [ord(str(n)) for n in range(10)]:
            num = int(chr(key))
            pages.set(num)
        elif key == ord('q') or key == ord('Q'):
            break
Ejemplo n.º 56
0
 def start(self) -> None:
     super().start()
     with suppress(Exception):
         curses.curs_set(0)
Ejemplo n.º 57
0
 def reset(self):
     curses.nocbreak()
     curses.echo()
     curses.curs_set(1)
     curses.endwin()
Ejemplo n.º 58
0
def displayStrategyRun(individual):

    input("press me")

    #routine = gp.compile(individual, pset)

    curses.initscr()
    win = curses.newwin(YSIZE + 15, XSIZE + 15, 0, 0)
    win.keypad(1)
    curses.noecho()
    curses.curs_set(0)
    win.border(0)
    win.nodelay(1)
    win.timeout(60)

    snake = None

    if len(snakeList) > 0:
        snake = copy.deepcopy(random.choice(snakeList))
    else:
        snake = SnakePlayer()
    food = placeFood(snake)

    for f in food:
        win.addch(f[0], f[1], '@')

    timer = 0
    collided = False
    while not collided and not timer == ((2 * XSIZE) * YSIZE):

        # Set up the display
        win.border(0)
        win.addstr(0, 2, 'Score : ' + str(snake.score) + ' ')
        win.addstr(19, 2, 'ScorA : ' + str("%4.3f" % (snake.aa)) + ' ')
        win.addstr(20, 2, 'part1 : ' + str("%4.3f" % (snake.aaa)) + ' ')
        win.addstr(21, 2, 'ScorB : ' + str("%4.3f" % (snake.bb)) + ' ')
        win.addstr(22, 2, 'part2 : ' + str("%4.3f" % (snake.bbb)) + ' ')
        win.addstr(23, 2, 'ScorC : ' + str("%4.3f" % (snake.cc)) + ' ')
        win.addstr(24, 2, 'part3 : ' + str("%4.3f" % (snake.ccc)) + ' ')
        win.addstr(25, 2, 'ScorD : ' + str("%4.3f" % (snake.dd)) + ' ')
        win.addstr(26, 2, 'part4 : ' + str("%4.3f" % (snake.ddd)) + ' ')

        win.getch()

        ## EXECUTE THE SNAKE'S BEHAVIOUR HERE ##

        snake.updateDirection(individual, True)
        snake.updatePosition()

        if snake.body[0] in food:
            snake.score += 1
            for f in food:
                win.addch(f[0], f[1], ' ')
            food = placeFood(snake)
            for f in food:
                win.addch(f[0], f[1], '@')
            timer = 0
        else:
            last = snake.body.pop()
            win.addch(last[0], last[1], ' ')
            timer += 1  # timesteps since last eaten
        win.addch(snake.body[0][0], snake.body[0][1], 'o')

        collided = snake.snakeHasCollided()
        hitBounds = (timer == ((2 * XSIZE) * YSIZE))

    curses.endwin()

    print(collided)
    print(hitBounds)
    input("Press to continue...")

    return snake.score,
Ejemplo n.º 59
0
def main(repo, rules, stdscr):
    # initialize color pattern
    curses.init_pair(COLOR_HELP, curses.COLOR_WHITE, curses.COLOR_BLUE)
    curses.init_pair(COLOR_SELECTED, curses.COLOR_BLACK, curses.COLOR_WHITE)
    curses.init_pair(COLOR_WARN, curses.COLOR_BLACK, curses.COLOR_YELLOW)
    curses.init_pair(COLOR_OK, curses.COLOR_BLACK, curses.COLOR_GREEN)

    # don't display the cursor
    try:
        curses.curs_set(0)
    except curses.error:
        pass

    def rendercommit(win, state):
        """Renders the commit window that shows the log of the current selected
        commit"""
        pos = state["pos"]
        rules = state["rules"]
        rule = rules[pos]

        ctx = rule.ctx
        win.box()

        maxy, maxx = win.getmaxyx()
        length = maxx - 3

        line = "changeset: {0}:{1:<12}".format(ctx.rev(), str(ctx))
        win.addstr(1, 1, line[:length])

        line = "user:      {0}".format(util.shortuser(ctx.user()))
        win.addstr(2, 1, line[:length])

        bms = repo.nodebookmarks(ctx.node())
        line = "bookmark:  {0}".format(" ".join(bms))
        win.addstr(3, 1, line[:length])

        line = "files:     {0}".format(",".join(ctx.files()))
        win.addstr(4, 1, line[:length])

        line = "summary:   {0}".format(ctx.description().splitlines()[0])
        win.addstr(5, 1, line[:length])

        conflicts = rule.conflicts
        if len(conflicts) > 0:
            conflictstr = ",".join([str(r.ctx) for r in conflicts])
            conflictstr = "changed files overlap with {0}".format(conflictstr)
        else:
            conflictstr = "no overlap"

        win.addstr(6, 1, conflictstr[:length])
        win.noutrefresh()

    def helplines(mode):
        if mode == MODE_PATCH:
            help = """\
?: help, k/up: line up, j/down: line down, v: stop viewing patch
pgup: prev page, space/pgdn: next page, c: commit, q: abort
"""
        else:
            help = """\
?: help, k/up: move up, j/down: move down, space: select, v: view patch
d: drop, e: edit, f: fold, m: mess, p: pick, r: roll
pgup/K: move patch up, pgdn/J: move patch down, c: commit, q: abort
"""
        return help.splitlines()

    def renderhelp(win, state):
        maxy, maxx = win.getmaxyx()
        mode, _ = state["mode"]
        for y, line in enumerate(helplines(mode)):
            if y >= maxy:
                break
            addln(win, y, 0, line, curses.color_pair(COLOR_HELP))
        win.noutrefresh()

    def renderrules(rulesscr, state):
        rules = state["rules"]
        pos = state["pos"]
        selected = state["selected"]
        start = state["modes"][MODE_RULES]["line_offset"]

        conflicts = [r.ctx for r in rules if r.conflicts]
        if len(conflicts) > 0:
            line = "potential conflict in %s" % ",".join(map(str, conflicts))
            addln(rulesscr, -1, 0, line, curses.color_pair(COLOR_WARN))

        for y, rule in enumerate(rules[start:]):
            if y >= state["page_height"]:
                break
            if len(rule.conflicts) > 0:
                rulesscr.addstr(y, 0, " ", curses.color_pair(COLOR_WARN))
            else:
                rulesscr.addstr(y, 0, " ", curses.COLOR_BLACK)
            if y + start == selected:
                addln(rulesscr, y, 2, rule, curses.color_pair(COLOR_SELECTED))
            elif y + start == pos:
                addln(rulesscr, y, 2, rule, curses.A_BOLD)
            else:
                addln(rulesscr, y, 2, rule)
        rulesscr.noutrefresh()

    def renderstring(win, state, output):
        maxy, maxx = win.getmaxyx()
        length = min(maxy - 1, len(output))
        for y in range(0, length):
            win.addstr(y, 0, output[y])
        win.noutrefresh()

    def renderpatch(win, state):
        start = state["modes"][MODE_PATCH]["line_offset"]
        renderstring(win, state, patchcontents(state)[start:])

    def layout(mode):
        maxy, maxx = stdscr.getmaxyx()
        helplen = len(helplines(mode))
        return {
            "commit": (8, maxx),
            "help": (helplen, maxx),
            "main": (maxy - helplen - 8, maxx),
        }

    def drawvertwin(size, y, x):
        win = curses.newwin(size[0], size[1], y, x)
        y += size[0]
        return win, y, x

    state = {
        "pos": 0,
        "rules": rules,
        "selected": None,
        "mode": (MODE_INIT, MODE_INIT),
        "page_height": None,
        "modes": {MODE_RULES: {"line_offset": 0}, MODE_PATCH: {"line_offset": 0}},
        "repo": repo,
    }

    # eventloop
    ch = None
    stdscr.clear()
    stdscr.refresh()
    while True:
        try:
            oldmode, _ = state["mode"]
            if oldmode == MODE_INIT:
                changemode(state, MODE_RULES)
            e = event(state, ch)

            if e == E_QUIT:
                return False
            if e == E_HISTEDIT:
                return state["rules"]
            else:
                if e == E_RESIZE:
                    size = screen_size()
                    if size != stdscr.getmaxyx():
                        curses.resizeterm(*size)

                curmode, _ = state["mode"]
                sizes = layout(curmode)
                if curmode != oldmode:
                    state["page_height"] = sizes["main"][0]
                    # Adjust the view to fit the current screen size.
                    movecursor(state, state["pos"], state["pos"])

                # Pack the windows against the top, each pane spread across the
                # full width of the screen.
                y, x = (0, 0)
                helpwin, y, x = drawvertwin(sizes["help"], y, x)
                mainwin, y, x = drawvertwin(sizes["main"], y, x)
                commitwin, y, x = drawvertwin(sizes["commit"], y, x)

                if e in (E_PAGEDOWN, E_PAGEUP, E_LINEDOWN, E_LINEUP):
                    if e == E_PAGEDOWN:
                        changeview(state, +1, "page")
                    elif e == E_PAGEUP:
                        changeview(state, -1, "page")
                    elif e == E_LINEDOWN:
                        changeview(state, +1, "line")
                    elif e == E_LINEUP:
                        changeview(state, -1, "line")

                # start rendering
                commitwin.erase()
                helpwin.erase()
                mainwin.erase()
                if curmode == MODE_PATCH:
                    renderpatch(mainwin, state)
                elif curmode == MODE_HELP:
                    renderstring(mainwin, state, __doc__.strip().splitlines())
                else:
                    renderrules(mainwin, state)
                    rendercommit(commitwin, state)
                renderhelp(helpwin, state)
                curses.doupdate()
                # done rendering
                ch = stdscr.getkey()
        except curses.error:
            pass
Ejemplo n.º 60
0
 def init_curses():
     curses.curs_set(0)
     # self.screen.nodelay(1)
     curses.mousemask(-1)