Example #1
0
    def setup_windows(self, resize=False):
        """Initialize windows."""
        yx = self.screen.getmaxyx()
        self.text_input = None
        self.header_win = curses.newwin(1, yx[1], 0, 0)
        self.status_win = curses.newwin(1, yx[1], yx[0]-1, 0)
        
        # Test for new curses
        if not "get_wch" in dir(self.header_win):
            # Notify only once
            if not self.warned_old_curses:
                self.app.log("Using old curses! Some keys and special characters might not work.", LOG_WARNING)
                self.warned_old_curses = 1
            
        y_sub = 0
        y_start = 0
        if self.app.config["display"]["show_top_bar"]:
            y_sub += 1
            y_start = 1
        if self.app.config["display"]["show_bottom_bar"]:
            y_sub += 1
        if self.app.config["display"]["show_legend"]:
            y_sub += 2
        self.editor_win = curses.newwin(yx[0]-y_sub, yx[1], y_start, 0)
        if self.app.config["display"]["show_top_bar"]:
            self.legend_win = curses.newwin(2, yx[1], yx[0]-y_sub+1, 0)
        else:
            self.legend_win = curses.newwin(2, yx[1], yx[0]-y_sub, 0)

        if resize:
            self.app.get_editor().resize( (yx[0]-y_sub, yx[1]) )
            self.app.get_editor().move_win( (y_start, 0) )
Example #2
0
def nstart(stdscr):
	global logw
	global cw
	global netstatw
	global trash
	global player
	global kingdom
	global opponent
	curses.start_color()
	maxY, maxX = stdscr.getmaxyx()
	logw = GameInput(windowX=math.floor(maxX/2), windowY=math.floor(maxY/3), height=math.floor(maxY*2/3)-2, width=maxX-math.floor(maxX/2)-1, scrollDepth=1000)
	cw = NetInput(windowX=math.floor(maxX/4), windowY=math.floor(maxY/8*7), height=maxY-math.floor(maxY/8*7)-2, width=math.floor(maxX/4)-1)
	netstatw = curses.newwin(maxY-math.floor(maxY/8*7), math.floor(maxX/4)-1, math.floor(maxY/8*7), 0)
	trash = curses.newwin(math.floor(maxY/8), math.floor(maxX/2), math.floor(maxY*7/16), 0)
	player = Player(math.floor(maxY*7/16), math.floor(maxX/2), 0, 0)
	kingdom = Kingdom(math.floor(maxY/3), math.floor(maxX/2), 0, math.floor(maxX/2))
	opponent = Opponent(math.floor(maxY*5/16), math.floor(maxX/2), math.floor(maxY*9/16), 0)
	trash.addstr('trash')
	trash.refresh()
	if os.path.exists('cccnfg.cfg'):
		with open('cccnfg.cfg', 'r') as f:
			for ln in f.read().splitlines(): cw.command(ln)
	while True:
		cw.run()
		logw.run()
Example #3
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()
Example #4
0
File: cli.py Project: mike42/pyTodo
def inpbox(scr, prompt):
    scr.clear()
    scr.refresh()

    # Parent window
    width = 42
    height = 5
    top = (curses.LINES - height) // 2
    left = (curses.COLS - width) // 2
    box = curses.newwin(height, width, top, left)
    box.bkgd(curses.color_pair(1))
    box.border()
    box.addstr(1, 2, prompt)
    box.refresh()

    # Input box
    txt = curses.newwin(1, width - 4, top + height - 2, left + 2)
    txt.bkgd(curses.color_pair(2))
    txt.refresh()
    txt.keypad(1)
    curses.echo()
    new = txt.getstr().decode('UTF-8')
    curses.noecho()

    scr.clear()
    scr.refresh()
    return new
Example #5
0
	def __init__(self, nlines, ncols, y, x):
		super(Kingdom, self).__init__(nlines, ncols, y, x)
		self.update({
			'piles': curses.newwin(math.floor(nlines*3/5), ncols, y, x),
			'events': curses.newwin(math.floor(nlines*2/5), math.floor(ncols/4), y+math.floor(nlines*3/5), x),
			'nonSupplyPiles': curses.newwin(math.floor(nlines*2/5), math.floor(ncols*3/4), y+math.floor(nlines*3/5), x+math.floor(ncols/4)),
		})
def curses_gui(cscreen):
  global trx_running
  global hs_recipient

  mbar = curses.newwin(5, cscreen.getmaxyx()[1]-2, 1, 1)
  pbar = curses.newwin(5, cscreen.getmaxyx()[1]-2, 6, 1) 

  while True:
    cscreen.clear()
    cscreen.refresh()
    show_menu(mbar)
    show_pbar(pbar)

    c = cscreen.getch()
    if c == ord('x'):
      trx_running = False
      break
    elif (c == ord('h')) and (not trx_running):
      hs_recipient = True
    elif (c == ord('l')) and (not trx_running):
      hs_recipient = False
    elif c == ord('s') and (not trx_running):
      trx_running = True

      pst = PBar_Updater(pbar)
      pst.start()

      trx = Transmitter(hs_server if hs_recipient else ls_server)
      trx.start()
    elif c == ord('q'):
      trx_running = False
Example #7
0
    def run(self):
        self.calculate_dimensions()
        self.windowH = curses.LINES
        self.windowW = curses.COLS

        self.title_window = curses.newwin(1,0,0,0)
        self.nav_window = curses.newwin(self.nlines, self.ncols, self.nyval, self.nxval)
        #Create the pad window
        self.data_window = curses.newpad(BUFFER_SIZE, self.dcols)
        self.data_window.keypad(1)
        self.data_window.timeout(100) #100 ms

        self.update_title()
        self.update_windows()

        counter = time.time()
        #self.started = True
        while not self.stopped:
            c = self.data_window.getch()

            self.check_resize_ui()
            #Update every 1 seconds
            newtime = time.time()
            if newtime - counter >= 1 :
                counter = newtime
                if self.__current_panel__().autoscroll:
                    self.scroll_end()

                #check to see if window has been resized
                if not self.check_resize_ui():
                    self.update_windows()

            if not self.handle_input(c):
                break
    def initcurse(self):
        
        # Check the terminal type.  If we fail, then assume that the
        # terminal has no capabilities.
        try: curses.setupterm()
        except: return
        
        #self.colors = cursescolors()
        
        self.cols = curses.tigetnum('cols')
        self.lines = curses.tigetnum('lines')
        self.wfilelines = self.lines-3

        self.w = curses.initscr()
        # fenetre                    hauteur          largeur    y             x
        self.wheader = curses.newwin(              1, self.cols,            0, 0)
        self.wfile   = curses.newwin(self.wfilelines, self.cols,            1, 0)
        self.wfooter = curses.newwin(              1, self.cols, self.lines-2, 0)
        self.wcmd    = curses.newwin(              1, self.cols, self.lines-1, 0)
        curses.noecho()
        curses.cbreak()
        curses.nonl() # permet d'activer la touche enter (code 13)
        curses.curs_set(0)
        curses.mousemask(0)
        curses.mouseinterval(0)
        self.w.keypad(1)
        self.w.nodelay(0)
        self.w.timeout(self.timeout)
        
        try:
            self.initcolors_1()
        except:
            self.initcolors_2()
Example #9
0
def cursesMain():
    global thebox
    stdscr.clear()
    menu = curses.newwin(height - 2, 15, 0, 1)
    thebox = curses.newwin(height - 3, width - 15, 2, 14)
    menu.box()
    thebox.box()
    menu.addstr( 1, 1, "(i)inbox")
    menu.addstr( 2, 1, "(t)today")
    menu.addstr( 3, 1, "(7)7 days")
    menu.addstr( 4, 1, "(p)projects")
    menu.addstr( 5, 1, "(a)all tasks")
    menu.addstr( 6, 1, "(q)quit")
    stdscr.refresh()
    menu.refresh()
    thebox.refresh()
    keys = stdscr.getch()
    if keys == ord('a'):
        cursesBox(itemList)
        thebox.refresh()
        z = stdscr.getch()
    elif keys == ord('i'):
        cursesInbox()
    elif keys == ord('q'):
        return False
    return True
Example #10
0
    def __init__(self, game, term_width, term_height,stdscr): 
        self.game = game
        self.stdscr = stdscr
        
        """
        break up the screen into four panes:
        ----------------
        | a     |b     |
        |       |      |
        |-------|      |
        | c     |      |
        ----------------
        | d            |
        ----------------
        window a is for drawing the hangman
        window b is for recording the guesses
        window c is for showing the word (blanks and correct letters)
        window d is for communicating with the user
        """
        self.a = curses.newwin(int(term_height*4/6), int(term_width/2), 0,0) 
        self.b = curses.newwin(int(term_height*4/6), int(term_width/2), 
                                0, int(term_width/2)) 
        self.c = curses.newwin(int(term_height*1/6), term_width,
                                int(term_height*4/6), 0) 
        self.d = curses.newwin(int(term_height*1/6), term_width,
                                int(term_height*5/6), 0)

        #initialize magenta colour pairing for printing out guessed letters.
        curses.init_pair(1, curses.COLOR_MAGENTA,curses.COLOR_BLACK)
Example #11
0
def windows():
    stdscr = curses.initscr()
    curses.noecho()
    curses.start_color()
    curses.use_default_colors()
    curses.init_pair(1, curses.COLOR_RED, -1)
    curses.init_pair(2, curses.COLOR_CYAN, -1)
    curses.init_pair(3, curses.COLOR_GREEN, -1)
    curses.cbreak()
    curses.curs_set(1)
    (sizey, sizex) = stdscr.getmaxyx()
    input_win = curses.newwin(8, sizex, sizey-8, 0)
    output_win = curses.newwin(sizey-9, sizex, 1, 0)
    title_win = curses.newwin(1, sizex, 0, 0)
    input_win.idlok(1)
    input_win.scrollok(1)
    input_win.nodelay(1)
    input_win.leaveok(0)
    input_win.timeout(100)
    input_win.attron(curses.color_pair(3))
    output_win.idlok(1)
    output_win.scrollok(1)
    output_win.leaveok(0)
    title_win.idlok(1)
    title_win.scrollok(1)
    title_win.leaveok(0)
    return stdscr, input_win, output_win, title_win
