Beispiel #1
0
int draw_map(struct t_map* map, struct t_map_entity* persp, bool show_vis, bool show_fov, bool show_targets, bool show_heatmaps, bool hl_persp) {

    int cs = curs_set(0);
    int x,y;
    getsyx(y,x);

    wmove(mapwindow,0,0);

    for (int iy=0; iy< MAP_HEIGHT; iy++) {
	for (int ix=0; ix < MAP_WIDTH; ix++) {

	    chtype tilech = mapchar[map->sq[iy*(MAP_WIDTH)+ix].type]; 

	    int tilevis = 1;

	    tilevis = map->aidata.p_viewarr[iy * MAP_WIDTH + ix];
	    if (!show_vis && (tilevis<1)) tilevis = 1;

	    chtype tileflags = 0;

	    switch (tilevis) {
		case 1: tileflags = CP_BLUE; break;
		case 2: tileflags = CP_LIGHTGRAY; break;
		case 3:
		case 4:	tileflags = CP_WHITE; break;
		default: break;
	    }

	    if (tilevis) mvwaddch(mapwindow,iy,ix, tileflags | tilech ); else if (dbgmode) mvwaddch (mapwindow,iy,ix,' ');

	}
    }
    
    if (show_heatmaps) {
	for (int yx=0; yx < HEATMAP_SIZE; yx++) {
	    uint8_t y = yx / MAP_WIDTH; uint8_t x = yx % MAP_WIDTH;
	    uint8_t m = map->aidata.e_hm[yx];
	    if (m) mvwaddch(mapwindow,y,x,'&' | ( (m > 2) ? CP_RED : ((m == 2) ? CP_GREEN : CP_YELLOW) ) ) ;
	}
    }

    for (int i=0; i < MAX_ENTITIES; i++) {


	if (map->ent[i].type == ET_NONE) continue;

	if ((map->ent[i].aidata) != NULL) {

	    if (show_targets) {
		if (vtile(map->ent[i].aidata->dx,map->ent[i].aidata->dy))
		    mvwaddch(mapwindow,map->ent[i].aidata->dy,map->ent[i].aidata->dx,'%' | CP_PURPLE);
	    }

	    if (show_fov && (map->aidata.p_viewarr[map->ent[i].y * MAP_WIDTH + map->ent[i].x] >= 3)) {

		// if we can see the entity, that means we can see what direction it is currently looking at.
		// the next tile in that direction will be redrawn with a cyan color.

		uint8_t vx = map->ent[i].x + movediff[map->ent[i].aidata->viewdir][0];
		uint8_t vy = map->ent[i].y + movediff[map->ent[i].aidata->viewdir][1];

		if (vtile(vx,vy)) {
		    chtype t = mvwinch(mapwindow,vy,vx);
		    // we strip the original character of all previous attributes,
		    // except the "alternate charset" one.
		    
		    chtype fcol = 0;

		    switch(map->ent[i].aidata->task) {
			case AIT_WORKING: fcol = CP_BLUE; break;
			case AIT_PATROLLING: fcol = CP_CYAN; break;
			case AIT_CHECKING_OUT:
			case AIT_LOOKING_FOR: fcol = CP_YELLOW; break;
			case AIT_PLEASE_LEAVE:
			case AIT_PURSUING:
			case AIT_ATTACKING: fcol = CP_RED; break;
			case AIT_FLEEING: fcol = CP_MAGENTA; break;
			default: fcol = CP_GREEN; break;


		    }	

		    mvwaddch(mapwindow,vy,vx,(t & (A_ALTCHARSET | A_CHARTEXT)) | fcol);
		}
	    }


	}
    }
    
    for (int i= (MAX_ENTITIES - 1); i >= 0; i--) {

	if (map->ent[i].type == ET_NONE) continue;
	int ex = map->ent[i].x; int ey = map->ent[i].y;

	if ( (persp == NULL) || (map->ent[i].flags & EF_ALWAYSVISIBLE) || ((map->aidata.p_viewarr[ey * (MAP_WIDTH) + ex] >= 3) ) ) {

	    int highlight = (hl_persp) && (&map->ent[i] == persp);
	    mvwaddch(mapwindow,ey,ex,entchar(&map->ent[i]) | (highlight ? A_REVERSE : 0) );
	}
    }

    wnoutrefresh(mapwindow);

    setsyx(y,x);
    curs_set(cs);
    doupdate();
    return 0;
}
Beispiel #2
0
int main (void)
{   int peg_A[8];
    int peg_B[8];
    int peg_C[8];
    int disks;
    int choice;
    int index_from;
    char choice_from;
    char choice_to;

    int n_discs;
    peg my_pegs[3];

    printf("Instructions on playing TOWERS OF HANOI:\nThere are\nthree pegs, labeled A, B, and C.\n\nInitially, peg A contains a certain\namount of disks, each one with a different size.\nThe disks are \nstacked\nin increasing size so that a disk is always on top of a larger one,\nforming a tower.\nThe goal of the game is to move all the disks from peg\nA to peg C.\nYou may move only one disk at a time.\n\nYou may move the\ntop disk from any peg to the top of the stack at another peg.\nThe\nonly\nlimitation is that you may not place a disk on top of one which is\nsmaller.\nYOU MAY STOP THE GAME ANYTIME BY ENTERING Q (THEN PRESSING \nTHE\nENTER KEY)");
    get_number_of_disks(&disks);
    initialize(disks, peg_A, peg_B, peg_C);
    print_status(disks, peg_A, peg_B, peg_C);
    while (peg_C[disks-1]!=3)
    {
        validate_move_from(&choice_from, peg_A, peg_B, peg_C);
        if(choice_from=='Q' || choice_from=='q')
        {
            printf("1.print sol'n\n");
            //sleep(10);
            printf("2.Display sol'n\n");
            printf("3.Exit\n");
            scanf("%d",&choice);
            switch(choice) {
            case 1:
                printsoln(disks);
                break;
            case 2:
                initscr();	/* Start curses mode 		*/
                cbreak();	/* Line buffering disabled. Pass on every thing */
                keypad(stdscr, TRUE);
                curs_set(FALSE);

                print_in_middle(0, LINES / 2, COLS, welcome_string, NULL);
                scanw("%d", &n_discs);

                timeout(TIME_OUT);
                noecho();
                store_n_discs = n_discs;

                init_pegs(my_pegs, n_discs);
                show_pegs(stdscr, my_pegs, n_discs);
                solve_hanoi(my_pegs, n_discs, 0, 1, 2);

                free_pegs(my_pegs, n_discs);
                endwin();		/* End curses mode		  */
                break;
            case 3:
                break;


            }
            break;

        }

        validate_move_to(disks, choice_from, &choice_to,&index_from, peg_A, peg_B, peg_C);
        if(choice_to=='Q' || choice_to=='q') {
            printf("1.print sol'n\n");
            //sleep(10);
            printf("2.Display sol'n\n");
            printf("3.Exit\n");
            scanf("%d",&choice);
            switch(choice) {
            case 1:
                printsoln(disks);
                break;
            case 2:
                initscr();	/* Start curses mode 		*/
                cbreak();	/* Line buffering disabled. Pass on every thing */
                keypad(stdscr, TRUE);
                curs_set(FALSE);

                print_in_middle(0, LINES / 2, COLS, welcome_string, NULL);
                scanw("%d", &n_discs);

                timeout(TIME_OUT);
                noecho();
                store_n_discs = n_discs;

                init_pegs(my_pegs, n_discs);
                show_pegs(stdscr, my_pegs, n_discs);
                solve_hanoi(my_pegs, n_discs, 0, 1, 2);

                free_pegs(my_pegs, n_discs);
                endwin();		/* End curses mode		  */
                break;
            case 3:
                printf("\nExiting");
                break;

            }
            break;

        }
        move_disk(disks, choice_from, choice_to, index_from,peg_A, peg_B, peg_C);
        print_status(disks, peg_A, peg_B, peg_C);
    }
    if(peg_C[disks-1]==3)
        printf("Congratulations! You won!\n");

    return 0;
}
int Shop::fenceselect(squadst& customers) const
{
   int ret=0;

   consolidateloot(location[customers.squad[0]->base]->loot);

   int page=0;

   vector<int> selected(location[customers.squad[0]->base]->loot.size(),0);

   do
   {
      erase();

      set_color(COLOR_WHITE,COLOR_BLACK,0);
      move(0,0);
      addstr("What will you sell?");

      if (ret > 0)
      {
         move(0,30);
         addstr("Estimated Liberal Amount: $");
         addstr(tostring(ret).c_str());
      }

      printparty();

      int x = 1, y = 10;
      std::string outstr;
      std::string itemstr;

      for (int l = page * 18;
           l < (int)location[customers.squad[0]->base]->loot.size() && l < page * 18 + 18;
           l++)
      {
         if (selected[l])
            set_color(COLOR_GREEN,COLOR_BLACK,1);
         else
            set_color(COLOR_WHITE,COLOR_BLACK,0);
         itemstr = location[customers.squad[0]->base]->loot[l]->equip_title();
         if (location[customers.squad[0]->base]->loot[l]->get_number() > 1)
         {
            if(selected[l] > 0)
            {
               itemstr += " " + tostring(selected[l]) + "/";
            }
            else
               itemstr += " x";
            itemstr += tostring(location[customers.squad[0]->base]->loot[l]->get_number());
         }

         outstr = static_cast<char>(l - page * 18 + 'A');
         outstr += " - " + itemstr;

         move(y,x);
         addstr(outstr.c_str());

         x += 26;
         if (x > 53)
         {
            x = 1;
            y++;
         }
      }

      //PAGE UP
      set_color(COLOR_WHITE,COLOR_BLACK,0);
      if (page > 0)
      {
         move(17,1);
         addprevpagestr();
      }
      //PAGE DOWN
      if((page + 1) * 18 < (int)location[customers.squad[0]->base]->loot.size())
      {
         move(17,53);
         addnextpagestr();
      }

      set_color(COLOR_WHITE,COLOR_BLACK,0);
      move(23,1);
      addstr("Press a letter to select an item to sell.");
      move(24,1);
      addstr("Enter - Done");

      refresh();

      int c = getch();
      translategetch(c);

      if (c >= 'a' && c <= 'r')
      {
         int slot = c - 'a' + page * 18;

         if(slot >= 0 && slot < (int)location[customers.squad[0]->base]->loot.size())
         {
            if (selected[slot])
            {
               ret -= location[customers.squad[0]->base]->loot[slot]->get_fencevalue() * selected[slot];
               selected[slot] = 0;
            }
            else
            {
               if (!location[customers.squad[0]->base]->loot[slot]->is_good_for_sale())
               {
                  printparty();

                  move(8,15);
                  set_color(COLOR_WHITE,COLOR_BLACK,1);
                  addstr(" You can't sell damaged goods.");

                  refresh();
                  getch();
               }
               else
               {
                  if (location[customers.squad[0]->base]->loot[slot]->get_number() > 1)
                  {
                     selected[slot] = 1;

                     printparty();

                     move(8,15);
                     set_color(COLOR_WHITE,COLOR_BLACK,1);
                     addstr("       How many?          ");

                     refresh();

                     char str[100];

                     keypad(stdscr,FALSE);
                     raw_output(FALSE);
                     echo();
                     curs_set(1);
                     mvgetstr(8,32,str);
                     curs_set(0);
                     noecho();
                     raw_output(TRUE);
                     keypad(stdscr,TRUE);

                     selected[slot] = atoi(str);
                     if (selected[slot] < 0)
                        selected[slot] = 0;
                     else if (selected[slot] > location[customers.squad[0]->base]->loot[slot]->get_number())
                        selected[slot]=location[customers.squad[0]->base]->loot[slot]->get_number();
                  }
                  else
                     selected[slot]=1;
                  ret += location[customers.squad[0]->base]->loot[slot]->get_fencevalue() * selected[slot];
               }
            }
         }
      }

      if(c == 'x'||c==10||c==ESC)
         break;

      //PAGE UP
      if((c == interface_pgup || c == KEY_UP || c == KEY_LEFT) && page > 0)
         page--;
      //PAGE DOWN
      if((c == interface_pgdn || c == KEY_DOWN || c == KEY_RIGHT)
         && (page + 1) * 18 < (int)location[customers.squad[0]->base]->loot.size())
         page++;

   } while (true);

   for(int l = location[customers.squad[0]->base]->loot.size() - 1; l >= 0; l--)
   {
      if(selected[l] > 0)
      {
         location[customers.squad[0]->base]->loot[l]->decrease_number(selected[l]);
         if(location[customers.squad[0]->base]->loot[l]->get_number() <= 0)
            delete_and_remove(location[customers.squad[0]->base]->loot,l);
      }
   }

   return ret;
}
Beispiel #4
0
/*
 * Handle a "special request"
 */