Example #12
0
    def set_rect(self, l, t, r, b):
        """Set window coordinate"""

        if hasattr(self, 'splitter') and self.splitter:
            assert t <= self.splitter.rect[1]

        try:
            self._cwnd = curses.newwin(b - t, r - l, t, l)
            self.rect = (l, t, r, b)
        except curses.error as e:
            log.debug('error on resizing window: {} {}'.format(self,
                                                               (l, t, r, b), exc_info=True))
            # shrink window to avoid segfault in curses
            self._cwnd = curses.newwin(1, 1, 0, 0)
            self.rect = (0, 0, 1, 1)

         # surprisingly enough, the following assert fails sometime.
#        t, l = self._cwnd.getbegyx()
#        h, w = self._cwnd.getmaxyx()
#        assert (l, t, l+w, t+h) == self.rect

        self._cwnd.keypad(1)

        self._panel = curses.panel.new_panel(self._cwnd)
        self.on_setrect(*self.rect)
Example #13
0
 def start(self):
     self.stdscr = curses.initscr()
     curses.noecho()
     curses.cbreak()
     self.stdscr.keypad(True)
     self.stdscr.clear()
     self.stdscr.nodelay(True)
     curses.curs_set(False)
     self.stdscr.leaveok(False)
     curses.setsyx(*self.stdscr.getmaxyx())
     self.threadwindow = curses.newwin(self.nb_proc + 2, 70, 0, 3)
     self.threadwindow.border()
     self.threadwindow.refresh()
     self.titlewindow = curses.newwin(3, 52, self.nb_proc + 3, 28)
     self.titlewindow.border()
     self.update_titlewindow()
     self.titlewindow.refresh()
     self.threadwindow.border()
     for i, key in enumerate(self.keyboardwindows):
         self.keyboardwindows[key] = curses.newwin(
             12, 26, self.nb_proc + 5, i * 26 + 2)
         self.keyboardwindows[key].border()
         self.keyboardwindows[key].addstr(1, 1, key.title().center(24),
                                          curses.A_BOLD)
         self.keyboardwindows[key].refresh()
Example #14
0
	def __init__(self, y, x, height, width):
		self.title = curses.newwin(1, width, y, x)
		self.title.addstr("input your message and push [Ctrl + g]")
		self.title.refresh()
		self.win = curses.newwin(height, width, y+1, x)
		self.textbox = Textbox(self.win)
		self.stripspaces = True
Example #15
0
	def __get_window__(self,size="small"):
		"""
			Used to generate a sub-window.
			I will be using this when I finally get combat to work...
			inputs:	string size generates the size widow based on overall max 
					window size. Current options are: small(default), medium

			output: returns a curses window object
		"""
		if size.lower() == 'small':
			startY = int(self.maxY*.5)
			startX = int(self.maxX*.5)
			endY   = int(self.maxY*.1)
			endX   = int(self.maxX*.1)
			return curses.newwin(startY,startX,endY,endX)
		elif size.lower() == 'medium':
			startY = int(self.maxY*.5)
			startX = int(self.maxX*.5)
			endY   = int(self.maxY*.25)
			endX   = int(self.maxX*.25)
			return curses.newwin(startY,startX,endY,endX)
		else :
			startY = int(self.maxY*.5)
			startX = int(self.maxX*.5)
			endY   = int(self.maxY*.1)
			endX   = int(self.maxX*.1)
			return curses.newwin(self.maxY*.5,self.maxX*.5,self.maxY*.25,self.maxX*.25)
def main(stdscr):

    curses.noecho()
    stdscr.keypad(1)
    curses.start_color()
    win = curses.newwin(22, 79, 0, 0)
    win2 = curses.newwin(22,79,0,79)
    wina = win.subpad(18,18,1,0)
    winb = win2.subpad(18,19,1,80)
    wina.refresh()
    winb.refresh()
    win.border()
    win2.border()
    curses.init_pair(1,curses.COLOR_BLACK, curses.COLOR_WHITE) #this line enables white
    curses.init_pair(2,curses.COLOR_WHITE, curses.COLOR_BLACK)
    while True:
        c = stdscr.getch()
        if c == 260:
            wina.bkgd(curses.color_pair(1))
            winb.bkgd(curses.color_pair(2))
        if c == 261:
            winb.bkgd(curses.color_pair(1))
            wina.bkgd(curses.color_pair(2))
        wina.refresh()
        winb.refresh()
Example #17
0
File: ui.py Project: rcoh/Rally
 def create_panels(self):
   my, mx = self.maxyx
   self.new_msg_panel = curses.newwin(chat_height, mx, my-chat_height, 0)
   self.new_msg_panel.keypad(1)
   self.old_chats = curses.newwin(my-chat_height, mx, 0, 0)
   self.draw_input_box()
   self.old_chats.refresh()
Example #18
0
def setup(screen, searchstring):
    (maxy,maxx) = screen.getmaxyx()


    searchHeight=3
    infoHeight = 7
    matchHeight = maxy - searchHeight - infoHeight


    screen.refresh() 

    search = curses.newwin(searchHeight,maxx,0,0) 
    search.box() 
    search.move(1,1)
    search.addstr("Search:"+ searchstring)
    search.refresh()

    matches = curses.newwin(matchHeight, maxx,searchHeight,0)
    drawHits(matches, searchstring, 0)

    info = curses.newwin(infoHeight,maxx,matchHeight+searchHeight,0)
    infoRefresh(info,0)

    highlight = 0
    maxLight = matchHeight-1

    return search, matches, info, highlight, maxLight, 0, maxx
 def __credentials__(self):
     ''' Get display name from user '''
     self.stop_thread = False
     thread = threading.Thread(target=self.__matrix__)
     self.loading_bar.clear()
     # Get agent name
     prompt = "Account: "
     self.agent_prompt = curses.newwin(
         3,
         len(self.load_message) + 2, (self.max_y / 2) - 1,
         ((self.max_x - len(self.load_message)) / 2))
     self.agent_prompt.clear()
     self.agent_prompt.border(0)
     self.agent_prompt.addstr(1, 1, prompt, curses.A_BOLD)
     curses.echo()
     thread.start()
     self.agent_name = self.agent_prompt.getstr(
         1,
         len(prompt) + 1,
         len(self.load_message) - len(prompt) - 1)
     # Get password
     curses.noecho()
     prompt = "Password: "******"Matrix" threads to stop
Example #20
0
    def setupwindows(self, resize=False):
        """Setup and draw bannerwin and logwin

        If `resize`, don't create new windows, just adapt size. This
        function should be invoked with CursesUtils.locked()."""
        self.height, self.width = self.stdscr.getmaxyx()
        self.logheight = self.height - len(self.accframes) - 1
        if resize:
            curses.resizeterm(self.height, self.width)
            self.bannerwin.resize(1, self.width)
            self.logwin.resize(self.logheight, self.width)
        else:
            self.bannerwin = curses.newwin(1, self.width, 0, 0)
            self.logwin = curses.newwin(self.logheight, self.width, 1, 0)

        self.draw_bannerwin()
        self.logwin.idlok(True)    # needed for scrollok below
        self.logwin.scrollok(True) # scroll window when too many lines added
        self.draw_logwin()
        self.accounts = reversed(sorted(self.accframes.keys()))
        pos = self.height - 1
        index = 0
        self.hotkeys = []
        for account in self.accounts:
            acc_win = curses.newwin(1, self.width, pos, 0)
            self.accframes[account].setwindow(acc_win, index)
            self.hotkeys.append(account)
            index += 1
            pos -= 1
        curses.doupdate()
Example #21
0
def InitWindows(screen, args):
    # reset curses
    logger.handlers = []
    curses.endwin()

    # set up screen
    curses.initscr()
    screen.nodelay(1)
    curses.start_color()
    curses.cbreak()
    curses.setsyx(-1, -1)
    screen.addstr("Quake Live rcon: %s" % args.host)
    screen.refresh()
    maxy, maxx = screen.getmaxyx()

    # set up colors
    for i in range(1,7):
        curses.init_pair(i, i, 0)

    # bugfix: 5 and 6 are swapped in Quake from the standard terminal colours
    curses.init_pair(5, 6, 0)
    curses.init_pair(6, 5, 0)

    # this window holds the log and server output
    begin_x = 2; width = maxx - 4
    begin_y = 2; height = maxy - 5
    output_window = curses.newwin(height, width, begin_y, begin_x)
    screen.refresh()
    output_window.scrollok(True)
    output_window.idlok(True)
    output_window.leaveok(True)
    output_window.refresh()

    # this window takes the user commands
    begin_x = 4; width = maxx - 6
    begin_y = maxy - 2; height = 1
    input_window = curses.newwin(height, width, begin_y, begin_x)
    screen.addstr(begin_y, begin_x - 2, '>')
    screen.refresh()
    input_window.idlok(True)
    input_window.leaveok(False)
    input_window.refresh()

    # solid divider line between input and output
    begin_x = 2; width = maxx - 4
    begin_y = maxy - 3; height = 1
    divider_window = curses.newwin(height, width, begin_y, begin_x)
    screen.refresh()
    divider_window.hline(curses.ACS_HLINE, width)
    divider_window.refresh()

    # redirect logging to the log window
    mh = CursesHandler(output_window)
    formatterDisplay = logging.Formatter('%(asctime)-8s|%(name)-12s|%(levelname)-6s|%(message)-s', '%H:%M:%S')
    logger.addHandler(mh)

    # finalize layout
    screen.refresh()

    return input_window, output_window