static errr Term_xtra_gcu(int n, int v)
{
	term_data *td = (term_data *)(Term->data);

	/* Analyze the request */
	switch (n)
	{
		/* Clear screen */
	case TERM_XTRA_CLEAR:
		touchwin(td->win);
		(void)wclear(td->win);
		return (0);

		/* Make a noise */
	case TERM_XTRA_NOISE:
		(void)write(1, "\007", 1);
		return (0);

		/* Flush the Curses buffer */
	case TERM_XTRA_FRESH:
		(void)wrefresh(td->win);
		return (0);

#ifdef USE_CURS_SET

		/* Change the cursor visibility */
	case TERM_XTRA_SHAPE:
		curs_set(v);
		return (0);

#endif

		/* Suspend/Resume curses */
	case TERM_XTRA_ALIVE:
		return (Term_xtra_gcu_alive(v));

		/* Process events */
	case TERM_XTRA_EVENT:
		return (Term_xtra_gcu_event(v));

		/* Flush events */
	case TERM_XTRA_FLUSH:
		while (!Term_xtra_gcu_event(FALSE));
		return (0);

		/* Delay */
	case TERM_XTRA_DELAY:
		usleep(1000 * v);
		return (0);

		/* Get Delay of some milliseconds */
	case TERM_XTRA_GET_DELAY:
		{
			int ret;
			struct timeval tv;

			ret = gettimeofday(&tv, NULL);
			Term_xtra_long = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);

			return ret;
		}

		/* Subdirectory scan */
	case TERM_XTRA_SCANSUBDIR:
		{
			DIR *directory;
			struct dirent *entry;

			scansubdir_max = 0;

			directory = opendir(scansubdir_dir);
			if (!directory)
				return 1;

			while ((entry = readdir(directory)))
			{
				char file[PATH_MAX + NAME_MAX + 2];
				struct stat filedata;

				file[PATH_MAX + NAME_MAX] = 0;
				strncpy(file, scansubdir_dir, PATH_MAX);
				strncat(file, "/", 2);
				strncat(file, entry->d_name, NAME_MAX);
				if (!stat(file, &filedata) && S_ISDIR((filedata.st_mode)))
				{
					string_free(scansubdir_result[scansubdir_max]);
					scansubdir_result[scansubdir_max] = string_make(entry->d_name);
					++scansubdir_max;
				}
			}
		}

		/* React to events */
	case TERM_XTRA_REACT:
		Term_xtra_gcu_react();
		return (0);
	}

	/* Unknown */
	return (1);
}
Beispiel #5
0
//
// Affiche une fenêtre de menu.
//
int displayMenu(char **choices, int nbChoices, char title[], bool logo) {
    if(choices == NULL || nbChoices < 1) return -1;
    
    //variables pour l'affichage du menu
    ITEM **menuItems = NULL;
    MENU *menu = NULL;
    WINDOW *menuWin = NULL;
    
    int i = 0, c;
    int winWidth = POPUP_WINDOW_WIDTH;
    //largeur du menu = longueur du plus grand des choix possibles
    int menuWidth = max_strlen(choices, nbChoices) + 2;
    
    //on alloue de la mémoire pour initialiser les éléments du menu
    menuItems = (ITEM **) calloc(nbChoices + 1, sizeof(ITEM *));
    
    //on créé de nouveaux éléments à partir des choix fournis
    for(i = 0; i < nbChoices; i++) {
        menuItems[i] = new_item(choices[i], NULL);
    }
    
    //on met un élément nul à la fin du tableau
    menuItems[nbChoices] = (ITEM *) NULL;
    
    while(true) {
        clear();
        
        menuWin = (logo) ? getMenuWindow(nbChoices, title) : getMenuWindowNoLogo(nbChoices, title, -1, -1);
        
        //on initialise le menu
        menu = new_menu((ITEM **) menuItems);
        
        //on lui précise bien que le menu fait N lignes et 1 colonne
        set_menu_format(menu, nbChoices, 1);
        
        menu_opts_off(menu, O_NONCYCLIC);
        set_menu_mark(menu, "> ");
        
        //on associe le menu à une fenêtre et une sous-fenêtre
        set_menu_win(menu, menuWin);
        //fenêtre hauteur largeur x y
        set_menu_sub(menu, derwin(menuWin, nbChoices, menuWidth, (logo) ? 15 : 4, (winWidth - menuWidth) / 2));
        
        //et hop, on affiche le menu et on rafraîchit.
        post_menu(menu);
        
        refresh();
        wrefresh(menuWin);
        
        curs_set(0);
        noecho();
        
        //boucle pour le menu
        while((c = getch())) {
            bool resized = false;
            
            switch(c) {
                case KEY_DOWN:
                    menu_driver(menu, REQ_DOWN_ITEM);
                    break;
                case KEY_UP:
                    menu_driver(menu, REQ_UP_ITEM);
                    break;
                case KEY_ESC_ALT:
                    return -1;
                case KEY_RESIZE:
                    //si on a redimensionné le terminal, on ré-exécute la boucle d'affichage
                    resized = true;
                    break;
                case KEY_MENU_ENTER: {
                    int choice = item_index(current_item(menu));
                    
                    //on libère la mémoire pour le menu, les choix, la fenêtre
                    unpost_menu(menu);
                    free_menu(menu);
                    
                    for(i = 0; i < nbChoices; ++i)
                        free_item(menuItems[i]);
                    
                    clear();
                    refresh();
                    
                    delwin(menuWin);
                    
                    //on réactive l'affichage des caractères tapés et du curseur
                    echo();
                    curs_set(1);
                    
                    return choice;
                }
            }
            
            if(resized) break;
            wrefresh(menuWin);
        }

    }
    
    return 0;
}
bool JumpToDocDialogue::run(DocMgr::Connection &db, IDList *id_list)
{
  bool retval = false;

  clear();
  frame();
  writestr(2, 0, "Jump to Document");

  curs_set(1);
  _stack.push_back("");
  if (_stack.size() > 10) _stack.erase(_stack.begin());
  _sp = _stack.size() - 1;
  _id_str = "";
  _field = new TextField(_x + 2, _y + 2, _w - 4, _id_str);
  _field->focus(true);
  _field->display();
  doupdate();

  InteractorList interaction;
  interaction.push_back(*_field);
  interaction.push_back(*this);

  bool ok = false;
  string err_msg;
  while (!ok) {
    doupdate();
    _completed = false;
    while (!_completed) { interaction.process_key(); doupdate(); }

    ok = true;
    if (_id_str != "") {
      ok = true;
      if (!DocMgr::DocID::valid(_id_str)) {
        ok = false;
        err_msg = "INVALID DOCUMENT ID!";
      } else {
        DocMgr::DocID id(_id_str);
        if (!id_list->id_visible(id)) {
          DocMgr::Query tmp_q(db);
          vector<DocMgr::DocID> ids;
          tmp_q.run(ids);
          bool found = false;
          for (int idx = 0; idx < ids.size(); ++idx)
            if (ids[idx] == id) { found = true;  break; }
          if (!found) {
            ok = false;
            err_msg = "DOCUMENT ID NOT FOUND IN DATABASE!";
          } else {
            retval = true;
            id_list->clear_query();
            id_list->set_current(id);
            _stack[_sp] = _id_str;
          }
        } else {
          _stack[_sp] = _id_str;
          id_list->set_current(id);
          if (_sp != _stack.size() - 1) _stack.erase(_stack.end());
        }
      }
    } else {
      _stack.erase(_stack.end());
      --_sp;
    }

    if (!ok) {
      string blank(getmaxx(stdscr), ' ');
      mvaddstr(0, 0, blank.c_str());
      wattron(stdscr, A_BOLD);
      mvaddstr(0, 0, err_msg.c_str());
      wattroff(stdscr, A_BOLD);
      wnoutrefresh(stdscr);
      _field->display();
    }
  }

  curs_set(0);
  clear();

  delete _field;
  return retval;
}
Beispiel #7
0
Ui *ui_curses_new(void) {

	UiCurses *uic = calloc(1, sizeof(UiCurses));
	Ui *ui = (Ui*)uic;
	if (!uic)
		return NULL;
	if (!(uic->termkey = termkey_new(STDIN_FILENO, TERMKEY_FLAG_UTF8)))
		goto err;
	termkey_set_canonflags(uic->termkey, TERMKEY_CANON_DELBS);
	setlocale(LC_CTYPE, "");
	if (!getenv("ESCDELAY"))
		set_escdelay(50);
	char *term = getenv("TERM");
	if (!term)
		term = "xterm";
	if (!newterm(term, stderr, stdin)) {
		snprintf(uic->info, sizeof(uic->info), "Warning: unknown term `%s'", term);
		if (!newterm(strstr(term, "-256color") ? "xterm-256color" : "xterm", stderr, stdin))
			goto err;
	}
	start_color();
	use_default_colors();
	raw();
	noecho();
	nonl();
	keypad(stdscr, TRUE);
	meta(stdscr, TRUE);
	curs_set(0);
	/* needed because we use getch() which implicitly calls refresh() which
	   would clear the screen (overwrite it with an empty / unused stdscr */
	refresh();

	*ui = (Ui) {
		.init = ui_init,
		.start = ui_start,
		.free = ui_curses_free,
		.termkey_get = ui_termkey_get,
		.suspend = ui_suspend,
		.resize = ui_resize,
		.update = ui_update,
		.window_new = ui_window_new,
		.window_free = ui_window_free,
		.window_focus = ui_window_focus,
		.window_swap = ui_window_swap,
		.draw = ui_draw,
		.redraw = ui_redraw,
		.arrange = ui_arrange,
		.die = ui_die,
		.info = ui_info,
		.info_hide = ui_info_hide,
		.haskey = ui_haskey,
		.getkey = ui_getkey,
		.terminal_save = ui_terminal_save,
		.terminal_restore = ui_terminal_restore,
	};

	struct sigaction sa;
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);
	sa.sa_handler = sigwinch_handler;
	sigaction(SIGWINCH, &sa, NULL);
	sigaction(SIGCONT, &sa, NULL);

	ui_resize(ui);

	return ui;