Example #22
0
 def __init__(self, y=0, x=0, height=None, width=None):
     if width and height:
         self.window = curses.newwin(height, width, y, x)
     else:
         self.window = curses.newwin(y, x)
     self.y, self.x = y, x
     self.height, self.width = self.window.getmaxyx()
Example #23
0
    def __init__(self, screen, protocol):
        ''' 
        __init__: Initializes the application window with both a display and an input screen.

        :param screen: A curses window object, representing the root window that the application runs in
        :param protocol: A protocols.Protocol object that the application will use to communicate with
            the server.
        '''
        self.screen = screen
        curses.noecho()
        curses.cbreak()
        self.screen.keypad(1) 

        self.screen.border(0)
        height, width = self.screen.getmaxyx()
        display_window = curses.newwin(height - 10, width, 1, 1)
        display_window.box()
        input_window = curses.newwin(9, width, height-10, 1)
        input_window.box()
        self.display = DisplayScreen(display_window)
        self.input_w = InputWindow(input_window)
        input_window.move(0, 0)
        self.P = protocol

        self.current_user = None
        self.mode = -1
        self.exited = False
        self.screen.refresh()
        display_window.refresh()
        input_window.refresh()
Example #24
0
	def buildPanel(self, frame=0, border=False):
		""" Show the three windows as
			+----+--------------------+
			|    |                    |
			|    |                    |
			|    |         2          |
			| 1  |                    |
			|    |                    |
			|    |                    |
			|    +--------------------+
			|    |         3          |
			+----+--------------------+
		"""
		y, x = self.scr.getmaxyx()

		## Left Slidebar, width = ScreenWidth*0.2
		leftSlideBar = curses.newwin(y, int(x*0.2), 0, 0)
		## WorkSpace, height = ScreenHeight*0.8
		workSpace = curses.newwin(int(y*0.8), x-int(x*0.2), 0, int(x*0.2))
		## FootBar
		footBar = curses.newwin(y-int(y*0.8), x-int(x*0.2), int(y*0.8), int(x*0.2))

		ret = (leftSlideBar, workSpace, footBar)
		curses.start_color()
		curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_BLUE)
		curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_YELLOW)
		curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_GREEN)
		ret[frame].bkgd(curses.color_pair(frame+1))

		[_.box() for _ in ret]
		[ret[_].addch(1, 1, str(_)) for _ in range(len(ret))]
		footBar.addstr(" %s "%self.msg)
		[_.refresh() for _ in ret]
		return ret
Example #25
0
def main(stdscr):
    curses.curs_set(False)
    stdscr.clear()

    stdscr.addstr(0, 0, "viSort Test Build {}.{}.{}".format(VERSION, BUILD, PATCH))
    stdscr.refresh()

    ROWS, COLUMNS = curses.LINES, curses.COLS
    infoport = curses.newwin(1, COLUMNS, 1, 0)
    viewport = curses.newwin(ROWS - 2, COLUMNS, 2, 0)

    while 1:
        render_header(infoport, 'Data')

        lst = [random.randint(0, ROWS - 3) for _ in range(COLUMNS)]
        render_sort(viewport, lst)
        k = stdscr.getkey()

        render_header(infoport, 'Selection Sort')
        visualize_sort(viewport, selectionsorter, lst, 0.05)

        k = stdscr.getkey()

        render_header(infoport, 'Insertion Sort')
        visualize_sort(viewport, insertionsorter, lst, 0.001)

        k = stdscr.getkey()

        render_header(infoport, 'Merge Sort (Bottom Up)')
        visualize_sort(viewport, mergesorter, lst, 0.1)

        k = stdscr.getkey()

    k = stdscr.getkey()
 def set_up_curses(self):
     # Instantiate standard screen object.
     self.stdscr = curses.initscr()
     # Properly initialize screen.
     curses.noecho()
     curses.cbreak()
     curses.curs_set(0)
     # Check for and begin color support.
     if curses.has_colors():
         curses.start_color()
     # Optionally enable the F-1 etc. keys, which are multi-byte.
     self.stdscr.keypad(1)
     # Declare colors.
     curses.use_default_colors()
     for i in range(0, curses.COLORS):
         curses.init_pair(i + 1, i, -1)
     # Create and configure window.
     self.window = curses.newwin(curses.LINES, curses.COLS)
     self.window.chgat(curses.color_pair(198))
     self.window.nodelay(1)
     # Create and configure main half-screen subwindows.
     half_screen = curses.COLS//2
     self.attacks = curses.newwin(curses.LINES-3, half_screen, 1, 0)
     self.attacks.box()
     self.noncomb = curses.newwin(
             curses.LINES-3, half_screen, 1, half_screen)
     self.noncomb.chgat(-1, curses.color_pair(198))
     self.noncomb.box()
Example #27
0
    def make_windows(self):
        # set up windows

        start = 5
        end = 1

        space = self.y - start - end

        amount = int(space / 4)

        size_playlist = amount
        start_playlist = 5
        size_artists = amount
        start_artists = start_playlist + size_playlist
        size_albums = amount
        start_albums = start_artists + size_artists
        size_tracks = space - size_playlist - size_artists - size_albums
        start_tracks = start_albums + size_albums

        self.win_playlist = curses.newwin(size_playlist, self.x, start_playlist, 0)
        self.win_artists = curses.newwin(size_artists, self.x, start_artists, 0)
        self.win_albums = curses.newwin(size_albums, self.x, start_albums, 0)
        self.win_tracks = curses.newwin(size_tracks, self.x, start_tracks, 0)
        self.win_status = curses.newwin(end + 1, self.x, self.y - 1, 0)

        # show windows
        self.artists_control.refresh(self.win_artists)
        self.tracks_control.refresh(self.win_tracks)
        self.albums_control.refresh(self.win_albums)
        self.playlist_control.refresh(self.win_playlist)
Example #28
0
    def __init__(self, console_height, console_width):
        """Create a main screen.

        :param console_height: the height of the console
        :param console_width: the width of the console
        :return: null
        """
        # List should be two smaller in each direction because of surrounding border.
        self._dungeon_height, self._dungeon_width = console_height-2, console_width-2

        # Center the window based on the size of the console.
        display_start_y, display_start_x = util.center(console_height, console_width,
                                                       self._dungeon_height, self._dungeon_width)

        # Create window that will act as main visual.
        self._dungeon_display = curses.newwin(self._dungeon_height, self._dungeon_width, display_start_y, display_start_x)

        # Add visual detail to window.
        self._dungeon_display.bkgd(' ', curses.color_pair(1))
        util.color_border(self._dungeon_display, 0, 0, self._dungeon_height - 1, self._dungeon_width - 1, 3)

        # Initializes help window for use in pause().
        help_height, help_width = 12, 50
        help_y, help_x = util.center(console_height, console_width, help_height, help_width)
        self.help_window = curses.newwin(help_height, help_width, help_y, help_x)