err:
	ui_curses_free(ui);
	return NULL;
}
Beispiel #8
0
void get_command(void)
{
	char com[255];

	int text_width, text_startx;
	allocated_block_t *allocated_block = NULL;
	int i = 0;
	int count = 0;

	WINDOW *command_win = NULL;
        List allocated_blocks = NULL;
	ListIterator results_i;

	if (params.commandline && !params.command) {
		printf("Configure won't work with commandline mode.\n");
		printf("Please remove the -c from the commandline.\n");
		bg_configure_ba_fini();
		exit(0);
	}

	if (working_cluster_rec) {
		char *cluster_name = slurm_get_cluster_name();
		if (xstrcmp(working_cluster_rec->name, cluster_name)) {
			xfree(cluster_name);
			endwin();
			printf("To use the configure option you must be on the "
			       "cluster the configure is for.\nCross cluster "
			       "support doesn't exist today.\nSorry for the "
			       "inconvenince.\n");
			bg_configure_ba_fini();
			exit(0);
		}
		xfree(cluster_name);
	}

	/* make sure we don't get any noisy debug */
	ba_configure_set_ba_debug_flags(0);

	bg_configure_ba_setup_wires();

	color_count = 0;

	allocated_blocks = list_create(_destroy_allocated_block);

	if (params.commandline) {
		snprintf(com, sizeof(com), "%s", params.command);
		goto run_command;
	} else {
		text_width = text_win->_maxx;
		text_startx = text_win->_begx;
		command_win = newwin(3, text_width - 1, LINES - 4,
				     text_startx + 1);
		curs_set(1);
		echo();
	}

	while (xstrcmp(com, "quit")) {
		clear_window(grid_win);
		print_grid();
		clear_window(text_win);
		box(text_win, 0, 0);
		box(grid_win, 0, 0);

		if (!params.no_header)
			_print_header_command();

		if (error_string != NULL) {
			i = 0;
			while (error_string[i] != '\0') {
				if (error_string[i] == '\n') {
					main_ycord++;
					main_xcord=1;
					i++;
				}
				mvwprintw(text_win,
					  main_ycord,
					  main_xcord,
					  "%c",
					  error_string[i++]);
				main_xcord++;
			}
			main_ycord++;
			main_xcord = 1;
			memset(error_string, 0, 255);
		}
		results_i = list_iterator_create(allocated_blocks);

		count = list_count(allocated_blocks)
			- (LINES-(main_ycord+5));

		if (count<0)
			count=0;
		i=0;
		while ((allocated_block = list_next(results_i)) != NULL) {
			if (i >= count)
				_print_text_command(allocated_block);
			i++;
		}
		list_iterator_destroy(results_i);

		wnoutrefresh(text_win);
		wnoutrefresh(grid_win);
		doupdate();
		clear_window(command_win);

		box(command_win, 0, 0);
		mvwprintw(command_win, 0, 3,
			  "Input Command: (type quit to change view, "
			  "exit to exit)");
		wmove(command_win, 1, 1);
		wgetstr(command_win, com);

		if (!xstrcmp(com, "exit")) {
			endwin();
			FREE_NULL_LIST(allocated_blocks);
			bg_configure_ba_fini();
			exit(0);
		}
	run_command:

		if (!xstrcmp(com, "quit") || !xstrcmp(com, "\\q")) {
			break;
		} else if (!strncasecmp(com, "layout", 6)) {
			_set_layout(com);
		} else if (!strncasecmp(com, "midplane", 8) ||
			   !strncasecmp(com, "basepartition", 13)) {
			_set_midplane_cnode_cnt(com);
		} else if (!strncasecmp(com, "nodecard", 8)) {
			_set_nodecard_cnt(com);
		} else if (!strncasecmp(com, "resolve", 7) ||
			   !strncasecmp(com, "r ", 2)) {
			_resolve(com);
		} else if (!strncasecmp(com, "resume", 6)) {
			mvwprintw(text_win,
				main_ycord,
				main_xcord, "%s", com);
		} else if (!strncasecmp(com, "drain", 5)) {
			mvwprintw(text_win,
				main_ycord,
				main_xcord, "%s", com);
		} else if (!strncasecmp(com, "alldown", 7)) {
			_change_state_all_bps(com, NODE_STATE_DOWN);
		} else if (!strncasecmp(com, "down", 4)) {
			_change_state_bps(com, NODE_STATE_DOWN);
		} else if (!strncasecmp(com, "allup", 5)) {
			_change_state_all_bps(com, NODE_STATE_IDLE);
		} else if (!strncasecmp(com, "up", 2)) {
			_change_state_bps(com, NODE_STATE_IDLE);
		} else if (!strncasecmp(com, "remove", 6)
			|| !strncasecmp(com, "delete", 6)
			|| !strncasecmp(com, "drop", 4)) {
			_remove_allocation(com, allocated_blocks);
		} else if (!strncasecmp(com, "create", 6)) {
			_create_allocation(com, allocated_blocks);
		} else if (!strncasecmp(com, "copy", 4)
			|| !strncasecmp(com, "c ", 2)
			|| !strncasecmp(com, "c\0", 2)) {
			_copy_allocation(com, allocated_blocks);
		} else if (!strncasecmp(com, "save", 4)) {
			_save_allocation(com, allocated_blocks);
		} else if (!strncasecmp(com, "load", 4)) {
			_load_configuration(com, allocated_blocks);
		} else if (!strncasecmp(com, "clear all", 9)
			|| !strncasecmp(com, "clear", 5)) {
			list_flush(allocated_blocks);
		} else {
			memset(error_string, 0, 255);
			sprintf(error_string, "Unknown command '%s'",com);
		}

		if (params.commandline) {
			bg_configure_ba_fini();
			exit(1);
		}
	}
	FREE_NULL_LIST(allocated_blocks);
	params.display = 0;
	noecho();

	clear_window(text_win);
	main_xcord = 1;
	main_ycord = 1;
	curs_set(0);
	print_date();
	get_job();
	return;
}
Beispiel #9
0
static WINDOW *
ncurses_setup(void){
	struct ncurses_input_marshal *nim;
	const char *errstr = NULL;
	WINDOW *w = NULL;

	fprintf(stderr,"Entering ncurses mode...\n");
	if(initscr() == NULL){
		fprintf(stderr,"Couldn't initialize ncurses\n");
		return NULL;
	}
	if(cbreak() != OK){
		errstr = "Couldn't disable input buffering\n";
		goto err;
	}
	if(noecho() != OK){
		errstr = "Couldn't disable input echoing\n";
		goto err;
	}
	if(intrflush(stdscr,TRUE) != OK){
		errstr = "Couldn't set flush-on-interrupt\n";
		goto err;
	}
	if(scrollok(stdscr,FALSE) != OK){
		errstr = "Couldn't disable scrolling\n";
		goto err;
	}
	if(nonl() != OK){
		errstr = "Couldn't disable nl translation\n";
		goto err;
	}
	if(start_color() != OK){
		errstr = "Couldn't initialize ncurses color\n";
		goto err;
	}
	if(use_default_colors()){
		errstr = "Couldn't initialize ncurses colordefs\n";
		goto err;
	}
	w = stdscr;
	ESCDELAY = 100;
	keypad(stdscr,TRUE);
	if(nodelay(stdscr,FALSE) != OK){
		errstr = "Couldn't set blocking input\n";
		goto err;
	}
	if(curs_set(0) == ERR){
		errstr = "Couldn't disable cursor\n";
		goto err;
	}
	if(setup_statusbar(COLS)){
		errstr = "Couldn't setup status bar\n";
		goto err;
	}
	if(COLORS < 16){
		assert(init_pair(BORDER_COLOR,COLOR_GREEN,-1) == OK);
		assert(init_pair(HEADER_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(FOOTER_COLOR,COLOR_YELLOW,-1) == OK);
		assert(init_pair(DBORDER_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(DHEADING_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(UBORDER_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UHEADING_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(PBORDER_COLOR,COLOR_YELLOW,-1) == OK);
		assert(init_pair(PHEADING_COLOR,COLOR_RED,-1) == OK);
		assert(init_pair(BULKTEXT_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(BULKTEXT_ALTROW_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(IFACE_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(LCAST_COLOR,COLOR_CYAN,-1) == OK); // will use A_BOLD via OUR_BOLD
		assert(init_pair(UCAST_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LSELECTED_COLOR,-1,COLOR_CYAN) == OK);
		assert(init_pair(USELECTED_COLOR,-1,COLOR_CYAN) == OK);
		assert(init_pair(MSELECTED_COLOR,-1,COLOR_BLUE) == OK);
		assert(init_pair(BSELECTED_COLOR,-1,COLOR_MAGENTA) == OK);
		assert(init_pair(LCAST_L3_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_L3_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_L3_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_L3_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LCAST_RES_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_RES_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_RES_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_RES_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LCAST_ALTROW_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_ALTROW_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_ALTROW_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_ALTROW_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LCAST_ALTROW_L3_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_ALTROW_L3_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_ALTROW_L3_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_ALTROW_L3_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LCAST_ALTROW_RES_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_ALTROW_RES_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_ALTROW_RES_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_ALTROW_RES_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(SUBDISPLAY_COLOR,COLOR_WHITE,-1) == OK);
	}else{
		int z;

		assert(init_pair(BORDER_COLOR,COLOR_ALUMINIUM,-1) == OK);
		assert(init_pair(HEADER_COLOR,COLOR_MODBLUE,-1) == OK);
		assert(init_pair(FOOTER_COLOR,COLOR_MODYELLOW,-1) == OK);
		assert(init_pair(DBORDER_COLOR,COLOR_ALUMINIUM,-1) == OK);
		assert(init_pair(DHEADING_COLOR,COLOR_MODWHITE,-1) == OK);
		assert(init_pair(UBORDER_COLOR,COLOR_MODCYAN,-1) == OK);
		assert(init_pair(UHEADING_COLOR,COLOR_ORANGE,-1) == OK);
		assert(init_pair(PBORDER_COLOR,COLOR_MODBLUE,-1) == OK);
		assert(init_pair(PHEADING_COLOR,COLOR_MODRED,-1) == OK);
		assert(init_pair(BULKTEXT_COLOR,COLOR_MODWHITE,-1) == OK);
		assert(init_pair(BULKTEXT_ALTROW_COLOR,COLOR_MODWHITE,COLOR_PALEALUMINIUM) == OK);
		assert(init_pair(IFACE_COLOR,COLOR_MODWHITE,-1) == OK);
		assert(init_pair(LCAST_COLOR,COLOR_CHAMELEON,-1) == OK);
		assert(init_pair(UCAST_COLOR,COLOR_MODBLUE,-1) == OK);
		assert(init_pair(MCAST_COLOR,COLOR_SKYBLUE,-1) == OK);
		assert(init_pair(BCAST_COLOR,COLOR_MODVIOLET,-1) == OK);
		assert(init_pair(LSELECTED_COLOR,COLOR_MODWHITE,COLOR_CHAMELEON_50) == OK);
		assert(init_pair(USELECTED_COLOR,COLOR_MODWHITE,COLOR_BLUE_50) == OK);
		assert(init_pair(MSELECTED_COLOR,COLOR_MODWHITE,COLOR_SKYBLUE_50) == OK);
		assert(init_pair(BSELECTED_COLOR,COLOR_MODWHITE,COLOR_VIOLET_50) == OK);
		assert(init_pair(LCAST_L3_COLOR,COLOR_CHAMELEON_75,-1) == OK);
		assert(init_pair(UCAST_L3_COLOR,COLOR_BLUE_75,-1) == OK);
		assert(init_pair(MCAST_L3_COLOR,COLOR_SKYBLUE_75,-1) == OK);
		assert(init_pair(BCAST_L3_COLOR,COLOR_VIOLET_75,-1) == OK);
		assert(init_pair(LCAST_RES_COLOR,COLOR_CHAMELEON_50,-1) == OK);
		assert(init_pair(UCAST_RES_COLOR,COLOR_BLUE_50,-1) == OK);
		assert(init_pair(MCAST_RES_COLOR,COLOR_SKYBLUE_50,-1) == OK);
		assert(init_pair(BCAST_RES_COLOR,COLOR_VIOLET_50,-1) == OK);

		// Disable altrow stuff for now. It's hard to read and ugly.
		assert(init_pair(LCAST_ALTROW_COLOR,COLOR_CHAMELEON,-1) == OK);
		assert(init_pair(UCAST_ALTROW_COLOR,COLOR_MODBLUE,-1) == OK);
		assert(init_pair(MCAST_ALTROW_COLOR,COLOR_SKYBLUE,-1) == OK);
		assert(init_pair(BCAST_ALTROW_COLOR,COLOR_MODVIOLET,-1) == OK);
		assert(init_pair(LCAST_ALTROW_L3_COLOR,COLOR_CHAMELEON_75,-1) == OK);
		assert(init_pair(UCAST_ALTROW_L3_COLOR,COLOR_BLUE_75,-1) == OK);
		assert(init_pair(MCAST_ALTROW_L3_COLOR,COLOR_SKYBLUE_75,-1) == OK);
		assert(init_pair(BCAST_ALTROW_L3_COLOR,COLOR_VIOLET_75,-1) == OK);
		assert(init_pair(LCAST_ALTROW_RES_COLOR,COLOR_CHAMELEON_50,-1) == OK);
		assert(init_pair(UCAST_ALTROW_RES_COLOR,COLOR_BLUE_50,-1) == OK);
		assert(init_pair(MCAST_ALTROW_RES_COLOR,COLOR_SKYBLUE_50,-1) == OK);
		assert(init_pair(BCAST_ALTROW_RES_COLOR,COLOR_VIOLET_50,-1) == OK);
		assert(init_pair(SUBDISPLAY_COLOR,COLOR_MODWHITE,-1) == OK);

		for(z = FIRST_FREE_COLOR ; z < COLORS && z < COLOR_PAIRS ; ++z){
			assert(init_pair(z,z,-1) == OK);
		}
	}
	if(draw_main_window(w)){
		errstr = "Couldn't use ncurses\n";
		goto err;
	}
	if((nim = malloc(sizeof(*nim))) == NULL){
		goto err;
	}
	nim->w = w;
	nim->maintid = pthread_self();
	// Panels aren't yet being used, so we need call refresh() to
	// paint the main window.
	refresh();
	if(pthread_create(&inputtid,NULL,ncurses_input_thread,nim)){
		errstr = "Couldn't create UI thread\n";
		free(nim);
		goto err;
	}
	// FIXME install SIGWINCH() handler...?
	return w;

err:
	mandatory_cleanup(&w);
	fprintf(stderr,"%s",errstr);
	return NULL;
}
Beispiel #10
0
int main(void)
{
//extern variables
char *help_topic=NULL,*fname=NULL,buff[5000]={'\0'},file[50]={};
int logc,logr,ch,i,j,k,flag;
FILE *fp;

// initialise curses mode and colors
initCurses();
noecho();
cbreak();
keypad(stdscr,TRUE);
mousemask(ALL_MOUSE_EVENTS,NULL);
curs_set(0);

//displays starting blue screen
Screen();
	while(1)
	{
		int ch;
		ch=getResponse();
		switch(ch)
		{
			//file menu
			case 1:
					//pop up menu file
					(WINDOW**)draw_menu(fmenu,SIZE(fmenu),1,0);
			break;
			
			//new item
			case 2:
				refresh();
				//draws black screen
				new_file();
				noecho();
				//displays filename and line number on black screen
				New();						
			break;
			
			//Return To Shell
			case 5:
				clear();
	       		refresh();
	       		endwin();
	       		system("sh");
	       		clear();
				refresh();
				Screen();
			break;
			
			//exit menu
			case 6:
				clear();
	    		refresh();
				endwin();
				exit(EXIT_SUCCESS);
			break;
			
			/*compile menu
			case 7:
				//pop up menu compile
					(WINDOW**)draw_menu(cmenu,SIZE(cmenu),1,12);
			break;
			
			*/
			/*compile item
			case 8:
				compile();
			break;*/
			
			//help menu
			case 11:
				//pop up  help menu
 					(WINDOW**)draw_menu(hmenu,SIZE(hmenu),1,27);
			break;
			
			//help index
			case KEY_F(1):
			case 12:
				Help();
			break;
			
			//help topic
			case 13:
				help_topic=(char*)calloc(30,sizeof(char));
				help_topic=dialog("| Help |"," Find "," Cancel ");
			break;
			
			
			
			//open file
			case KEY_F(3):
			case 3:
						k=0;
					for(i=2;i<22;++i)
					{
						for(j=0;j<78;++j)
							buff[k++]=(mvinch(i,j)&A_CHARTEXT);
						buff[k++]='\n';
					}
				new_file();
					//pops up open dialogbox				
				fname=(char*)calloc(30,sizeof(char));
				fname=dialog("| Open |"," Open "," Cancel ");
				
				//if user press cancel display screen contents
				if((strlen(fname)==0))
				{
					logc=1;logr=2;
					for(k=0;buff[k]!='\0';++k)
					{
						refresh();
						if(buff[k]=='\n')
						{
					        logr+=1;
					        logc=1;
					       	move(logr+1,logc);
						}
						else
						{
							mvaddch(logr,logc,buff[k]);
							logc+=1;
						}
					}
				}
				
				//othewise open a file and display it's contents
				else
				{
					//redraws new screen
					new_file();
				
				
					if(!(fp=fopen(fname,"r")))
					{
						warning("| Warning |","	No such file ","Press a key to return !!!");
						getch();
						//new_file();
							logc=1;logr=2;
							for(k=0;buff[k]!='\0';++k)
							{
								refresh();
								if(buff[k]=='\n')
								{
					        		logr+=1;
					        		logc=1;
					       			 move(logr+1,logc);
								}
								else
								{
									mvaddch(logr,logc,buff[k]);
									logc+=1;
								}
							}	
					
					}
					//if file is exist display contents 
					else
					{	
						new_file();
						logc=1;logr=2;
						while((ch=fgetc(fp))!=EOF)
						{
							if(ch=='\n')
							{
						        logr+=1;
						        logc=1;
						        move(logr+1,logc);
							}
							else
							{
								mvaddch(logr,logc,ch);
								logc+=1;
							}
						}
						fclose(fp);
						move(2,2);
						refresh();
						
						//displays file name
							move(1,2);
						hline(ACS_HLINE,75);
						strcat(file,"| ");
						strcat(file,fname);
						strcat(file," |");
						//move(1,2);
						//hline(ACS_HLINE,60);
						writeString(stdscr,1,35,file,white_black);
					}
				}
			break;
			
			
		}
	}
}
Beispiel #11
0
int APIENTRY	WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
 int argc = __argc;
 char **argv = __argv;
#else
int main(int argc, char *argv[])
{
#endif
#ifdef ENABLE_LOGGING
  setupDebug();
#endif
 int seed = time(NULL);

    // set locale to system default
    setlocale(LC_ALL, "");
    bindtextdomain("cataclysm-dda", "lang/mo");
    bind_textdomain_codeset("cataclysm-dda", "UTF-8");
    textdomain("cataclysm-dda");

//args: world seeding only.
 argc--; argv++;
 while (argc){
  if(std::string(argv[0]) == "--seed"){
   argc--; argv++;
   if(argc){
    seed = djb2_hash((unsigned char*)argv[0]);
    argc--; argv++;
   }
  }
  else // ignore unknown args.
   argc--; argv++;
 }

// ncurses stuff
 load_options(); // For getting size options
 initscr(); // Initialize ncurses
 noecho();  // Don't echo keypresses
 cbreak();  // C-style breaks (e.g. ^C to SIGINT)
 keypad(stdscr, true); // Numpad is numbers
 init_colors(); // See color.cpp
// curs_set(0); // Invisible cursor
 set_escdelay(10); // Make escape actually responsive

 std::srand(seed);

 bool quit_game = false;
 bool delete_world = false;
 g = new game;
 if(g->game_error())
  exit_handler(-999);
 g->init_ui();
 MAPBUFFER.set_game(g);
 g->load_artifacts(); //artifacts have to be loaded before any items are created
 if(g->game_error())
  exit_handler(-999);
 MAPBUFFER.load();

 curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone

 #if (!(defined _WIN32 || defined WINDOWS))
  struct sigaction sigIntHandler;
  sigIntHandler.sa_handler = exit_handler;
  sigemptyset(&sigIntHandler.sa_mask);
  sigIntHandler.sa_flags = 0;
  sigaction(SIGINT, &sigIntHandler, NULL);
 #endif

 do {
  g->setup();
  while (!g->do_turn()) ;
  if (g->uquit == QUIT_DELETE_WORLD)
    delete_world = true;
  if (g->game_quit() || g->game_error())
   quit_game = true;
 } while (!quit_game);

 if (delete_world)
 {
   g->delete_save();
 } else {
  MAPBUFFER.save_if_dirty();
 }

 exit_handler(-999);

 return 0;
}
Beispiel #12
0
void tx_refresh_screen(void)
{
	endwin();
	doupdate();
	curs_set(0);
}
Beispiel #13
0
/* Draws possibly centered formatted message with specified title and control
 * message on error_win. */
static void
draw_msg(const char title[], const char msg[], const char ctrl_msg[],
		int centered, int recommended_width)
{
	enum { margin = 1 };

	int sw, sh;
	int w, h;
	int max_h;
	int len;
	size_t ctrl_msg_n;
	size_t wctrl_msg;
	size_t i;
	int first_line_x = 1;
	const int first_line_y = 2;

	curs_set(0);

	getmaxyx(stdscr, sh, sw);

	ctrl_msg_n = MAX(measure_sub_lines(ctrl_msg, &wctrl_msg), 1U);

	max_h = sh - 2 - ctrl_msg_n + !cfg.display_statusline;
	h = max_h;
	/* The outermost condition is for VLA below (to calm static analyzers). */
	w = MAX(2 + 2*margin, MIN(sw - 2,
	        MAX(MAX(recommended_width, sw/3),
	            (int)MAX(wctrl_msg, determine_width(msg)) + 4)));
	wresize(error_win, h, w);

	werase(error_win);

	len = strlen(msg);
	if(len <= w - 2 && strchr(msg, '\n') == NULL)
	{
		first_line_x = (w - len)/2;
		h = 5 + ctrl_msg_n;
		wresize(error_win, h, w);
		mvwin(error_win, (sh - h)/2, (sw - w)/2);
		checked_wmove(error_win, first_line_y, first_line_x);
		wprint(error_win, msg);
	}
	else
	{
		int i = 0;
		int cy = first_line_y;
		while(i < len)
		{
			int j;
			char buf[w - 2 - 2*margin + 1];
			int cx;

			copy_str(buf, sizeof(buf), msg + i);

			for(j = 0; buf[j] != '\0'; j++)
				if(buf[j] == '\n')
					break;

			if(buf[j] != '\0')
				i++;
			buf[j] = '\0';
			i += j;

			if(buf[0] == '\0')
				continue;

			if(cy >= max_h - (int)ctrl_msg_n - 3)
			{
				/* Skip trailing part of the message if it's too long, just print how
				 * many lines we're omitting. */
				size_t max_len;
				const int more_lines = 1U + measure_sub_lines(msg + i, &max_len);
				snprintf(buf, sizeof(buf), "<<%d more line%s not shown>>", more_lines,
						(more_lines == 1) ? "" : "s");
				/* Make sure this is the last iteration of the loop. */
				i = len;
			}

			h = 1 + cy + 1 + ctrl_msg_n + 1;
			wresize(error_win, h, w);
			mvwin(error_win, (sh - h)/2, (sw - w)/2);

			cx = centered ? (w - utf8_strsw(buf))/2 : (1 + margin);
			if(cy == first_line_y)
			{
				first_line_x = cx;
			}
			checked_wmove(error_win, cy++, cx);
			wprint(error_win, buf);
		}
	}

	box(error_win, 0, 0);
	if(title[0] != '\0')
	{
		mvwprintw(error_win, 0, (w - strlen(title) - 2)/2, " %s ", title);
	}

	/* Print control message line by line. */
	for(i = ctrl_msg_n; i > 0U; --i)
	{
		const size_t len = strcspn(ctrl_msg, "\n");
		mvwaddnstr(error_win, h - i - 1, MAX(0, (w - (int)len)/2), ctrl_msg, len);
		ctrl_msg = skip_char(ctrl_msg + len + 1U, '/');
	}

	checked_wmove(error_win, first_line_y, first_line_x);
}
Beispiel #14
0
//
// Affiche le tableau des high-scores dans une fenêtre modale.
//
void displayLeaderboard() {
    int i, c;
    
    const int menuWidth = 10;
    
    const int winHeight = MAX_SAVED_SCORES_COUNT + 6;
    const int winWidth = POPUP_WINDOW_WIDTH + 20;
    
    const int colRank = 2;
    const int colScore = 20;
    const int colName = 35;
    const int colBoard = 55;
    
    ITEM* menuItems[2];
    MENU* menu;
    
    Score scores[MAX_SAVED_SCORES_COUNT];
    
    int n = loadScoreBoard(scores);
    
    while (true) {
        clear();
        refresh();
        
        WINDOW* win = newwin(winHeight, winWidth, (LINES - winHeight) / 2, (COLS - winWidth) / 2);
        box(win, 0, 0);
        
        mvwaddch(win, 2, 0, ACS_LTEE);
        mvwhline(win, 2, 1, ACS_HLINE, winWidth - 1);
        mvwaddch(win, 2, winWidth - 1, ACS_RTEE);
        
        mvwprintw(win, 1, colRank, "CLASSEMENT");
        mvwprintw(win, 1, colScore, "SCORE");
        mvwprintw(win, 1, colName, "PSEUDO");
        mvwprintw(win, 1, colBoard, "PLATEAU");
        
        mvwaddch(win, 0, colScore - 2, ACS_TTEE);
        mvwvline(win, 1, colScore - 2, ACS_VLINE, winHeight - 2);
        mvwaddch(win, winHeight - 1, colScore - 2, ACS_BTEE);
        
        mvwaddch(win, 0, colName - 2, ACS_TTEE);
        mvwvline(win, 1, colName - 2, ACS_VLINE, winHeight - 2);
        mvwaddch(win, winHeight - 1, colName - 2, ACS_BTEE);
        
        mvwaddch(win, 0, colBoard - 2, ACS_TTEE);
        mvwvline(win, 1, colBoard - 2, ACS_VLINE, winHeight - 2);
        mvwaddch(win, winHeight - 1, colBoard - 2, ACS_BTEE);
        
        for(i = 0; i < n; i++) {
            mvwprintw(win, i + 3, colRank, "#%d", i+1);
            mvwprintw(win, i + 3, colScore, "%d", scores[i].score);
            mvwprintw(win, i + 3, colName, "%s", scores[i].username);
            mvwprintw(win, i + 3, colBoard, "%s", scores[i].boardName);
        }
        
        menuItems[0] = new_item("<Retour>", NULL);
        menuItems[1] = (ITEM *) NULL;
        
        //on initialise le menu
        menu = new_menu((ITEM **) menuItems);
        
        //on lui précise bien que le menu fait 1 ligne et 1 colonne
        set_menu_format(menu, 1, 1);
        
        //on associe le menu à une fenêtre et une sous-fenêtre
        set_menu_win(menu, win);
        //fenêtre hauteur largeur x y
        set_menu_sub(menu, derwin(win, 1, menuWidth, winHeight - 2, (winWidth - menuWidth) / 2));
        set_menu_mark(menu, "");
        
        noecho();
        curs_set(0);
        
        //et hop, on affiche le menu et on rafraîchit.
        post_menu(menu);
        
        wrefresh(win);
        refresh();
        
        //boucle pour le menu
        while((c = getch())) {
            bool resized = false;
            
            switch(c) {
                case KEY_RESIZE:
                    //si le terminal a été redimensionné, on ré-exécute la boucle d'affichage
                    resized = true;
                    break;
                case KEY_MENU_ENTER: {
                    unpost_menu(menu);
                    free_menu(menu);
                    
                    for(i = 0; i < 2; ++i)
                        free_item(menuItems[i]);
                    
                    clear();
                    refresh();
                    
                    delwin(win);
                    
                    curs_set(1);
                    echo();
                    return;
                }
            }
            
            if(resized) break;
            wrefresh(win);
        }
    }
}
Beispiel #15
0
int main(int argc, char **argv){
	extern char *optarg;
	int c;
	int colouron = 0;

	time_t last_update = 0;

	WINDOW *window;

	extern int errno;

	int delay=2;

	sg_init();
	if(sg_drop_privileges() != 0){
		fprintf(stderr, "Failed to drop setuid/setgid privileges\n");
		return 1;
	}

#ifdef COLOR_SUPPORT
	while ((c = getopt(argc, argv, "d:cvh")) != -1){
#else
	while ((c = getopt(argc, argv, "d:vh")) != -1){
#endif
		switch (c){
			case 'd':
				delay = atoi(optarg);
				if (delay < 1){
					fprintf(stderr, "Time must be 1 second or greater\n");
					exit(1);
				}
				break;
#ifdef COLOR_SUPPORT
			case 'c':
				colouron = 1;
				break;
#endif
			case 'v':
				version_num(argv[0]);
				break;
			case 'h':
			default:
				usage(argv[0]);
				return 1;
				break;
		}
	}

	signal(SIGWINCH, sig_winch_handler);
	initscr();
#ifdef COLOR_SUPPORT
	/* turn on colour */
	if (colouron) {
		if (has_colors()) {
			start_color();
			use_default_colors();
			init_pair(1,COLOR_RED,-1);
			init_pair(2,COLOR_GREEN,-1);
			init_pair(3,COLOR_YELLOW,-1);
			init_pair(4,COLOR_BLUE,-1);
			init_pair(5,COLOR_MAGENTA,-1);
			init_pair(6,COLOR_CYAN,-1);
		} else {
			fprintf(stderr, "Colour support disabled: your terminal does not support colour.");
			colouron = 0;
		}
	}
#endif
	nonl();
	curs_set(0);
	cbreak();
	noecho();
	timeout(delay * 1000);
	window=newwin(0, 0, 0, 0);
	clear();

	if(!get_stats()){
		fprintf(stderr, "Failed to get all the stats. Please check correct permissions\n");
		endwin();
		return 1;
	}

	display_headings();

	for(;;){
		time_t now;
		int ch = getch();

		if (ch == 'q'){
			break;
		}

		/* To keep the numbers slightly accurate we do not want them
		 * updating more frequently than once a second.
		 */
		now = time(NULL);
		if ((now - last_update) >= 1) {
			get_stats();
		}
		last_update = now;

		if(sig_winch_flag) {
			clear();
			display_headings();
			sig_winch_flag = 0;
		}

		display_data(colouron);
	}

	endwin();
	return 0;
}
Beispiel #16
0
/*#DOC*/
int viewG_cursorVisibility(int visib)
{
       if (ERR == curs_set(visib)) return ERR;
       return OK;
}
Beispiel #17
0
int main(int argc, char **argv)
{
    int c, i;

    struct panelw *actw;
    MEVENT event;
    const char *cb;

    args.address = 0x20;
    args.bus = 0x02;
    args.columns = 16;
    args.rows = 2;

    do
    {
        i = 0;
        c = getopt_long(argc, argv, "abc::r::h", options, &i);
        switch(c)
        {
            case 'a':
                if (optarg)
                {
                    args.address = strtoul(optarg, NULL, 0);
                    if (args.address == 0x00)
                        help(argv, "Address of a chip must be a number!");
                }
                break;
            case 'b':
                if (optarg)
                {
                    args.bus = strtoul(optarg, NULL, 0);
                    if (args.bus == 0x00)
                        help(argv, "Bus number must be a number!");
                }
                break;
            case 'c':
                if (optarg)
                {
                    args.columns = strtoul(optarg, NULL, 0);
                    if (args.columns == 0x00)
                        help(argv, "The display is not in the list below:");
                }
                break;
            case 'r':
                if (optarg)
                {
                    args.rows = strtoul(optarg, NULL, 0);
                    if (args.rows == 0x00)
                        help(argv, "The display is not in the list below:");
                }
                break;
            case 'f':
                if (optarg)
                    strncpy(args.headername, optarg, 32);
                else
                    strncpy(args.headername, "./gcbitmap.h", 32);
                break;
            case 'h':
                help(argv, "");
            case -1:
                break;
            case '?':
                help(argv, "Unknown option");
                break;
            default:
                help(argv, "No options given");
                break;

        }
    }while(c != -1);

    initscr();
    refresh();
    keypad(stdscr, TRUE);
    nonl();
    cbreak();
    noecho();
    curs_set(1);

    if (has_colors())
    {
	start_color();
	init_pair(1, COLOR_BLACK, COLOR_GREEN);
	init_pair(2, COLOR_WHITE, COLOR_BLACK);
	init_pair(3, COLOR_WHITE, COLOR_BLUE);
	init_pair(4, COLOR_GREEN, COLOR_BLACK);

	wattron(stdscr, COLOR_PAIR(4));
	wbkgd(stdscr, COLOR_PAIR(4));
    }

    openEditor(&args, &ed);
    actw = ed._actw;
    for(i=0; i < 8; i++)
        lcdSetGC(&ed.lcd, i, gcbitmap[i]);
    setWindowState(actw, 1);
    gcActivateHandler(actw->next);

    while(((c = wgetch(actw->win)) != KEY_F(10)))
    {
	//
	switch(c)
	{
	    case KEY_F(5):
		ed.brght -= ed.brght > 0 ? 1 : 0;
		lcdSetBacklight(&ed.lcd, ed.brght);
                mvwprintw(ed.potss->win, 1, 1, "Brightness:\t0x%02X", ed.brght);
                update_panels();
                doupdate();
		refresh();
	    continue;
	    case KEY_F(6):
		ed.brght += ed.brght < 0x3f ? 1 : 0;
		lcdSetBacklight(&ed.lcd, ed.brght);
		mvwprintw(ed.potss->win, 1, 1, "Brightness:\t0x%02X", ed.brght);
                update_panels();
                doupdate();
		refresh();
	    continue;
	    case KEY_F(4):
		ed.contr -= ed.contr > 0 ? 1 : 0;
		lcdSetContrast(&ed.lcd, ed.contr);
                mvwprintw(ed.potss->win, 2, 1, "Contrast:\t0x%02X", ed.contr);
                update_panels();
                doupdate();
		refresh();
	    continue;
	    case KEY_F(3):
		ed.contr += ed.contr < 0x3f ? 1 : 0;
		lcdSetContrast(&ed.lcd, ed.contr);
		mvwprintw(ed.potss->win, 2, 1, "Contrast:\t0x%02X", ed.contr);
                update_panels();
                doupdate();
		refresh();
	    continue;
            case 9:
                setWindowState(actw, 0);
                actw = returnNextWindow(&ed);
                setWindowState(actw, 1);
                continue;
	    case KEY_MOUSE:
		if(getmouse(&event) == OK)
		{
		    printf("%d %d\n", event.x, event.y);
		}
		continue;
            default:
                if(actw->handler)
                    actw->handler(actw, c);
                continue;
	}

    }

    closeEditor(&ed);

    clear();
    endwin();

    return 0;
}
Beispiel #18
0
int main(int argc, char* argv[]){
  /* Initialize pseudo random number generator */
  srand(time(NULL));

  /* Read command line arguments */
  struct basic_options op;
  struct multi_options mop;
  if (get_options(argc, argv, &op, &mop) == 1) return 1;
 
  /* Setup signal handlers */
  struct sigaction newhandler;            /* new settings         */
  sigset_t         blocked;               /* set of blocked sigs  */
  newhandler.sa_flags = SA_RESTART;       /* options     */
  sigemptyset(&blocked);                  /* clear all bits       */
  newhandler.sa_mask = blocked;           /* store blockmask      */
  newhandler.sa_handler = on_timer;      /* handler function     */
  if ( sigaction(SIGALRM, &newhandler, NULL) == -1 )
    perror("sigaction");


  /* prepare the terminal for the animation */
  setlocale(LC_ALL, "");
  initscr();     /* initialize the library and screen */
  cbreak();      /* put terminal into non-blocking input mode */
  noecho();      /* turn off echo */
  start_color();
  clear();       /* clear the screen */
  curs_set(0);   /* hide the cursor */

  use_default_colors();
  init_pair(0, COLOR_WHITE, COLOR_BLACK);
  init_pair(1, COLOR_WHITE, COLOR_BLACK);
  init_pair(2, COLOR_BLACK, COLOR_BLACK);
  init_pair(3, COLOR_RED, COLOR_BLACK);
  init_pair(4, COLOR_GREEN, COLOR_BLACK);
  init_pair(5, COLOR_BLUE, COLOR_BLACK);
  init_pair(6, COLOR_YELLOW, COLOR_BLACK);
  init_pair(7, COLOR_MAGENTA, COLOR_BLACK);
  init_pair(8, COLOR_CYAN, COLOR_BLACK);
 
  color_set(0, NULL);
  assume_default_colors(COLOR_WHITE, COLOR_BLACK);
  clear();
    
  struct state st;
  struct ui ui;

  /* Initialize the parameters of the program */
  attrset(A_BOLD | COLOR_PAIR(2));
  mvaddstr(0,0,"Map is generated. Please wait.");
  refresh();

  state_init(&st, &op, &mop);
 
  ui_init(&st, &ui);

  clear();
 
  /* non-blocking input */
  int fd_flags = fcntl(0, F_GETFL);
  fcntl(0, F_SETFL, (fd_flags|O_NONBLOCK));

  /* Start the real time interval timer with delay interval size */
  struct itimerval it;
  it.it_value.tv_sec = 0;
  it.it_value.tv_usec = 10000;
  it.it_interval.tv_sec = 0;
  it.it_interval.tv_usec = 10000;
  setitimer(ITIMER_REAL, &it, NULL);
  
  refresh();        
  input_ready = 0;
  time_to_redraw = 1;

  if (!mop.multiplayer_flag) {
    /* Run the game */
    run(&st, &ui);
  }
  else {
    if (mop.server_flag) run_server(&st, mop.clients_num, mop.val_server_port);
    else run_client(&st, &ui, mop.val_server_addr, mop.val_server_port, mop.val_client_port);
  }

  /* Restore the teminal state */
  echo();
  curs_set(1);
  clear();
  endwin();

  if (!mop.multiplayer_flag || mop.server_flag)
    printf ("Random seed was %i\n", st.map_seed);

  free(mop.val_server_addr);
  free(mop.val_server_port);
  free(mop.val_client_port);
  return 0;
}
Beispiel #19
0
static void ui_terminal_save(Ui *ui) {
	UiCurses *uic = (UiCurses*)ui;
	curs_set(1);
	reset_shell_mode();
	termkey_stop(uic->termkey);
}
Beispiel #20
0
//GOODEND or BADEND
void END(int end,int stgnum,node_t *trees,int auto_or_mamual,Agent_status *agent)
{
    int total_points = agent->X;
    if (end == 0)
    {
        if (agent->X < 0)
        {
            total_points = 0;
            agent->X = 0;
        }
        if (agent->ENEMY_TOUCH_FLAG == 1)
        {
            total_points -= 50;
        }
        if (total_points < 0)
        {
            total_points = 0;
        }
        //BadEND
        if (agent->ON_OFF == 0){

            mvprintw(LINES/2+1,COLS/2-10,"(>_<;)  (>_< )");
            mvprintw(LINES/2,COLS/2-4,"GAME OVER");
            mvaddstr(LINES/2-3,COLS/2-10,"retry or quit [r/q] ?");
            curs_set(0);
            Refresh(agent);

            mvprintw(LINES/2+1,COLS/2-12,"(>_<;))    (>_< ) ");
            mvprintw(LINES/2,COLS/2-4,"GAME OVER");
            mvaddstr(LINES/2-3,COLS/2-10,"retry or quit [r/q] ?");
            curs_set(0);
            Refresh(agent);

            mvprintw(LINES/2+1,COLS/2-14,"(>_<;))))       (T-T ) ");
            mvprintw(LINES/2,COLS/2-4,"GAME OVER");
            mvaddstr(LINES/2-3,COLS/2-10,"retry or quit [r/q] ?");
            curs_set(0);
            Refresh(agent);

            mvprintw(LINES/2+1,COLS/2-16,"(>_<;)))))sorry          (T-T )");
            mvprintw(LINES/2,COLS/2-4,"GAME OVER");
            mvaddstr(LINES/2-3,COLS/2-10,"retry or quit [r/q] ?");
            curs_set(0);
            mvprintw(LINES/4,COLS/2-20,"%d DISTANCE = TOTAL %d POINTS!!!",agent->X,total_points);
            Refresh(agent);

        }
        //agent->END_FLAG = 1;
        agent->TOTAL_POINTS = total_points;


    }
    else
    {

        //GoodEND
        if(agent->ON_OFF == 0)
        {
            clear();
            mvprintw(LINES/2+1,COLS/2-8,"(*´<)          (>'*)");
            mvprintw(LINES/2,COLS/2-4,"GOOD END");
            mvaddstr(LINES/2-3,COLS/2-10,"retry or quit [r/q] ?");
            curs_set(0);
            Refresh(agent);

            clear();
            mvprintw(LINES/2+1,COLS/2-7,"(*´<)       (>'*)");
            mvprintw(LINES/2,COLS/2-4,"GOOD END");
            mvaddstr(LINES/2-3,COLS/2-10,"retry or quit [r/q] ?");
            curs_set(0);
            Refresh(agent);

            clear();
            mvprintw(LINES/2+1,COLS/2-6,"(*´<)    (>'*)");
            mvprintw(LINES/2,COLS/2-4,"GOOD END");
            mvaddstr(LINES/2-3,COLS/2-10,"retry or quit [r/q] ?");
            curs_set(0);
            Refresh(agent);

            clear();
            mvprintw(LINES/2+1,COLS/2-5,"(*´з)(ε'*)chu!!");
            mvprintw(LINES/2,COLS/2-4,"GOOD END");
            mvaddstr(LINES/2-3,COLS/2-10,"retry or quit [r/q] ?");
            curs_set(0);
            Refresh(agent);
        }


        total_points += agent->TIMES;
        mvprintw(LINES/4,COLS/2-30,"%d TIMES + %d DISTANCE = TOTAL %d POINTS!!!",agent->TIMES,agent->X,total_points);
        curs_set(0);
        Refresh(agent);

    }//Dead or Goal

    agent->END_FLAG = 1;
    agent->TOTAL_POINTS = total_points;

}
int dialog_inputbox(WINDOW *main_window,
		const char *title, const char *prompt,
		const char *init, char **resultp, int *result_len)
{
	int prompt_lines = 0;
	int prompt_width = 0;
	WINDOW *win;
	WINDOW *prompt_win;
	WINDOW *form_win;
	PANEL *panel;
	int i, x, y;
	int res = -1;
	int cursor_position = strlen(init);
	int cursor_form_win;
	char *result = *resultp;

	if (strlen(init)+1 > *result_len) {
		*result_len = strlen(init)+1;
		*resultp = result = realloc(result, *result_len);
	}

	/* find the widest line of msg: */
	prompt_lines = get_line_no(prompt);
	for (i = 0; i < prompt_lines; i++) {
		const char *line = get_line(prompt, i);
		int len = get_line_length(line);
		prompt_width = max(prompt_width, len);
	}

	if (title)
		prompt_width = max(prompt_width, strlen(title));

	/* place dialog in middle of screen */
	y = (LINES-(prompt_lines+4))/2;
	x = (COLS-(prompt_width+4))/2;

	strncpy(result, init, *result_len);

	/* create the windows */
	win = newwin(prompt_lines+6, prompt_width+7, y, x);
	prompt_win = derwin(win, prompt_lines+1, prompt_width, 2, 2);
	form_win = derwin(win, 1, prompt_width, prompt_lines+3, 2);
	keypad(form_win, TRUE);

	(void) wattrset(form_win, attributes[INPUT_FIELD]);

	(void) wattrset(win, attributes[INPUT_BOX]);
	box(win, 0, 0);
	(void) wattrset(win, attributes[INPUT_HEADING]);
	if (title)
		mvwprintw(win, 0, 3, "%s", title);

	/* print message */
	(void) wattrset(prompt_win, attributes[INPUT_TEXT]);
	fill_window(prompt_win, prompt);

	mvwprintw(form_win, 0, 0, "%*s", prompt_width, " ");
	cursor_form_win = min(cursor_position, prompt_width-1);
	mvwprintw(form_win, 0, 0, "%s",
		  result + cursor_position-cursor_form_win);

	/* create panels */
	panel = new_panel(win);

	/* show the cursor */
	curs_set(1);

	touchwin(win);
	refresh_all_windows(main_window);
	while ((res = wgetch(form_win))) {
		int len = strlen(result);
		switch (res) {
		case 10: /* ENTER */
		case 27: /* ESCAPE */
		case KEY_F(F_HELP):
		case KEY_F(F_EXIT):
		case KEY_F(F_BACK):
			break;
		case 127:
		case KEY_BACKSPACE:
			if (cursor_position > 0) {
				memmove(&result[cursor_position-1],
						&result[cursor_position],
						len-cursor_position+1);
				cursor_position--;
				cursor_form_win--;
				len--;
			}
			break;
		case KEY_DC:
			if (cursor_position >= 0 && cursor_position < len) {
				memmove(&result[cursor_position],
						&result[cursor_position+1],
						len-cursor_position+1);
				len--;
			}
			break;
		case KEY_UP:
		case KEY_RIGHT:
			if (cursor_position < len) {
				cursor_position++;
				cursor_form_win++;
			}
			break;
		case KEY_DOWN:
		case KEY_LEFT:
			if (cursor_position > 0) {
				cursor_position--;
				cursor_form_win--;
			}
			break;
		case KEY_HOME:
			cursor_position = 0;
			cursor_form_win = 0;
			break;
		case KEY_END:
			cursor_position = len;
			cursor_form_win = min(cursor_position, prompt_width-1);
			break;
		default:
			if ((isgraph(res) || isspace(res))) {
				/* one for new char, one for '\0' */
				if (len+2 > *result_len) {
					*result_len = len+2;
					*resultp = result = realloc(result,
								*result_len);
				}
				/* insert the char at the proper position */
				memmove(&result[cursor_position+1],
						&result[cursor_position],
						len-cursor_position+1);
				result[cursor_position] = res;
				cursor_position++;
				cursor_form_win++;
				len++;
			} else {
				mvprintw(0, 0, "unknown key: %d\n", res);
			}
			break;
		}
		if (cursor_form_win < 0)
			cursor_form_win = 0;
		else if (cursor_form_win > prompt_width-1)
			cursor_form_win = prompt_width-1;

		wmove(form_win, 0, 0);
		wclrtoeol(form_win);
		mvwprintw(form_win, 0, 0, "%*s", prompt_width, " ");
		mvwprintw(form_win, 0, 0, "%s",
			result + cursor_position-cursor_form_win);
		wmove(form_win, 0, cursor_form_win);
		touchwin(win);
		refresh_all_windows(main_window);

		if (res == 10) {
			res = 0;
			break;
		} else if (res == 27 || res == KEY_F(F_BACK) ||
				res == KEY_F(F_EXIT)) {
			res = KEY_EXIT;
			break;
		} else if (res == KEY_F(F_HELP)) {
			res = 1;
			break;
		}
	}

	/* hide the cursor */
	curs_set(0);
	del_panel(panel);
	delwin(prompt_win);
	delwin(form_win);
	delwin(win);
	return res;
}
Beispiel #22
0
int main(int argc, char* argv[])
{
  initscr();                        // initialize ncurses display
  nodelay(stdscr, 1);               // don't wait for key presses
  noecho();                         // don't echo key presses
  gz_spi_set_width(2);              // Pass blocks of 2 bytes on SPI
  gz_clock_ena(GZ_CLK_5MHz, 80);    // 250 kHz
  erase();
  outputs_off();
  printw("Modulating PWMs.\n");
  printw("Press 'n' for next test, any other key to stop.\n");
  int key = 0;
  while(1) {
    exercise_pwms();
    key = getch();
    if (key != -1) {
      break;
    }
  }
  if (key == 'n') {
    printw("Toggling all outputs.\n");
    printw("Press 'n' for next test, any other key to stop.\n");
    while(1) {
      exercise_outputs(0xff, 0x00);
      key = getch();
      if (key != -1) {
        break;
      }
    }
  }
  if (key == 'n') {
    erase();
    printw("Toggling alternate outputs.\n");
    printw("Press 'n' for next test, any other key to stop.\n");
    while(1) {
      exercise_outputs(0xaa, 0x55);
      key = getch();
      if (key != -1) {
        break;
      }
    }
  }
  if (key == 'n') {
    erase();
    printw("Walking outputs.\n");
    printw("Press 'n' for next test, any other key to stop.\n");
    unsigned char current = 0xfe;
    while(1) {
      exercise_outputs(current, (current << 1) | 0x01);
      current = (current << 2) | 0x03;
      if (current == 0xff) {
        current = 0xfe;
      }
      key = getch();
      if (key != -1) {
        break;
      }
    }
  }
  if (key == 'n') {
    erase();
    curs_set(0);                     // Hide the cursor
    printw("Reading inputs.\n");
    printw("Press any key to stop.\n");
    while(1) {
      display_inputs();
      key = getch();
      if (key != -1) {
        break;
      }
    }
    move(getcury(stdscr) + 1 ,0);
    curs_set(1);
    refresh();
  }
  gz_spi_close();                   // close SPI channel
  erase();
  reset_shell_mode();               // turn off ncurses
  return 0;
}
Beispiel #23
0
int xyControl()
{
	define_key("\033Op", 1000);
	define_key("\033Oq", 1001);
	define_key("\033Or", 1002);
	define_key("\033Os", 1003);
	define_key("\033Ot", 1004);
	define_key("\033Ou", 1005);
	define_key("\033Ov", 1006);
	define_key("\033Ow", 1007);
	define_key("\033Ox", 1008);
	define_key("\033Oy", 1009);

	// non-arrow keypad keys (for macros)
	define_key("\033OM", 1010); // Enter
	define_key("\033OP", 1011); // NumLock
	define_key("\033OQ", 1012); // /
	define_key("\033OR", 1013); // *
	define_key("\033OS", 1014); // -
	define_key("\033Oj", 1015); // *
	define_key("\033Ok", 1016); // +
	define_key("\033Ol", 1017); // +
	define_key("\033Om", 1018); // .
	define_key("\033On", 1019); // .
	define_key("\033Oo", 1020); // -
	clearScreen();
	echo();
	curs_set(2);
	int Xdist = 0;
	int Ydist = 0;
	while(!quit)
	{    //must be acuroind to servoblaster wiring convention
		move(10,0);
		clrtoeol();
		move(14,0);
		clrtoeol();
		refresh();
		mvprintw(10,5,"Curent Position: X:%d\tY:%d",posX,posY);
		mvprintw(14,5,"Move:");
		mvprintw(14,12,"X:%d",Xdist);
		mvprintw(14,22,"Y:%d",Ydist);
		move(14,14);
		refresh();
		char valueString [6];
		char c = getch();
		if(c=='q'||c=='Q')
			return 0;
		if(c!='\n')
		{
			printw("     ");
			refresh();
			ungetch(c);
			move(14,14);
			getnstr(valueString,6);
			Xdist = atoi(valueString);
		}
		move(14,24);
		c = getch();
		if(c=='q'||c=='Q')
			return 0;
		if(c!='\n')
		{
			printw("     ");
			refresh();
			ungetch(c);
			move(14,24);
			getnstr(valueString,6);
			Ydist = atoi(valueString);
		
		}
		move(15,4);
		clrtoeol;
		//getch();
		mvprintw(15,5,"MOVING       X:%d,   Y:%d              ",Xdist,Ydist);
		refresh();
		posX +=Xdist;
		posY +=Ydist;
		moveXY(Xdist,Ydist);
	}

}
Beispiel #24
0
//
// Demande à l'utilisateur s'il souhaite rejouer.
//
bool wantsToReplay(WINDOW *win, int top) {
    if(win == NULL || top < 0) return false;
    
    //variables pour l'affichage du menu
    ITEM **menuItems = NULL;
    MENU *menu = NULL;
    
    int i = 0, c;
    int nbChoices = 2;
    
    char *choices[] = {
        "Menu Principal",
        "Quitter"
    };
    
    int winWidth = POPUP_WINDOW_WIDTH;
    //largeur du menu = longueur du plus grand des choix possibles
    int menuWidth = 22;
    
    //on alloue de la mémoire pour initialiser les éléments du menu
    menuItems = (ITEM **) calloc(nbChoices + 1, sizeof(ITEM *));
    
    //on créé de nouveaux éléments à partir des choix fournis
    for(i = 0; i < nbChoices; i++) {
        menuItems[i] = new_item(choices[i], NULL);
    }
    
    //on met un élément nul à la fin du tableau
    menuItems[nbChoices] = (ITEM *) NULL;
    
    //on initialise le menu
    menu = new_menu((ITEM **) menuItems);
    
    //on lui précise bien que le menu fait 1 ligne et 2 colonnes
    set_menu_format(menu, 1, 2);
    
    //on associe le menu à une fenêtre et une sous-fenêtre
    set_menu_win(menu, win);
    //fenêtre hauteur largeur x y
    set_menu_sub(menu, derwin(win, nbChoices, menuWidth, top, (winWidth - menuWidth) / 2));
    
    menu_opts_off(menu, O_NONCYCLIC);
    set_menu_mark(menu, "");
    
    //et hop, on affiche le menu et on rafraîchit.
	post_menu(menu);
	
    refresh();
    wrefresh(win);
    
    curs_set(0);
    noecho();
    
    //boucle pour le menu
    while((c = getch())) {
        switch(c) {
            case KEY_LEFT:
            case KEY_UP:
                menu_driver(menu, REQ_LEFT_ITEM);
                break;
            case KEY_RIGHT:
            case KEY_DOWN:
                menu_driver(menu, REQ_RIGHT_ITEM);
                break;
            case KEY_MENU_ENTER: {
                int choice = item_index(current_item(menu));
                
                unpost_menu(menu);
                free_menu(menu);
                
                for(i = 0; i < nbChoices; ++i)
                    free_item(menuItems[i]);
                
                //si l'indice est 1 on renvoie 0 et vice-versa
                return !choice;
            }
        }
        
        wrefresh(win);
    }
    
    return false;
}