Example #29
0
    def __init__(self, stdscr, config):
        """Creates a new CursesDisplay.

        stdscr: A curses main window object, as obtained from curses.wrapper() or curses.iniscr()
        config: The game configuration settings
        """
        # Make the cursor invisible
        curses.curs_set(0)
        # Make input non-blocking
        stdscr.nodelay(True)

        margin_x = (curses.COLS - config.arena_size[0] - 2) // 2
        margin_y = (curses.LINES - config.arena_size[1] - 2) // 2

        self.stdscr = stdscr
        self.config = config
        self.arena_win = curses.newwin(
            config.arena_size[1] + 2,
            config.arena_size[0] + 2,
            max(3, margin_y),
            max(0, margin_x))
        self.message_win = curses.newwin(
            1,
            curses.COLS,
            max(margin_y + config.arena_size[1] + 1, (margin_y * 3 // 2) + config.arena_size[1]),
            0)

        self.__draw_title()
        self.stdscr.refresh()
Example #30
0
	def __init__(self):
		self.stdscr = curses.initscr()
		self.WIDTH = curses.COLS
		self.HEIGHT = curses.LINES
		# dont write on screen and dont wait for enter
		curses.noecho()
		curses.cbreak()
		curses.curs_set(False) # no blinking
		curses.start_color() # colors
		# epic keys
		self.stdscr.keypad(True)
		self.stdscr = curses.newwin(self.HEIGHT-1,self.WIDTH,0,0)
		self.bottom = curses.newwin(1,self.WIDTH,self.HEIGHT-1,0)
		self.bar(default_items)
		curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
		if curses.has_colors():
			curses.init_pair(2, curses.COLOR_RED, 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_CYAN, curses.COLOR_BLACK)
		self.grapher = Grapher(self.stdscr,self.WIDTH,self.HEIGHT)
		self.painter = Painter(self.stdscr,self.WIDTH,self.HEIGHT)
		self.parser = Parser()
		self.command_hist = []
		self.command_indx = -1
Example #31
0
    def run_dialog(self, title, items, interval=2, buttons=None, y_pos=3):
        self.popup_pos = 0

        self.w = curses.newwin(
            5 + len(list(items)) * interval + (2 if buttons else 0), 50, y_pos,
            5)
        w = self.w
        out = {}
        while True:
            w.clear()
            w.border(0)
            w.addstr(0, 2, title)

            num = len(list(items))

            numpos = num
            if buttons: numpos += 2

            for i in range(num):
                item = items[i]
                label = item.get('label')
                if item.get('type') == 'list':
                    value = item.get('value', '')
                elif item.get('type') == 'satoshis':
                    value = item.get('value', '')
                elif item.get('type') == 'str':
                    value = item.get('value', '')
                elif item.get('type') == 'password':
                    value = '*' * len(item.get('value', ''))
                else:
                    value = ''
                if value is None:
                    value = ''
                if len(value) < 20:
                    value += ' ' * (20 - len(value))

                if 'value' in item:
                    w.addstr(2 + interval * i, 2, label)
                    w.addstr(
                        2 + interval * i, 15, value,
                        curses.A_REVERSE if self.popup_pos %
                        numpos == i else curses.color_pair(1))
                else:
                    w.addstr(
                        2 + interval * i, 2, label,
                        curses.A_REVERSE if self.popup_pos %
                        numpos == i else 0)

            if buttons:
                w.addstr(
                    5 + interval * i, 10, "[  ok  ]",
                    curses.A_REVERSE if self.popup_pos %
                    numpos == (numpos - 2) else curses.color_pair(2))
                w.addstr(
                    5 + interval * i, 25, "[cancel]",
                    curses.A_REVERSE if self.popup_pos %
                    numpos == (numpos - 1) else curses.color_pair(2))

            w.refresh()

            c = self.stdscr.getch()
            if c in [ord('q'), 27]: break
            elif c in [curses.KEY_LEFT, curses.KEY_UP]: self.popup_pos -= 1
            elif c in [curses.KEY_RIGHT, curses.KEY_DOWN]: self.popup_pos += 1
            else:
                i = self.popup_pos % numpos
                if buttons and c == 10:
                    if i == numpos - 2:
                        return out
                    elif i == numpos - 1:
                        return {}

                item = items[i]
                _type = item.get('type')

                if _type == 'str':
                    item['value'] = self.edit_str(item['value'], c)
                    out[item.get('label')] = item.get('value')

                elif _type == 'password':
                    item['value'] = self.edit_str(item['value'], c)
                    out[item.get('label')] = item['value']

                elif _type == 'satoshis':
                    item['value'] = self.edit_str(item['value'], c, True)
                    out[item.get('label')] = item.get('value')

                elif _type == 'list':
                    choices = item.get('choices')
                    try:
                        j = choices.index(item.get('value'))
                    except Exception:
                        j = 0
                    new_choice = choices[(j + 1) % len(choices)]
                    item['value'] = new_choice
                    out[item.get('label')] = item.get('value')

                elif _type == 'button':
                    out['button'] = item.get('label')
                    break

        return out
Example #32
0
import random
import curses

s = curses.initscr()
curses.curs_set(0)
sh, sw = s.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)

snk_x = sw / 4
snk_y = sh / 2
snake = [[snk_y, snk_x], [snk_y, snk_x - 1], [snk_y, snk_x - 2]]

food = [sh / 2, sw / 2]
w.addch(int(food[0]), int(food[1]), curses.ACS_PI)

key = curses.KEY_RIGHT

while True:
    next_key = w.getch()
    key = key if next_key == -1 else next_key

    if snake[0][0] in [0, sh] or snake[0][1] in [0, sw
                                                 ] or snake[0] in snake[1:]:
        curses.endwin()
        quit()
    new_head = [snake[0][0], snake[0][1]]

    if key == curses.KEY_DOWN:
        new_head[0] += 1
Example #33
0
def curses_main(stdscr: typing.Any, cmd_autostart_plotting: typing.Optional[bool], cmd_autostart_archiving: typing.Optional[bool], cfg: configuration.PlotmanConfig) -> None:
    log = Log()

    if cmd_autostart_plotting is not None:
        plotting_active = cmd_autostart_plotting
    else:
        plotting_active = cfg.commands.interactive.autostart_plotting

    archiving_configured = cfg.archiving is not None

    if not archiving_configured:
        archiving_active = False
    elif cmd_autostart_archiving is not None:
        archiving_active = cmd_autostart_archiving
    else:
        archiving_active = cfg.commands.interactive.autostart_archiving

    plotting_status = '<startup>'    # todo rename these msg?
    archiving_status: typing.Union[bool, str, typing.Dict[str, object]] = '<startup>'

    stdscr.nodelay(True)  # make getch() non-blocking
    stdscr.timeout(2000)

    # Create windows.  We'll size them in the main loop when we have their content.
    header_win = curses.newwin(1, 1, 1, 0)
    log_win = curses.newwin(1, 1, 1, 0)
    jobs_win = curses.newwin(1, 1, 1, 0)
    dirs_win = curses.newwin(1, 1, 1, 0)

    jobs = Job.get_running_jobs(cfg.logging.plots)
    last_refresh = None

    pressed_key = ''   # For debugging

    archdir_freebytes = None
    aging_reason = None

    while True:

        # A full refresh scans for and reads info for running jobs from
        # scratch (i.e., reread their logfiles).  Otherwise we'll only
        # initialize new jobs, and mostly rely on cached info.
        do_full_refresh = False
        elapsed = 0    # Time since last refresh, or zero if no prev. refresh
        if last_refresh is None:
            do_full_refresh = True
        else:
            elapsed = (datetime.datetime.now() - last_refresh).total_seconds()
            do_full_refresh = elapsed >= cfg.scheduling.polling_time_s

        if not do_full_refresh:
            jobs = Job.get_running_jobs(cfg.logging.plots, cached_jobs=jobs)

        else:
            last_refresh = datetime.datetime.now()
            jobs = Job.get_running_jobs(cfg.logging.plots)

            if plotting_active:
                (started, msg) = manager.maybe_start_new_plot(
                    cfg.directories, cfg.scheduling, cfg.plotting, cfg.logging
                )
                if (started):
                    if aging_reason is not None:
                        log.log(aging_reason)
                        aging_reason = None
                    log.log(msg)
                    plotting_status = '<just started job>'
                    jobs = Job.get_running_jobs(cfg.logging.plots, cached_jobs=jobs)
                else:
                    # If a plot is delayed for any reason other than stagger, log it
                    if msg.find("stagger") < 0:
                        aging_reason = msg
                    plotting_status = msg
                root_logger.info('[plot] %s', msg)

            if cfg.archiving is not None:
                if archiving_active:
                    archiving_status, log_messages = archive.spawn_archive_process(cfg.directories, cfg.archiving, cfg.logging, jobs)
                    if log_messages:
                        for log_message in log_messages:
                            log.log(log_message)
                            root_logger.info('[archive] %s', log_message)
                    else:
                        root_logger.info('[archive] %s', archiving_status)

                archdir_freebytes, log_messages = archive.get_archdir_freebytes(cfg.archiving)
                for log_message in log_messages:
                    log.log(log_message)


        # Get terminal size.  Recommended method is stdscr.getmaxyx(), but this
        # does not seem to work on some systems.  It may be a bug in Python
        # curses, maybe having to do with registering sigwinch handlers in
        # multithreaded environments.  See e.g.
        #     https://stackoverflow.com/questions/33906183#33906270
        # Alternative option is to call out to `stty size`.  For now, we
        # support both strategies, selected by a config option.
        # TODO: also try shutil.get_terminal_size()
        n_rows: int
        n_cols: int
        if cfg.user_interface.use_stty_size:
            completed_process = subprocess.run(
                ['stty', 'size'], check=True, encoding='utf-8', stdout=subprocess.PIPE
            )
            elements = completed_process.stdout.split()
            (n_rows, n_cols) = [int(v) for v in elements]
        else:
            (n_rows, n_cols) = map(int, stdscr.getmaxyx())

        stdscr.clear()
        stdscr.resize(n_rows, n_cols)
        curses.resize_term(n_rows, n_cols)

        #
        # Obtain and measure content
        #

        # Directory prefixes, for abbreviation
        tmp_prefix = os.path.commonpath(cfg.directories.tmp)
        dst_dir = cfg.directories.get_dst_directories()
        dst_prefix = os.path.commonpath(dst_dir)
        if archdir_freebytes is not None:
            archive_directories = list(archdir_freebytes.keys())
            if len(archive_directories) == 0:
                arch_prefix = ''
            else:
                arch_prefix = os.path.commonpath(archive_directories)

        n_tmpdirs = len(cfg.directories.tmp)

        # Directory reports.
        tmp_report = reporting.tmp_dir_report(
            jobs, cfg.directories, cfg.scheduling, n_cols, 0, n_tmpdirs, tmp_prefix)
        dst_report = reporting.dst_dir_report(
            jobs, dst_dir, n_cols, dst_prefix)
        if archdir_freebytes is not None:
            arch_report = reporting.arch_dir_report(archdir_freebytes, n_cols, arch_prefix)
            if not arch_report:
                arch_report = '<no archive dir info>'
        else:
            arch_report = '<archiving not configured>'

        #
        # Layout
        #

        tmp_h = len(tmp_report.splitlines())
        tmp_w = len(max(tmp_report.splitlines(), key=len)) + 1
        dst_h = len(dst_report.splitlines())
        dst_w = len(max(dst_report.splitlines(), key=len)) + 1
        arch_h = len(arch_report.splitlines()) + 1
        arch_w = n_cols

        header_h = 3
        dirs_h = max(tmp_h, dst_h) + arch_h
        remainder = n_rows - (header_h + dirs_h)
        jobs_h = max(5, math.floor(remainder * 0.6))
        logs_h = n_rows - (header_h + jobs_h + dirs_h)

        header_pos = 0
        jobs_pos = header_pos + header_h
        stdscr.resize(n_rows, n_cols)
        dirs_pos = jobs_pos + jobs_h
        logscreen_pos = dirs_pos + dirs_h

        linecap = n_cols - 1
        logs_h = n_rows - (header_h + jobs_h + dirs_h)

        try:
            header_win = curses.newwin(header_h, n_cols, header_pos, 0)
            log_win = curses.newwin(logs_h, n_cols, logscreen_pos, 0)
            jobs_win = curses.newwin(jobs_h, n_cols, jobs_pos, 0)
            dirs_win = curses.newwin(dirs_h, n_cols, dirs_pos, 0)
        except Exception:
            raise Exception('Failed to initialize curses windows, try a larger '
                            'terminal window.')

        #
        # Write
        #

        # Header
        header_win.addnstr(0, 0, 'Plotman', linecap, curses.A_BOLD)
        timestamp = datetime.datetime.now().strftime("%H:%M:%S")
        refresh_msg = "now" if do_full_refresh else f"{int(elapsed)}s/{cfg.scheduling.polling_time_s}"
        header_win.addnstr(f" {timestamp} (refresh {refresh_msg})", linecap)
        header_win.addnstr('  |  <P>lotting: ', linecap, curses.A_BOLD)
        header_win.addnstr(
                plotting_status_msg(plotting_active, plotting_status), linecap)
        header_win.addnstr(' <A>rchival: ', linecap, curses.A_BOLD)
        header_win.addnstr(
                archiving_status_msg(archiving_configured,
                    archiving_active, archiving_status), linecap)  # type: ignore[arg-type]

        # Oneliner progress display
        header_win.addnstr(1, 0, 'Jobs (%d): ' % len(jobs), linecap)
        header_win.addnstr('[' + reporting.job_viz(jobs) + ']', linecap)

        # These are useful for debugging.
        # header_win.addnstr('  term size: (%d, %d)' % (n_rows, n_cols), linecap)  # Debuggin
        # if pressed_key:
            # header_win.addnstr(' (keypress %s)' % str(pressed_key), linecap)
        header_win.addnstr(2, 0, 'Prefixes:', linecap, curses.A_BOLD)
        header_win.addnstr('  tmp=', linecap, curses.A_BOLD)
        header_win.addnstr(tmp_prefix, linecap)
        header_win.addnstr('  dst=', linecap, curses.A_BOLD)
        header_win.addnstr(dst_prefix, linecap)
        if archiving_configured:
            header_win.addnstr('  archive=', linecap, curses.A_BOLD)
            header_win.addnstr(arch_prefix, linecap)
        header_win.addnstr(' (remote)', linecap)


        # Jobs
        jobs_win.addstr(0, 0, reporting.status_report(jobs, n_cols, jobs_h,
            tmp_prefix, dst_prefix))
        jobs_win.chgat(0, 0, curses.A_REVERSE)

        # Dirs
        tmpwin_dstwin_gutter = 6

        maxtd_h = max([tmp_h, dst_h])

        tmpwin = curses.newwin(
                    tmp_h, tmp_w,
                    dirs_pos + int(maxtd_h - tmp_h), 0)
        tmpwin.addstr(tmp_report)
        tmpwin.chgat(0, 0, curses.A_REVERSE)

        dstwin = curses.newwin(
                dst_h, dst_w,
                dirs_pos + int((maxtd_h - dst_h) / 2), tmp_w + tmpwin_dstwin_gutter)
        dstwin.addstr(dst_report)
        dstwin.chgat(0, 0, curses.A_REVERSE)

        archwin = curses.newwin(arch_h, arch_w, dirs_pos + maxtd_h, 0)
        archwin.addstr(0, 0, 'Archive dirs free space', curses.A_REVERSE)
        archwin.addstr(1, 0, arch_report)

        # Log.  Could use a pad here instead of managing scrolling ourselves, but
        # this seems easier.
        log_win.addnstr(0, 0, ('Log: %d (<up>/<down>/<end> to scroll)\n' % log.get_cur_pos() ),
                linecap, curses.A_REVERSE)
        for i, logline in enumerate(log.cur_slice(logs_h - 1)):
            log_win.addnstr(i + 1, 0, logline, linecap)

        stdscr.noutrefresh()
        header_win.noutrefresh()
        jobs_win.noutrefresh()
        tmpwin.noutrefresh()
        dstwin.noutrefresh()
        archwin.noutrefresh()
        log_win.noutrefresh()
        curses.doupdate()

        try:
            key = stdscr.getch()
        except KeyboardInterrupt:
            key = ord('q')

        if key == curses.KEY_UP:
            log.shift_slice(-1)
            pressed_key = 'up'
        elif key == curses.KEY_DOWN:
            log.shift_slice(1)
            pressed_key = 'dwn'
        elif key == curses.KEY_END:
            log.shift_slice_to_end()
            pressed_key = 'end'
        elif key == ord('p'):
            plotting_active = not plotting_active
            pressed_key = 'p'
        elif key == ord('a'):
            archiving_active = not archiving_active
            pressed_key = 'a'
        elif key == ord('q'):
            break
        else:
            pressed_key = key
Example #34
0
import time
import curses

stdscr = curses.initscr()
begin_x = 20
begin_y = 7
height = 5
width = 40
win = curses.newwin(height, width, begin_y, begin_x)

time.sleep(10)
Example #35
0
def run(stdscr):
    global ip
    ip = proxy.server_address
    stdscr.clear()
    (max_y, max_x) = stdscr.getmaxyx()
    column_width = 30
    begin_x = 0
    begin_y = 0
    height = max_y - 2
    width = max_x - column_width

    #a changer peut etre v
    curses.curs_set(0)

    #creation de la window de thread_Pull
    chat_win = curses.newwin(height, width, begin_y, begin_x)
    chat_win.refresh()

    #creation window de statubar
    status_win = curses.newwin(2, max_x, height, 0)
    # message_Win.border()
    status_win.refresh()

    #creation de la windows de thread_users
    users_win = curses.newwin(int(max_y / 2), column_width, 0, width)
    users_win.border()
    users_win.addstr(0, 1, 'Connected users')
    users_win.refresh()

    #creation de la windows de thread_tables
    tables_win = curses.newwin(int(max_y / 2 - 1.5), column_width,
                               int(max_y / 2), width)
    tables_win.border()
    tables_win.addstr(0, 1, 'Tables')
    tables_win.refresh()

    #on run le Thread des pull messages
    pull_thread = Thread(target=pull,
                         args=(
                             chat_win,
                             users_win,
                             tables_win,
                             status_win,
                         ))
    pull_thread.start()
    while True:
        status_win.addstr(0, 0, get_statusbar(max_x), curses.A_REVERSE)
        status_win.addstr(1, 0, '$ ')
        status_win.refresh()
        editwin = curses.newwin(1, max_x, max_y - 1, 2)
        box = textpad.Textbox(editwin)
        box.edit()
        text = box.gather().strip()
        if len(text) == 0:
            continue
        message = proxy.push_message(text)
        if message == 'quit':
            proxy.quit()
            pull_thread.join()
            exit(0)
        elif message == 'clear':
            global lines
            lines = []
            chat_win.clear()
            chat_win.refresh()
Example #36
0
	def setposition(self,x,y):
		self.xpos=x
		self.ypos=y
		self.window=curses.newwin(self.width,self.height,x,y)
Example #37
0
	def __init__(self,ancho,alto):
		self.width=0
		self.height=0
		self.xpos=0
		self.ypos=0
		self.window=curses.newwin(ancho,alto)
Example #38
0
    def __init__(self,
                 starty,
                 maxx,
                 width,
                 text_file_path,
                 height,
                 menu_items,
                 partition=False,
                 popupWindow=False,
                 install_config={},
                 text_items=[],
                 table_space=0,
                 default_start=0,
                 info=[],
                 size_left=[]):
        self.head_position = 0  #This is the start of showing
        self.menu_position = default_start
        self.lines = []
        self.menu_items = menu_items
        self.text_items = text_items
        self.table_space = table_space
        self.info = info
        self.size_left = size_left

        self.width = width

        if partition == False:
            self.read_file(text_file_path, self.width - 3)
        else:
            self.install_config = install_config
            self.partition()

        self.num_items = len(self.lines)
        if self.info:
            self.text_height = height - 4
        else:
            self.text_height = height - 2

        # Check if we need to add a scroll bar
        if self.num_items > self.text_height:
            self.show_scroll = True
        else:
            self.show_scroll = False

        # Some calculation to detitmine the size of the scroll filled portion
        if (self.num_items == 0):
            self.filled = 0
        else:
            self.filled = int(
                round(self.text_height * self.text_height /
                      float(self.num_items)))
        if self.filled == 0:
            self.filled += 1
        for i in [1, 2]:
            if (self.num_items - self.text_height) >= i and (
                    self.text_height - self.filled) == (i - 1):
                self.filled -= 1

        self.window = curses.newwin(height, self.width)
        self.window.bkgd(' ', curses.color_pair(2))
        self.popupWindow = popupWindow

        self.window.keypad(1)
        self.panel = curses.panel.new_panel(self.window)

        self.panel.move(starty, (maxx - self.width) // 2)
        self.panel.hide()
        curses.panel.update_panels()
Example #39
0
            delay_ms = int(sys.argv[2])

    maze = Field(maze_fname)
    goal = Node(maze.cols - 2, maze.rows - 2, None, None)
    start = Node(1, 1, None, goal)
    s = Astar(start, goal, maze.isInBounds, 9999)
    success = False

    # curses setup
    def exit_gracefully(*_):
        curses.endwin()
        sys.exit()

    curses.initscr()
    curses.noecho()
    win = curses.newwin(maze.rows+10, maze.cols+10)
    signal.signal(signal.SIGINT, exit_gracefully)

    # run astar
    while s.openset.size() > 0:
        done, node, node_g, counter = s.search()

        # output to curses
        win.erase()
        win.addstr(maze.toString(s.openset, s.closedset, node))
        win.addstr("iterations: {:<6}\n".format(counter))
        win.addstr("path cost: {:.2f}".format(node_g))
        win.refresh()

        if done:
            success = True
Example #40
0
def asteroidPuzzle(gametime, debug=False):
    # Disable buttons while printing
    if not debug:
        disableButton()

    pygame.mixer.init()
    pygame.init()  #turn all of pygame on.
    hit_sound = pygame.mixer.Sound('puzzles/asteroids/hit.wav')

    clearScreen()

    printOut(
        '--- WARNING! ---\nESCAPE POD NOW ENTERING HIGHLY DENSE ASTEROID FIELD'
    )
    printOut(
        'MAIN MONITOR WILL BE DISABLED TO CONSERVE POWER FOR EVASIVE MANEUVERS\nMANUAL NAVIGATION REQUIRED\nMANUAL CONTROLS LOCATED TO YOUR LEFT'
    )
    printOut('ENTERING FIELD IN')
    for i in [3, 2, 1]:
        print(i)
        time.sleep(1)

    os.system("killall -s SIGINT omxplayer.bin")

    clearScreen()
    pygame.mixer.music.load('puzzles/asteroids/moon.wav')
    pygame.mixer.music.play(-1)

    timeout = time.time() + TIMEOUT
    speed = SPEED
    curses.initscr()
    win = curses.newwin(HEIGHT, WIDTH, 0, 0)
    win.keypad(1)
    curses.noecho()
    curses.curs_set(0)
    win.border(0)
    win.nodelay(1)

    player = Player()
    win.addch(player.y, player.x, player.getIcon())

    key = None

    asteroids = []

    interval = time.time()
    curr_time = time.time()

    # Enable buttons
    if not debug:
        disableButton(False)

    while True:
        if time.time() > timeout:
            break
        if time.time() > curr_time + 5:
            speed *= RATE
            curr_time = time.time()
        win.border(0)
        win.addstr(0, 0, 'Time Left : {:.2f} '.format(timeout - time.time()))
        win.addstr(HEIGHT - 1, 1, 'Deaths : {} '.format(player.deaths()))
        if debug:
            win.addstr(HEIGHT - 1, WIDTH - 13, 'Speed : {:.2f}'.format(speed))

        event = win.getch()
        key = None if event == -1 else event

        if key == ord('a'):
            player.left()
            win.addch(player.y, player.x, player.getIcon())
            win.addch(player.y, player.x + 1, ' ')
        if key == ord('d'):
            player.right()
            win.addch(player.y, player.x, player.getIcon())
            win.addch(player.y, player.x - 1, ' ')

        if time.time() > player.last_death + 1:
            player.setIcon()

        if time.time() > interval + speed:
            win.addch(player.y, player.x, player.getIcon())
            for i in range(0, NUM_ASTEROIDS):
                first = Asteroid()
                asteroids.append(first)
            for asteroid in asteroids:
                asteroid.fall()
                if asteroid.exist:
                    if hit(player, asteroid, hit_sound):
                        player.setIcon('*')
                        win.addch(player.y, player.x, player.getIcon())
                        win.addch(asteroid.y - 1, asteroid.x, ' ')
                    else:
                        win.addch(asteroid.y, asteroid.x, '@')
                        win.addch(asteroid.y - 1, asteroid.x, ' ')
            interval = time.time()

    curses.endwin()
    pygame.mixer.music.fadeout(2000)

    # Disable buttons
    if not debug:
        disableButton()

    clearScreen()
    printOut('NAVIGATION THROUGH ASTEROID FIELD COMPLETE...')
    printOut('POD WAS HIT {} TIME{}'.format(
        player.deaths(), '' if player.deaths() == 1 else 'S'))
    printOut('\n\n--- POD STATUS ---')
    m, s = divmod(gametime - time.time(), 60)
    printOut(
        'ENGINE STATUS:\tOK\nHYPERDRIVE:\tOFFLINE\nLIFE SUPPORT:\tLIMITED - {:.0f} MINUTE{} {} SECONDS REMAINING'
        .format(m, 'S' if m >= 2.0 else '', int(s)))

    return player.deaths()
Example #41
0
import curses as cs
from curses import panel as pnl

#init screen
scr = cs.initscr()
scr.keypad(1)
cs.noecho()
cs.curs_set(False)

cs.start_color()
cs.init_pair(1, cs.COLOR_BLACK, cs.COLOR_GREEN)

window = cs.newwin(5, 5, 3, 5)
window.box()
panel = pnl.new_panel(window)

window2 = cs.newwin(15, 15, 2, 4)
window2.box()
window2.addstr(1, 1, 'Back window')
panel2 = pnl.new_panel(window2)

running = True
while running:
    pnl.update_panels()
    cs.doupdate()
    key = scr.getch()
    if key == 27:
        running = False
    if key == ord('w'):
        window.bkgd(' ', cs.color_pair(1))
    if key == ord('s'):
    def __init__(self):
        # Initialize the screen and three sub-windows (chat, input, users).
        self.screen = curses.initscr()
        self.screen.hline(TOP_BORDER_Y, TOP_BORDER_X, curses.ACS_HLINE,
                          curses.COLS)

        # THE FOLLOWING IS FOR CHATWINDOW
        self.screen.hline(3, 1, curses.ACS_HLINE,
                          curses.COLS - 25)  # Top Border
        self.screen.hline(3, 1, curses.ACS_ULCORNER, 1)  # Upper-Left Corner
        self.screen.hline(3, curses.COLS - 25, curses.ACS_URCORNER,
                          1)  # Upper-Right Corner
        self.screen.vline(4, 1, curses.ACS_VLINE,
                          curses.LINES - 7)  # Left Border
        self.screen.vline(4, curses.COLS - 25, curses.ACS_VLINE,
                          curses.LINES - 7)  # Right Border
        self.screen.hline(curses.LINES - 7, 1, curses.ACS_HLINE,
                          curses.COLS - 25)  # Bottom Border
        self.screen.hline(curses.LINES - 7, 1, curses.ACS_LLCORNER,
                          1)  # Bottom-left Border
        self.screen.hline(curses.LINES - 7, curses.COLS - 25,
                          curses.ACS_LRCORNER, 1)  # Bottom-right Border

        # THE FOLLOWING IS FOR INPUTWINDOW
        self.screen.hline(curses.LINES - 6, 1, curses.ACS_HLINE,
                          curses.COLS - 25)  # Top Border
        self.screen.hline(curses.LINES - 6, 1, curses.ACS_ULCORNER,
                          1)  # Upper-Left Corner
        self.screen.hline(curses.LINES - 6, curses.COLS - 25,
                          curses.ACS_URCORNER, 1)  # Upper-Right Corner
        self.screen.vline(curses.LINES - 5, 1, curses.ACS_VLINE,
                          1)  # Left Border
        self.screen.vline(curses.LINES - 5, curses.COLS - 25, curses.ACS_VLINE,
                          1)  # Right Border
        self.screen.hline(curses.LINES - 4, 1, curses.ACS_HLINE,
                          curses.COLS - 25)  # Bottom Border
        self.screen.hline(curses.LINES - 4, 1, curses.ACS_LLCORNER,
                          1)  # Bottom-left Border
        self.screen.hline(curses.LINES - 4, curses.COLS - 25,
                          curses.ACS_LRCORNER, 1)  # Bottom-right Border

        # THE FOLLOWING IS FOR USERWINDOW
        self.screen.hline(3, curses.COLS - 24, curses.ACS_HLINE,
                          20)  # Top Border
        self.screen.hline(curses.LINES - 17, curses.COLS - 24,
                          curses.ACS_HLINE, 20)  # Bottom Border
        self.screen.vline(4, curses.COLS - 24, curses.ACS_VLINE,
                          curses.LINES - 21)  # Left Border
        self.screen.vline(4, curses.COLS - 4, curses.ACS_VLINE,
                          curses.LINES - 21)  # Right Border
        self.screen.hline(3, curses.COLS - 24, curses.ACS_ULCORNER,
                          1)  # Upper-left Corner
        self.screen.hline(3, curses.COLS - 4, curses.ACS_URCORNER,
                          1)  # Upper-right Corner
        self.screen.hline(curses.LINES - 17, curses.COLS - 24,
                          curses.ACS_LLCORNER, 1)  # Bottom-left Corner
        self.screen.hline(curses.LINES - 17, curses.COLS - 4,
                          curses.ACS_LRCORNER, 1)  # Bottom-right Corner

        # THE FOLLOWING IS FOR CHANNELWINDOW
        self.screen.hline(curses.LINES - 16, curses.COLS - 24,
                          curses.ACS_HLINE, 20)  # Top Border
        self.screen.hline(curses.LINES - 4, curses.COLS - 24, curses.ACS_HLINE,
                          20)  # Bottom Border
        self.screen.vline(curses.LINES - 15, curses.COLS - 24,
                          curses.ACS_VLINE, curses.LINES - 27)  # Left Border
        self.screen.vline(curses.LINES - 15, curses.COLS - 4, curses.ACS_VLINE,
                          curses.LINES - 27)  # Right Border
        self.screen.hline(curses.LINES - 16, curses.COLS - 24,
                          curses.ACS_ULCORNER, 1)  # Upper-left Corner
        self.screen.hline(curses.LINES - 16, curses.COLS - 4,
                          curses.ACS_URCORNER, 1)  # Upper-right Corneer
        self.screen.hline(curses.LINES - 4, curses.COLS - 24,
                          curses.ACS_LLCORNER, 1)  # Bottom-left Corner
        self.screen.hline(curses.LINES - 4, curses.COLS - 4,
                          curses.ACS_LRCORNER, 1)  # Bottom-right Corner

        self.screen.addstr(0, curses.COLS / 3,
                           "The Super-Fantastic LizChat 1.0")  # Clever title
        self.chatWindow = curses.newwin(curses.LINES - 11, curses.COLS - 27,
                                        CHAT_Y, 2)  # Chat Window
        self.inputWindow = curses.newwin(1, curses.COLS - 27, curses.LINES - 5,
                                         2)  # Input Window
        self.userWindow = curses.newwin(curses.LINES - 11, 18, CHAT_Y,
                                        curses.COLS - 23)  # User Window
        self.channelWindow = curses.newwin(11, 19, curses.LINES - 15,
                                           curses.COLS - 23)  # Channels Window

        self.chatWindow.scrollok(True)
        self.userWindow.scrollok(True)
        self.channelWindow.scrollok(True)
        curses.noecho()

        self.screen.refresh()
        self.chatWindow.refresh()
        self.inputWindow.refresh()
Example #43
0
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_CYAN, curses.COLOR_BLACK)

# BEGIN PROGRAM
screen.addstr('RANMOM QUOTES', curses.A_REVERSE)
screen.chgat(-1, curses.A_REVERSE)
screen.addstr(curses.LINES - 1, 0, 'Press R to request a new quote, Q to quit')

# Change the R to green
screen.chgat(curses.LINES - 1, 6, 1, curses.A_BOLD | curses.color_pair(2))
# Change the Q to green
screen.chgat(curses.LINES - 1, 32, 1, curses.A_BOLD | curses.color_pair(1))
# Set up the window to hold the random quotes

quote_window = curses.newwin(curses.LINES - 2, curses.COLS, 1, 0)
#Create a sub-window so as to cleanly display the quote without worrying
# about overwriting the quote windowo's border
quote_text_window = quote_window.subwin(curses.LINES - 6, curses.COLS - 4, 3,
                                        2)
quote_text_window.addstr('Press R to get your first quote')
# Draw a border around the main quote window
quote_window.box()
# Update the internal window data structures
screen.noutrefresh()
quote_window.noutrefresh()
# Redraw the screen
curses.doupdate()
# Create the event loop
while True:
    c = quote_window.getch()
Example #44
0
import curses
import random

races = ['Human', 'Flying Eyeball', 'Robot', 'Dino-person']

curses.initscr()

try:
    win = curses.newwin(0, 0)
    win.addstr(0, 2, 'What is thy name? ')
    pcname = win.getstr()
    win.clear()
    win.refresh()
    y = 0
    for race in races:
        win.addstr(y, 2, (str(y) + ': ' + str(race)))
        y += 1
    win.addstr(6, 2, 'Choose thine race: ')
    racechoice = win.getstr()

    # starts the pc in a random position
    pcy = random.randint(1, 10)
    pcx = random.randint(1, 10)
    # hides the cursor
    curses.curs_set(0)
    # draws the playfield and UI
    while True:
        win.clear()
        win.refresh()
        liney = 0
        while liney != 21:
Example #45
0
def game(r, c, y, x):
    rows = r
    cols = c
    begin_y = y
    begin_x = x

    # Create game window
    curses.initscr()
    window = curses.newwin(rows, cols, y, x)
    window.keypad(1)
    curses.noecho()
    curses.curs_set(0)
    window.border(0)
    window.nodelay(1)
    window.addstr(0, 21, " STAY ALIVE! ")
    dimensions = window.getmaxyx()

    # initialize player
    player = Player(dimensions)

    # initialize Enemy Management, #1 corporation in killing players
    mgmt = EnemyManager(window, dimensions)

    # draw player
    window.addch(player.y, player.x, ord('@'))

    # Game variables
    gameover = False
    key = None
    start_time = time.time()
    loop_count = -1

    # game loop
    while key != ord('q'):
        # loop tracking
        loop_count += 1
        window.addstr(0, 40, " Loops: {} ".format(loop_count))

        # Time keeping
        seconds = format_time(start_time)
        window.addstr(0, 2, " Time: {} ".format(seconds))

        # Player movement
        key = window.getch()
        window.addch(player.y, player.x, ord(' '))
        player.move(key)
        window.addch(player.y, player.x, ord('@'))

        ### Enemy actions ###
        # Show information
        window.addstr(19, 2, " Enemies: {} ".format(len(mgmt.employees)))
        window.addstr(19, 20, " Limit: {} ".format(mgmt.employee_limit))
        window.addstr(19, 40, " Level: {} ".format(mgmt.level))

        # Spawn enemies
        if len(mgmt.employees) < mgmt.employee_limit and loop_count > 5000:
            if mgmt.level <= 2:
                mgmt.spawn(window, 0)
            elif mgmt.level <= 4 and mgmt.level > 2:
                if randint(0, 10) < 5:
                    mgmt.spawn(window, 0)
                else:
                    mgmt.spawn(window, 1)
            elif mgmt.level <= 8 and mgmt.level > 4:
                rn = randint(0, 30)
                if rn < 10:
                    mgmt.spawn(window, 0)
                elif rn >= 10 and rn < 20:
                    mgmt.spawn(window, 1)
                else:
                    mgmt.spawn(window, 2)
            else:
                rn = randint(0, 40)
                if rn < 10:
                    mgmt.spawn(window, 0)
                elif rn >= 10 and rn < 20:
                    mgmt.spawn(window, 1)
                elif rn >= 20 and rn < 30:
                    mgmt.spawn(window, 2)
                else:
                    mgmt.spawn(window, 3)

        # move enemies
        mgmt.move_employees(loop_count)

        # check player collisions
        for e in mgmt.employees:
            if e.y == player.y and e.x == player.x:
                gameover = True

        # increase level
        mgmt.increase_level(loop_count)

        # pause game, NOTE: F***s up time keeping but fixable
        if key == ord(' '):
            key = -1
            while key != ord(' '):
                key = window.getch()
            continue

        if gameover:
            key = ord('q')

    curses.beep()
    curses.endwin()
    score = "Level: {}, Time: {}, Loop Count: {}\n".format(
        mgmt.level, seconds, loop_count)
    print "Gameover."
    print "Stats: " + score

    # write scores to a file
    with open('scores.txt', 'a') as filewriter:
        filewriter.write(score)
Example #46
0
def drawWin(h, w, x, y):
    # create a new window oject of the specified h(eight), w(idth), begin y, and begin x
    return curses.newwin(h, w, y, x)
Example #47
0
 def __init__(self, frame, delegate=None, can_become_first_responder=True):
     window = curses.newwin(frame.size.h, frame.size.w, frame.origin.y,
                            frame.origin.x)
     super(Panel, self).__init__(window, delegate,
                                 can_become_first_responder)
     self.panel = curses.panel.new_panel(window)
Example #48
0
def main(stdscr):
    height, width = stdscr.getmaxyx()  # get the window size
    curses.start_color()
    curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
    curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_CYAN, curses.COLOR_BLACK)

    # header
    stdscr.addstr(1, 1, " " * (width - 2), curses.color_pair(1))
    stdscr.addstr(1, 1, "Plant Monitor", curses.color_pair(1))
    stdscr.hline(2, 1, "_", width)

    # footer
    stdscr.addstr(height - 1, 1, " " * (width - 2), curses.color_pair(1))
    stdscr.addstr(height - 1, 1, "Hit q to quit", curses.color_pair(1))

    prev_ch0, prev_ch1, prev_ch2, prev_ch3 = get_all_data()

    # load in soil data
    last_n, days_old = load_soil_data(30)
    dates = []
    times = []
    s0_data = []
    s1_data = []
    s2_data = []
    s3_data = []

    # split out soil data
    for line in last_n:
        dates.append(line[0])
        times.append(line[1])
        s0_data.append(float(line[2]))
        s1_data.append(float(line[3]))
        s2_data.append(float(line[4]))
        s3_data.append(float(line[5]))
    # remove this print statement later:
    stdscr.addstr(height - 3, 1, str(days_old))

    # gregarious monstera ascii art
    with open('med_monstera.txt', 'r') as leaves:
        leaf_array = leaves.read().split('\n')
        i = height - len(leaf_array)
        for row in leaf_array:
            stdscr.addstr(i, width - 50, row)
            i += 1
    leaves.close()

    # Define windows to be used for bar charts
    # curses.newwin(height, width, begin_y, begin_x)
    win0 = curses.newwin(13, 54, 3, 1)
    win1 = curses.newwin(13, 54, 17, 1)
    win2 = curses.newwin(13, 54, 31, 1)
    win3 = curses.newwin(13, 54, 3, 56)

    k = 0
    written_today = False
    while True:
        if k != ord('q'):
            # read data values
            ch0_voltage, ch1_voltage, ch2_voltage, ch3_voltage = get_all_data()

            # these will hopefully cutdown on times that we render the graphs
            if prev_ch0 != ch0_voltage:
                prev_ch0 = ch0_voltage
                win0.clear()

            if prev_ch1 != ch1_voltage:

                prev_ch1 = ch1_voltage
                win1.clear()

            if prev_ch2 != ch2_voltage:
                prev_ch2 = ch2_voltage
                win2.clear()

            if prev_ch3 != ch3_voltage:
                prev_ch3 = ch3_voltage
                win3.clear()

            now = datetime.now()
            stdscr.addstr(1, width - 10, now.strftime("%x"),
                          curses.color_pair(1))
            # write to csv once a day
            # not sure the logic for this checks out...
            if len(last_n) != 0:
                if last_n[len(last_n) - 1][0] != now.strftime(
                        "%x") and written_today == False:
                    with open('soil_data.txt', 'a') as soil_data:
                        soil_data.write(
                            now.strftime("%x") + ',' + now.strftime("%X") +
                            ',' + str(ch0_voltage) + ',' + str(ch1_voltage) +
                            ',' + str(ch2_voltage) + ',' + str(ch3_voltage) +
                            "\n")
                    written_today = True
                    soil_data.close()

            #draw_sensor_win(window, dates, data, number=0):
            draw_sensor_win(win0, dates, s0_data, 0)
            draw_sensor_win(win1, dates, s1_data, 1)
            draw_sensor_win(win2, dates, s2_data, 2)
            draw_sensor_win(win3, dates, s3_data, 3)

            # refresh windows
            win0.refresh()
            win1.refresh()
            win2.refresh()
            win3.refresh()

            #stdscr.refresh()
            time.sleep(1)
            stdscr.nodelay(1)
            k = stdscr.getch()  # look for a keyboard input, but don't wait
        elif k == ord('q'):
            break
Example #49
0
#/**************************************************************************/
#/* Main application procedure.                                            */
#/**************************************************************************/
# Instance of the system time class to handle system time and clock module.
ThisSystemTime = SystemTime.SystemTime()
# Instance of schedule class to store and process timer schedules.
ThisSchedule = Schedule.Schedule()
# Instnace of relays class to store current relay states.
ThisRelays = Relays.Relays()

#  /*********************************************************/
# /* Configure the console so key presses can be captured. */
#/*********************************************************/
curses.initscr()
curses.noecho()
window = curses.newwin(80, 25)
window.nodelay(1)
window.timeout(0)

# Instance of user interface class to manage user interactions.
ThisUserInterface = UserInterface.UserInterface(window, ThisSchedule,
                                                ThisRelays)
time.sleep(1)

#   /*******************************************************************/
#  /* Get the time from the timer module, and set the system time to  */
# /* ensure the system time is correct at the start.                 */
#/*******************************************************************/
ModuleTime = ThisSystemTime.GetModuleTime()
ThisSystemTime.SetSystemTime(ModuleTime)
Example #50
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]                                                     # First food co-ordinates

win.addch(food[0], food[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
    win.timeout(150 - (len(snake)/5 + len(snake)/10)%120)          # Increases the speed of Snake as its length increases
    
    prevKey = key                                                  # Previous key pressed
    event = win.getch()
Example #51
0
import curses
from random import randint



WINDOW_WIDTH = 60  
WINDOW_HEIGHT = 20

Number of blocks in window per line = WINDOW_WIDTH -2. 
Block x index ranges from 1 to WINDOW_WIDTH -2.
Number of blocks in window per column = WINDOW_HEIGHT -2. 
Block y index ranges from 1 to WINDOW_HEIGHT -2.


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


snake = [(4, 4), (4, 3), (4, 2)]
food = (6, 6)


win.addch(food[0], food[1], '#')

score = 0
Example #52
0
def main_loop(stdscr):
    try:
        if not curses.can_change_color():
            with SuspendCurses():
                print(f'no color change support')
            return 1

        curses.curs_set(1)  # set curses options and variables
        curses.noecho()
        curses.cbreak()
        maxy, maxx = stdscr.getmaxyx()
        h, w = 14, 80
        if maxy < h or maxx < w:
            with SuspendCurses():
                print(f'Terminal window needs to be at least {h} by {w}')
                print(f'Current h:{maxy}  and w:{maxx}')
            return 1

        stdscr.refresh()
        test_win = curses.newwin(h, w, 0, 0)
        stdscr.nodelay(1)
        test_win.leaveok(0)
        test_win.keypad(1)
        test_win.bkgd(' ', cp(0))
        test_win.box()
        test_win.move(2, 2)
        set_pairs(COLOR.BLACK, sys.platform)
        test_win.refresh()
        # maxc = curses.COLORS
        maxc = len(COLOR8)
        k, newk = 1, 2
        done = False
        while not done:
            if k > -1:
                test_win.clear()
                if k in (ord('q'), 27):
                    done = True
                test_win.addstr(1, 3, f'{16} colors supported', cp(0))
                for x in range(16):
                    test_win.addstr(3, 2 + x * 2, 'A ', cp(x + 1))

                for i in range(256):
                    row = i // 32
                    x = i % 32
                    test_win.addstr(5 + row, 2 + x * 2, 'A ', cp(i + 1))

                test_win.move(1, 2)
                test_win.box()
                test_win.refresh()
                curses.napms(10)
            newk = stdscr.getch()
            if newk != k:
                k = newk
    except KeyboardInterrupt:
        pass
    except:
        with SuspendCurses():
            print(format_exc())
        return 1

    return 0
def make_panel(h, l, y, x):
    win = curses.newwin(h, l, y, x)
    win.erase()
    win.box()
    panel = curses.panel.new_panel(win)
    return win, panel
Example #54
0
import curses
import time
import random
import pandas as pd
import os
from assets import Eminem, Bomb, Gun, Bullet

stdscr = curses.initscr()

win = curses.newwin(24, 80, 0, 0)


def score_processing(score):
    pattern = ['Name', 'Score', 'Date']
    record = False
    rating_file = './top_score.csv'
    if os.path.isfile(rating_file):
        df = pd.read_csv(rating_file)

        if score > min(df['Score']):
            record = True
    else:
        print('new')
        empty = {
            'Name': ['None'] * 20,
            'Score': [0 for i in range(20)],
            'Date': [0 for i in range(20)]
        }
        df = pd.DataFrame(empty, index=[i for i in range(20)])
        df['Date'] = pd.to_datetime(df['Date'])
        record = True
Example #55
0
 def __init__(self, height, width, server_count):
     BaseUI.__init__(self, curses.newwin(server_count + 2, width, 1, 0))
Example #56
0
import random
import curses
import time

#create the screen
sc = curses.initscr()
h, w = sc.getmaxyx()
win = curses.newwin(h, w, 0, 0)

win.keypad(1)
curses.curs_set(0)

#create snake and food position
snake_head = [10, 15]
snake_position = [[15, 10],[14, 20],[13, 10]]
food_postion = [20, 20]
score = 0

#display food
win.addch(food_postion[0], food_postion[1], curses.ACS_DIAMOND)

prev_button_direction = 1
button_direction = 1
key = curses.KEY_RIGHT

def collision_with_food(score):
  food_postion = [random.randint(1,h-2), random.randint(1,w-2)]
  score += 1
  return food_postion, score

  def collision_with_boundries(snake_head):
Example #57
0
    def main(self, stdscr) -> None:
        """
        Main program loop, handles user control and logical flow
        """
        curses.use_default_colors()
        self.stdscr = stdscr
        stdscr.keypad(1)
        height, width = stdscr.getmaxyx()  # Get screen size

        # Save these values
        self.height = height
        self.width = width - 1

        # Setup Output window
        output_start_row = 0  # Leave space for top border
        output_height = height - 3  # Leave space for command line
        self.last_row = output_height - output_start_row  # The last row we can write to
        # Create the window with these sizes
        self.outwin = curses.newwin(output_height, width - 1, output_start_row,
                                    0)
        self.outwin.refresh()

        # Setup Command line
        self.build_command_line()

        # Update the command line status
        reset_regex_status(self)

        # Disable cursor:
        curses.curs_set(0)

        # If the streams do not exist, create them
        if not self.streams:
            setup_streams(self)

        # Start the main app loop
        while True:
            # Update messages from the input stream's queues, track time
            t_0 = time.perf_counter()
            new_messages: int = 0
            for stream in self.streams:
                while not stream.stderr.empty():
                    message = stream.stderr.get()
                    self.stderr_messages.append(message)
                    new_messages += 1

                while not stream.stdout.empty():
                    message = stream.stdout.get()
                    self.stdout_messages.append(message)
                    new_messages += 1
            # Prevent this loop from taking up 100% of the CPU dedicated to the main thread by delaying loops
            t_1 = time.perf_counter() - t_0
            # Don't delay if the queue processing took too long
            time.sleep(max(0, self.poll_rate - t_1))

            # Calculate new poll rate
            if self.smart_poll_rate:
                self.handle_smart_poll_rate(t_1, new_messages)

            # Since this is the first run, set the visible stream to the one that has the most messages
            if self.first_run and (len(self.stdout_messages) > 0
                                   or len(self.stderr_messages) > 0):
                self.first_run = False
                # Default to stdout unless stderr has more messages
                if len(self.stdout_messages) >= len(self.stderr_messages):
                    self.messages = self.stdout_messages
                else:
                    self.messages = self.stderr_messages

            try:
                # Get keypress, raise curses.error if nothing detected
                keypress = self.command_line.getkey()
                resolve_keypress(self, keypress)
            except curses.error:
                if self.exit_val == -1:
                    return
                # If we have an active filter/parser, process it/them
                if self.parser:
                    # This may block if there are a lot of messages
                    process_parser(self)
                if self.func_handle:
                    # This may block if there are a lot of messages
                    process_matches(self)
                # Always try to render
                self.render_text_in_output()
Example #58
0
 def __init__(self, height, width, server_count):
     BaseUI.__init__(
         self,
         curses.newwin(height - server_count - 3, width, server_count + 3,
                       0))
     self.sessions = [[] for i in range(server_count)]
Example #59
0
    exit(1)
if (height < 5 + len(sorted_modules)):
    curses.nocbreak()
    stdscr.keypad(0)
    curses.echo()
    curses.endwin()
    print "Terminal window needs to be taller... aborting"
    exit(1)

# Set up the screen
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
height = 5 + len(sorted_modules)
width = 50
win = curses.newwin(height, width)

# Define column coordinates (hardocded values to look ok)
published_column = max_name_length + 8
comingsoon_column = max_name_length + 19
highlight_column = max_name_length + 31

# dictionary of the column coordinates / meanings
columns = {
    published_column: "published",
    comingsoon_column: "comingsoon",
    highlight_column: "highlight"
}

# Print fixed strings
stdscr.addstr(0, 0, "MOREA Module publishing interface")
Example #60
0
 def __init__(self, height, width, server_count):
     BaseUI.__init__(self, curses.newwin(1, width, 0, 0))
     self.session_counts = [0 for i in range(server_count)]
     self.node_counts = [0 for i in range(server_count)]
     self.zxids = [0 for i in range(server_count)]