示例#1
0
文件: 190.C 项目: JackDrogon/Study
void edit()
{
 int j,n,i,a;
 float b;
 char tar[30],ch;
 int count=0;
		ch='y';
		while(ch=='y')
		{
		ptr = fopen("shop.dat","rb");
		clrscr();
		design();
		gotoxy(15,9);
		printf("\xDB\xDB ENTER ID OF THE PRODUCT TO BE SOLD:");
		scanf("%s",&tar);
		j=0;

		while((fread(&temp,sizeof(temp),1,ptr))==1)
		{
		   if((strcmp(temp.id,tar)<0) || (strcmp(temp.id,tar)>0))
		   {
		      x[j] = temp;
		      j++;
		    }
		  else
		  {
		  design();
		  gotoxy(8,7);
		  printf("\xDB\xDB  Description       = %s",temp.desc);
		  gotoxy(8,9);
		  printf("\xDB\xDB  Quantity in stock = %d",temp.quantity);
		  gotoxy(8,11);
		  printf("\xDB\xDB  Sales price       = %.2f",temp.sale);
		  gotoxy(8,13);
		  printf("\xDB\xDB  Quantity want to sale : ");
		  scanf("%d",&a);

		  x[j]=temp;
		  x[j].quantity=(x[j].quantity-a);
		  x[j].total=(x[j].quantity*temp.sale);
		  x[j].cost=(x[j].quantity*temp.unit);
		  x[j].bye=(x[j].sale*a);
		  b=x[j].bye;
		  x[j].qty=a;
		  j++;
		  count++;
		  }
		}
		if (count==0)
		{
		 clrscr();
		 design();
		 gotoxy(33,10);
		 printf("\a\xDB\xDB\xB2  Not in stock");
		 getch();
		 return;
		}

		fclose(ptr);
		n = j;
		clrscr();
		ptr=fopen("shop.dat","wb");
		for(i=0; i<n; i++)
		fwrite(&x[i],sizeof(x[i]),1,ptr);
		fclose(ptr);
		clrscr();
		design();
		gotoxy(8,9);
		printf("\xDB\xDB  Price paid by customer = %.2f",b);
		gotoxy(8,11);
		printf("\xDB\xDB  Quantity sold          = %d",a);
		getch();
		printf("more enteries=(y/n)");
		ch=getche();
		}
}
示例#2
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;
}
示例#3
0
	void keygen()
	{
	unsigned char key_string[50];
	long int s,s1,s2,power,p=0;
	int l,n;
	unsigned char ch;
	FILE *fp1;

	s=0;
	clrscr();
	printf("\n\n\nEnter your secret key string(Max. 16 chars. long) :");
		while(1)
		{
		ch=getch();
		if(ch!=13)
		{
		printf("*");
		key_string[s++]=ch;
		}
		else
		{
		key_string[s]='\0';
		break;
		}
		}
	s=0;
	for(l=0;key_string[l]!='\0';l++)
	{
	power=1;
	for(n=1;n<=l;n++)
	{
		power=power*2;
	}
	s+=power*key_string[l];
	}
	s1=0;
	s2=s;
	while(s2!=0)
	{
	p++;
	s1=s1+((s2%10)*p);
	s2=s2/10;
	}
	secure=s%s1;
	if(secure==0)
	secure=s1;
	for( ;secure>32; )
	secure=secure-32;
	if(secure>32)
	secure=secure/32;
	s1=0;
	s2=s;
	while(s2!=0)
	{
	s1=s1+((s2%10)*p);
	s2=s2/10;
	p--;
	}
	times=s%s1;
	if(times==0)
	times=s1;
	for( ;times>32; )
	times=times-32;
	if(times>32)
	times=times/32;
	printf("\n\nNumber of times of the randomization process will continue :%d\n",times);
	printf("\nNumber of times of Decryption is to be done :%d\n",secure);
	printf("\nPress any key to continue--->");
	getch();
	}
示例#4
0
int get_char() {
	return getch();
}
示例#5
0
void control(){
    init();
    int cmd;
    while (1)
    {     
        if(!is_lose){
            cmd=getch();
            if(cmd=='q'||cmd=='Q'||cmd==27) break;  //强制退出游戏
            //挡板左移
            if(cmd==KEY_LEFT){
                if(left_board>0){
                    move(BOTTOM,right_board);
                    addch(' ');
                    right_board--;
                    left_board--;                     
                    move(BOTTOM,left_board);
                    addch('-');
                    move(BOTTOM,RIGHT);
                    refresh();
                }
            }     
            //挡板右移
            else if(cmd==KEY_RIGHT){
                if(right_board<RIGHT){
                    move(BOTTOM,left_board);
                    addch(' ');
                    right_board++;
                    left_board++;
                    move(BOTTOM,right_board);
                    addch('-');
                    move(BOTTOM,RIGHT);
                    refresh();
                }
            }
            //给球加速
            else if(cmd==KEY_UP){   
                delay/=2;     
                set_ticker(delay);
            }
            //给球减速
            else if(cmd==KEY_DOWN){  
                delay*=2;
                set_ticker(delay);
            }
         
        }
        else{
            //输掉球后的处理
            int flag=1;
            char choice;
            move(8,15);
            addstr("Game Over!try again?(y/n):");
            refresh();
            choice=getch();
 
            while(flag){
                if(choice=='y'||choice=='Y'||choice=='n'||choice=='N')
                     flag=0;
                else  choice=getch();
            }
            if(choice=='y'||choice=='Y'){  /*游戏重新开始*/
                    delay=100; /*恢复球的初始速度*/
                    init();
                    continue;
            }
            else if(choice=='n'||choice=='N'){   /*结束游戏*/
                    break;
            }
        }
    }
}
示例#6
0
文件: ANI2.CPP 项目: pjmodi/projects
void main()
{
int gd=DETECT,gm,area,x=25,y=25,ch,xdirn=1,ydirn=1;
int maxx,maxy;
char *buff;

initgraph(&gd,&gm,"d:\\tc\\bgi");

setcolor(WHITE);
setfillstyle(SOLID_FILL,LIGHTRED);
circle(50,50,25);
floodfill(50,50,WHITE);

area=imagesize(25,25,75,75);
buff=(char *)malloc(area);
getimage(25,25,75,75,buff);

maxx=getmaxx();
maxy=getmaxy();
rectangle(0,20,maxx,maxy);
outtextxy(250,10,"Animation");

while(1)
	{
	if(kbhit())
		{
		ch=getch();

		if(ch=='\r')
			{
			xdirn*=-1;
			ydirn*=-1;
			}
		else
			{
			if(ch==27)
			break;
			}
		}

	putimage(x,y,buff,OR_PUT);
	delay(0);
	x=x+(xdirn*5);
	y=y+(ydirn*2);
	putimage(x,y,buff,OR_PUT);

       if(x>maxx-50||x<0);
		{
		sound(50);
		delay(10);
		nosound();
		xdirn*=-1;
		}

		if(y>maxy-50||y<20)
		{
		sound(50);
		delay(10);
		nosound();
		ydirn*=-1;
		}
       }

getch();
closegraph();
restorecrtmode();
}
示例#7
0
int curs_getch(void)
{
	int ch;
#ifdef NCURSES_VERSION_MAJOR
	MEVENT mevnt;
#endif

	if(curs_nextgetch) {
		ch=curs_nextgetch;
		curs_nextgetch=0;
	}
	else {
		while((ch=getch())==ERR) {
			if(mouse_trywait()) {
				curs_nextgetch=CIO_KEY_MOUSE>>8;
				return(CIO_KEY_MOUSE & 0xff);
			}
		}
		if(ch > 255) {
			switch(ch) {
				case KEY_DOWN:            /* Down-arrow */
					curs_nextgetch=0x50;
					ch=0;
					break;

				case KEY_UP:		/* Up-arrow */
					curs_nextgetch=0x48;
					ch=0;
					break;

				case KEY_LEFT:		/* Left-arrow */
					curs_nextgetch=0x4b;
					ch=0;
					break;

				case KEY_RIGHT:            /* Right-arrow */
					curs_nextgetch=0x4d;
					ch=0;
					break;

				case KEY_HOME:            /* Home key (upward+left arrow) */
					curs_nextgetch=0x47;
					ch=0;
					break;

				case KEY_BACKSPACE:            /* Backspace (unreliable) */
					ch=8;
					break;

				case KEY_F(1):			/* Function Key */
					curs_nextgetch=0x3b;
					ch=0;
					break;

				case KEY_F(2):			/* Function Key */
					curs_nextgetch=0x3c;
					ch=0;
					break;

				case KEY_F(3):			/* Function Key */
					curs_nextgetch=0x3d;
					ch=0;
					break;

				case KEY_F(4):			/* Function Key */
					curs_nextgetch=0x3e;
					ch=0;
					break;

				case KEY_F(5):			/* Function Key */
					curs_nextgetch=0x3f;
					ch=0;
					break;

				case KEY_F(6):			/* Function Key */
					curs_nextgetch=0x40;
					ch=0;
					break;

				case KEY_F(7):			/* Function Key */
					curs_nextgetch=0x41;
					ch=0;
					break;

				case KEY_F(8):			/* Function Key */
					curs_nextgetch=0x42;
					ch=0;
					break;

				case KEY_F(9):			/* Function Key */
					curs_nextgetch=0x43;
					ch=0;
					break;

				case KEY_F(10):			/* Function Key */
					curs_nextgetch=0x44;
					ch=0;
					break;

				case KEY_F(11):			/* Function Key */
					curs_nextgetch=0x57;
					ch=0;
					break;

				case KEY_F(12):			/* Function Key */
					curs_nextgetch=0x58;
					ch=0;
					break;

				case KEY_DC:            /* Delete character */
					curs_nextgetch=0x53;
					ch=0;
					break;

				case KEY_IC:            /* Insert char or enter insert mode */
					curs_nextgetch=0x52;
					ch=0;
					break;

				case KEY_EIC:            /* Exit insert char mode */
					curs_nextgetch=0x52;
					ch=0;
					break;

				case KEY_NPAGE:            /* Next page */
					curs_nextgetch=0x51;
					ch=0;
					break;

				case KEY_PPAGE:            /* Previous page */
					curs_nextgetch=0x49;
					ch=0;
					break;

				case KEY_ENTER:            /* Enter or send (unreliable) */
					curs_nextgetch=0x0d;
					ch=0;
					break;

				case KEY_A1:		/* Upper left of keypad */
					curs_nextgetch=0x47;
					ch=0;
					break;

				case KEY_A3:		/* Upper right of keypad */
					curs_nextgetch=0x49;
					ch=0;
					break;

				case KEY_B2:		/* Center of keypad */
					curs_nextgetch=0x4c;
					ch=0;
					break;

				case KEY_C1:		/* Lower left of keypad */
					curs_nextgetch=0x4f;
					ch=0;
					break;

				case KEY_C3:		/* Lower right of keypad */
					curs_nextgetch=0x51;
					ch=0;
					break;

				case KEY_BEG:		/* Beg (beginning) */
					curs_nextgetch=0x47;
					ch=0;
					break;

				case KEY_CANCEL:		/* Cancel */
					curs_nextgetch=0x03;
					ch=0;
					break;

				case KEY_END:		/* End */
					curs_nextgetch=0x4f;
					ch=0;
					break;

				case KEY_SELECT:		/* Select  - Is "End" in X */
					curs_nextgetch=0x4f;
					ch=0;
					break;

#ifdef NCURSES_VERSION_MAJOR
				case KEY_MOUSE:			/* Mouse stuff */
					if(getmouse(&mevnt)==OK) {
						int evnt=0;
						switch(mevnt.bstate) {
							case BUTTON1_PRESSED:
								evnt=CIOLIB_BUTTON_1_PRESS;
								break;
							case BUTTON1_RELEASED:
								evnt=CIOLIB_BUTTON_1_RELEASE;
								break;
							case BUTTON2_PRESSED:
								evnt=CIOLIB_BUTTON_2_PRESS;
								break;
							case BUTTON2_RELEASED:
								evnt=CIOLIB_BUTTON_2_RELEASE;
								break;
							case BUTTON3_PRESSED:
								evnt=CIOLIB_BUTTON_3_PRESS;
								break;
							case BUTTON3_RELEASED:
								evnt=CIOLIB_BUTTON_3_RELEASE;
								break;
							case REPORT_MOUSE_POSITION:
								evnt=CIOLIB_MOUSE_MOVE;
								break;
						}
						ciomouse_gotevent(evnt, mevnt.x+1, mevnt.y+1);
					}
					break;
#endif

				default:
					curs_nextgetch=0xff;
					ch=0;
					break;
			}
		}
	}
	return(ch);
}
示例#8
0
void KeyboardInput_INPUT_SHEAR() {
	if (Event::is_setviewport == true) {
		setviewport(0, 0, MAXX, MAXY, 1);
		Event::is_setviewport = false;
	}
	bool stop = false;
	Style::POS = 0;
	Style::InputText[0] = NULL; Style::InputText[85] = NULL;
	Style::normal_KEY_Shear();
	while (true) {
		if (Event::draw != Event::SHEAR) {
			stop = true;
			Style::hide_KEY();
			break;
		}
		if (kbhit()) {
			char c = getch();
			switch (c) {
			case 8: //backspace
				if (Style::POS > 0)
				{
					Style::POS = Style::POS - 1;
					Style::InputText[Style::POS] = NULL;
				}
				break;
			case 9: //tab
			case 32: //spacebar
			case 13: //return
				if (Style::POS < 85) {
					Style::POS = 85;
				}
				else {
					stop = true;
					Style::hide_KEY();
				}
				break;
			case 27: //Escape
				if (Style::POS < 85) {
					Style::InputText[0] = NULL;
				}
				else {
					Style::InputText[85] = NULL;
				}
				break;
			default:
				if (Style::POS < Style::nInputText - 1 && c >= '0' && c <= '9' || c == '.' || c == '-')
				{
					Style::InputText[Style::POS] = c;
					Style::POS = Style::POS + 1;
					Style::InputText[Style::POS] = NULL;
				} break;
			}
			if (stop == false) {
				if (Event::is_setviewport == true) {
					setviewport(0, 0, MAXX, MAXY, 1);
					Event::is_setviewport = false;
				}
				Style::normal_KEY_Shear();
			}
			else {
				break;
			}
		}
	}

	if (Event::draw == Event::SHEAR) {

		if (Event::is_setviewport == false) {
			setviewport(Event::item_drawing_area->layer->startx + 1, Event::item_drawing_area->layer->starty + 1, Event::item_drawing_area->layer->endx - Event::item_drawing_area->scrollbar->scrollthick, Event::item_drawing_area->layer->endy - Event::item_drawing_area->scrollbar->scrollthick, 1);
			Event::is_setviewport = true;
		}

		float g = (float)(atof(Style::InputText)), h = (float)(atof(Style::InputText + 85));

		putimage(Event::graph_sample->item->layer->startx, Event::graph_sample->item->layer->starty, Event::graph_sample->below, 0);

		Graph* drawing_graph = new Graph;
		drawing_graph->item = Event::graph_sample->item;
		drawing_graph->item->graph = drawing_graph;

		drawing_graph->set(Point(Event::graph_sample->points[0].x, Event::graph_sample->points[0].y), *Event::graph_sample, Event::graph_sample->width, Event::graph_sample->height);
		drawing_graph->shear((int)(g), (int)(h));

		drawing_graph->showsavior(Event::item_drawing_area->scrollbar);

		Event::item_drawing_area->scrollbar->update_show();

		delete Event::graph_sample;
		Event::graph_sample = NULL;

		if (Event::is_setviewport == true) {
			setviewport(0, 0, MAXX, MAXY, 1);
			Event::is_setviewport = false;
		}
	}
	Event::KeyboardInput = Event::INPUT_NONE;
}
示例#9
0
void KeyboardInput_INPUT_SQUARE() {
	if (Event::is_setviewport == true) {
		setviewport(0, 0, MAXX, MAXY, 1);
		Event::is_setviewport = false;
	}
	bool stop = false;
	Style::POS = 0;
	Style::InputText[0] = Style::InputText[85] = Style::InputText[170] = NULL;
	Style::normal_KEY_Square();
	while (true) {
		if (Event::draw != Event::SQUARE) {
			stop = true;
			Style::hide_KEY();
			break;
		}
		if (kbhit()) {
			char c = getch();
			switch (c) {
				case 8: //backspace
					if (Style::POS > 0)
					{
						Style::POS = Style::POS - 1;
						Style::InputText[Style::POS] = NULL;
					}
					break;
				case 9: //tab
				case 32: //spacebar
				case 13: //return
					if (Style::POS < 85) {
						Style::POS = 85;
					}
					else if (Style::POS < 170) {
						Style::POS = 170;
					}
					else {
						stop = true;
						Style::hide_KEY();
					}
					break;
				case 27: //Escape
					if (Style::POS < 85) {
						Style::InputText[0] = NULL;
					}
					else if (Style::POS < 170) {
						Style::InputText[85] = NULL;
					}
					else {
						Style::InputText[170] = NULL;
					}
					break;
				default:
					if (Style::POS < Style::nInputText - 1 && c >= '0' && c <= '9')
					{
						Style::InputText[Style::POS] = c;
						Style::POS = Style::POS + 1;
						Style::InputText[Style::POS] = NULL;
					} break;
			}
			if (stop == false) {
				if (Event::is_setviewport == true) {
					setviewport(0, 0, MAXX, MAXY, 1);
					Event::is_setviewport = false;
				}
				Style::normal_KEY_Square();
			}
			else {
				break;
			}
		}
	}

	if (Event::draw == Event::SQUARE) {
		if (Event::is_setviewport == false) {
			setviewport(Event::item_drawing_area->layer->startx + 1, Event::item_drawing_area->layer->starty + 1, Event::item_drawing_area->layer->endx - Event::item_drawing_area->scrollbar->scrollthick, Event::item_drawing_area->layer->endy - Event::item_drawing_area->scrollbar->scrollthick, 1);
			Event::is_setviewport = true;
		}
		int x = atoi(Style::InputText), y = atoi(Style::InputText + 85), a = atoi(Style::InputText + 170);
		SquareBresenhamSavior(x, y, a, Event::color, Event::item_drawing_area->scrollbar);
		Event::item_drawing_area->scrollbar->update_show();
		if (Event::is_setviewport == true) {
			setviewport(0, 0, MAXX, MAXY, 1);
			Event::is_setviewport = false;
		}
	}
	Event::KeyboardInput = Event::INPUT_NONE;
}
示例#10
0
文件: main.cpp 项目: bong0/school
int main(int argc, char **argv){
	/*
	 * Init Variables
	 */
	WINDOW *w_game = NULL; //game field
	WINDOW *w_gamefrm = NULL; // frame around the game field
	/* prepare panels in order */
	PANEL *p_game=NULL, *p_gamefrm=NULL;
	FILE *urandom;

	urandom = fopen("/dev/urandom", "rb");// treat as binary

	int *xPos, *yPos; //current x and y positions
	frame term, game;
	/*
	 * Gameplay Variables
	 */
	snake snk;
	xPos = &(snk.body[0][0]);
	yPos = &(snk.body[1][0]);
	snk.bodysym = ACS_BLOCK;
	snk.length=1;
	int cookie[2] = {0,0}; // stores cookie location x y; negative vals are invalid
	float speed = 150; // steps/ms
	char vector[2] = {0,0}; // movement vector x y
	int lastPos[2]; // store last position
	bool mod_length=FALSE;
	bool vec_diff=FALSE;

	/*
	 * Setup Terminal
	 */
	setup_term(&term, w_game);

	/*
	 * Setup Game Field
	 */
	w_game = prep_game(w_game, w_gamefrm, p_game, p_gamefrm, &game, &term, xPos, yPos, &snk);

	placeCookie(w_game, &game, cookie, urandom);
	getch();

	while(true){
		mvwprintw(stdscr, 22, 1, "snklen:%d", snk.length); 
		chdir_snake(w_game, &term, xPos, yPos, vector, &snk, &vec_diff);

		mod_length=mv_snake(w_game, &game, &term, &snk, xPos, yPos, vector, cookie, urandom, vec_diff);
		if(mod_length){
			xPos=&(snk.body[0][(snk.length)-1]); // need to renew position of head in arr
			yPos=&(snk.body[1][(snk.length)-1]);
		}
			
		debug(stdscr, &term, xPos, yPos);
		mvwprintw(stdscr, 5,1, "%d %d", snk.body[0][0], snk.body[1][0]);
		mvwprintw(stdscr, 6,1, "%d %d", snk.body[0][1], snk.body[1][1]);
		mvwprintw(stdscr, 7,1, "%d %d", snk.body[0][2], snk.body[1][2]);
		mvwprintw(stdscr, 8,1, "%d %d", snk.body[0][3], snk.body[1][3]);
		mvwprintw(stdscr, 9,1, "%d %d", snk.body[0][4], snk.body[1][4]);

		do_refresh(w_game, xPos, yPos, vector, &snk);
		wait(vector, &speed);
	}

 do_exit(urandom, 0);
 return 0;
}
示例#11
0
/* Main Function to start the Main menu */
int smitfsmenu(void)
{
	WINDOW *fsmdlg; /* Makes a Dialog for main menu */
	
	getmaxyx(stdscr, y,x);
	
	int menuitem, menukey;
	
	menuitem = 0;
	
	while(menuitem != 8)
	{
	 drawsmitfsmenu(menuitem);
	 refresh();
	 do
	 {
		 menukey = getch();
		 switch(menukey)
		 {
		 case KEY_F(1): /* Display Help */
		//	helpfunc();
			break;
			case KEY_F(2): /* Refresh Screen */
			refresh();
			break;
			case KEY_F(9): /* Runs the Shell */
			executedefaultshell();
			  break;
			case KEY_F(10): /* Exits */
			    clear();
			    return 0;
			 case KEY_DOWN:
			  menuitem++;
			  if(menuitem > FS_MENU_MAX) menuitem = 0;
			  break;
			case KEY_UP:
			  menuitem--;
			  if(menuitem < 0) menuitem = FS_MENU_MAX-1;
			  break;
			default:
			  break; 
		    }	
	   drawsmitfsmenu(menuitem);
	   refresh();
	 
	} while(menukey != '\n');
	
	/* If Statments which reflects on menu items goes here */		

		if(menuitem == 0) 
		{
			fsmgrmain();
		
		}
		else if(menuitem == 2)
		{
			mntlistmain();
		}
		else if(menuitem == 3)
		{
				endwin();
				system(SADE);  // Runs FreeBSD Sade
		}
		else if(menuitem == 6)
		{
			dfmain();
		};	
			
		
	}; /* End of While statements */ 
	
	clear();

	return 0;
	
	
}
示例#12
0
void player::power_bionics(game *g)
{
    int HEIGHT = TERMY;
    int WIDTH = FULL_SCREEN_WIDTH;
    int START_X = (TERMX - WIDTH)/2;
    int START_Y = (TERMY - HEIGHT)/2;
 WINDOW* wBio = newwin(HEIGHT, WIDTH, START_Y, START_X);
    int DESCRIPTION_WIDTH = WIDTH - 2; // Same width as bionics window minus 2 for the borders
    int DESCRIPTION_HEIGHT = 3;
    int DESCRIPTION_START_X = getbegx(wBio) + 1; // +1 to avoid border
    int DESCRIPTION_START_Y = getmaxy(wBio) - DESCRIPTION_HEIGHT - 1; // At the bottom of the bio window, -1 to avoid border
 WINDOW* w_description = newwin(DESCRIPTION_HEIGHT, DESCRIPTION_WIDTH, DESCRIPTION_START_Y, DESCRIPTION_START_X);

 werase(wBio);
 wborder(wBio, LINE_XOXO, LINE_XOXO, LINE_OXOX, LINE_OXOX,
               LINE_OXXO, LINE_OOXX, LINE_XXOO, LINE_XOOX );

 std::vector <bionic> passive;
 std::vector <bionic> active;
 int HEADER_TEXT_Y = START_Y + 1;
 mvwprintz(wBio, HEADER_TEXT_Y,  1, c_blue, _("BIONICS -"));
 mvwprintz(wBio, HEADER_TEXT_Y, 11, c_white, _("Activating.  Press '!' to examine your implants."));
 show_power_level_in_titlebar(wBio, this);

 int HEADER_LINE_Y = START_Y + 2;
 int DESCRIPTION_LINE_Y = DESCRIPTION_START_Y - 1;
 for (int i = 1; i < 79; i++) {
  mvwputch(wBio, HEADER_LINE_Y, i, c_ltgray, LINE_OXOX); // Draw line under title
  mvwputch(wBio, DESCRIPTION_LINE_Y, i, c_ltgray, LINE_OXOX); // Draw line above description
 }

 // Draw symbols to connect additional lines to border
 mvwputch(wBio, HEADER_LINE_Y,  0, c_ltgray, LINE_XXXO); // |-
 mvwputch(wBio, HEADER_LINE_Y, 79, c_ltgray, LINE_XOXX); // -|

 mvwputch(wBio, DESCRIPTION_LINE_Y,  0, c_ltgray, LINE_XXXO); // |-
 mvwputch(wBio, DESCRIPTION_LINE_Y, 79, c_ltgray, LINE_XOXX); // -|

 for (int i = 0; i < my_bionics.size(); i++) {
  if (!bionics[my_bionics[i].id]->activated)
   passive.push_back(my_bionics[i]);
  else
   active.push_back(my_bionics[i]);
 }
 nc_color type;
 if (passive.size() > 0) {
  mvwprintz(wBio, 3, 1, c_ltblue, _("Passive:"));
  for (int i = 0; i < passive.size(); i++) {
   if (bionics[passive[i].id]->power_source)
    type = c_ltcyan;
   else
    type = c_cyan;
   mvwputch(wBio, 4 + i, 1, type, passive[i].invlet);
   mvwprintz(wBio, 4 + i, 3, type, bionics[passive[i].id]->name.c_str());
  }
 }
 if (active.size() > 0) {
  mvwprintz(wBio, 3, 33, c_ltblue, _("Active:"));
  for (int i = 0; i < active.size(); i++) {
   if (active[i].powered && !bionics[active[i].id]->power_source)
    type = c_red;
    else if (bionics[active[i].id]->power_source && !active[i].powered)
    type = c_ltcyan;
    else if (bionics[active[i].id]->power_source && active[i].powered)
    type = c_ltgreen;
   else
    type = c_ltred;

   mvwputch(wBio, 4 + i, 33, type, active[i].invlet);
   mvwprintz(wBio, 4 + i, 35, type,
             (active[i].powered ? _("%s - ON") : _("%s - %d PU / %d trns")),
             bionics[active[i].id]->name.c_str(),
             bionics[active[i].id]->power_cost,
             bionics[active[i].id]->charge_time);
  }
 }
 wrefresh(wBio);
 char ch;
 bool activating = true;
 bionic *tmp = NULL;
 int b = 0;
 do {
  ch = getch();
  if (ch == '!') {
   activating = !activating;
   if (activating)
    mvwprintz(wBio, 1, 11, c_white, _("Activating.  Press '!' to examine your implants."));
   else
    mvwprintz(wBio, 1, 11, c_white, _("Examining.  Press '!' to activate your implants."));
  } else if (ch == ' ')
   ch = KEY_ESCAPE;
  else if (ch != KEY_ESCAPE) {
   for (int i = 0; i < my_bionics.size(); i++) {
    if (ch == my_bionics[i].invlet) {
     tmp = &my_bionics[i];
     b = i;
     ch = KEY_ESCAPE;
    }
   }
   if (ch == KEY_ESCAPE) {
    if (activating) {
     if (bionics[tmp->id]->activated) {
      show_power_level_in_titlebar(wBio, this);
      itype_id weapon_id = weapon.type->id;
      if (tmp->powered) {
       tmp->powered = false;
       g->add_msg(_("%s powered off."), bionics[tmp->id]->name.c_str());
      } else if (power_level >= bionics[tmp->id]->power_cost ||
                 (weapon_id == "bio_claws_weapon" && tmp->id == "bio_claws_weapon"))
       activate_bionic(b, g);
     } else
      mvwprintz(wBio, 21, 1, c_ltred, _("\
You can not activate %s!  To read a description of \
%s, press '!', then '%c'."), bionics[tmp->id]->name.c_str(),
                            bionics[tmp->id]->name.c_str(), tmp->invlet);
    } else {	// Describing bionics, not activating them!
// Clear the lines first
     ch = 0;
     werase(w_description);
     mvwprintz(w_description, 0, 0, c_ltblue, bionics[tmp->id]->description.c_str());
    }
   }
  }
  wrefresh(w_description);
  wrefresh(wBio);
 } while (ch != KEY_ESCAPE);
示例#13
0
Tabuleiro Usuario::Processa (Tabuleiro T, int lado) {
  int end=0,estado=1,sx,sy,i;

  T.ShowCursor ();
  do {
    gotoxy (40,1);
    cprintf ("Lado %d Estado=%d ",lado,estado);
    gotoxy (px*2+1,py+1);
    switch (getch ()) {
      case 0: switch (toupper (getch ())) {
                case UP:    py-=1;
                            break;
                case DOWN:  py+=1;
                            break;
                case RIGHT: px+=1;
                            break;
                case LEFT:  px-=1;
                            break;
              }
              if (px<0) px=7;
              if (py<0) py=7;
              if (px>7) px=0;
              if (py>7) py=0;
              T.DrawOne (px,py,T.tab[px][py]);
              break;
      case 27: endgame=1;
               end=1;
               break;
      case 'R': T.Draw ();
                break;
      case 13: if (estado) {
                 if (T.tab[px][py]%2==lado) {
                   textcolor (WHITE);
                   T.DrawOne (px,py,T.tab[px][py]);
                   textcolor (LIGHTGRAY);
                   estado=0;
                   sx=px;
                   sy=py;
                 }
               } else {
                 if (T.Checa (sx,sy,px,py,lado)) {
                   T.tab[px][py]=T.tab[sx][sy];
                   T.tab[sx][sy]=0;
                   end=1;
                   T.DrawOne (sx,sy,0);
                   textcolor (WHITE);
                   T.DrawOne (px,py,T.tab[px][py]);
                   textcolor (LIGHTGRAY);
                   if (T.comidas) {
                     for (i=0; i<T.comidas; i++) {
                       T.tab[T.pos[i][0]][T.pos[i][1]]=0;
                       T.DrawOne (T.pos[i][0],T.pos[i][1],0);
                     }
                   }
                 } else {
                   T.DrawOne (sx,sy,T.tab[sx][sy]);
                   estado=1;
                 }
               }
    }
  } while (!end);
  return T;
}
示例#14
0
文件: 190.C 项目: JackDrogon/Study
 menu()
{
 int x;
  do{
       {
	clrscr();
	design();
	t();
	textcolor(WHITE);
	gotoxy(24,3);
	cprintf("\xDB\xDB\xDB\xDB\xB2  SAM'S DEPARTMANTAL STORE  \xB2\xDB\xDB\xDB\xDB");
	gotoxy(3,4);
	cprintf("--------------------------------------------------------------------------");
	gotoxy(35,5);
	cprintf("MAIN MENU");
	gotoxy(26,8);
	cprintf(" 1  -   INFORMATION ABOUT PRODUCTS            ");
	gotoxy(26,9);
	cprintf(" 2  -   ENTER  PURCHASE  RECORDS            ");
	gotoxy(26,10);
	cprintf(" 3  -   ENTER PRODUCTS TO BE SALE           ");
	gotoxy(26,11);
	cprintf(" 4  -   SEARCH FOR RECORD                     ");
	gotoxy(26,12);
	cprintf(" 5  -   DELETE RECORD FROM STORE DATABASE     ");
	gotoxy(26,13);
	cprintf(" 6  -   VIEW SALES , PURCHASE & PROFIT REPORT ");
	gotoxy(26,14);
	cprintf(" 7  -   PRINT RECORDS                         ");
	gotoxy(26,15);
	cprintf(" 8  -   BAR  GRAPH OF QUANTITY / PROFIT       ");
	gotoxy(26,16);
	cprintf(" 9  -   RETRIEVE INFORMATION         ");
	gotoxy(26,17);
	cprintf(" H  -   HELP                                  ");
	gotoxy(26,18);
	cprintf(" E  -   EXIT                                  ");
	gotoxy(26,23);
	cprintf("ENTER YOUR CHOICE :: ");
	gotoxy(47,23);
	x=toupper(getch());
	switch(x)
	{
	case '1':
	infor();
	break;

	case '2':
	entry();
	break;

	case '3':
	edit();
	break;

	case '4':
	search();
	break;

	case '5':
	del();
	break;

	case '6':
	report2();
	break;

	case '7':
	print();
	break;

	case 'h': case'H':
	help();
	break;

	case'8':
	graph1();
	break;

	case '9':
	display();
	break;

	case 'e': case 'E':
	exit(0);
	break;

	default:
	clrscr();
	design();
	gotoxy(17,12);
	printf("\a\xDB\xB2  WRONG ENTRY : PRESS ANY KEY AND TRY AGAIN");
	getche();
	}
      }
    }while((x!='e')||(x!='E'));
return x;
}
示例#15
0
static void *
ncurses_input_thread(void *unsafe_marsh){
	struct ncurses_input_marshal *nim = unsafe_marsh;
	WINDOW *w = nim->w;
	int ch;

	active = NULL; // No subpanels initially
	while((ch = getch()) != 'q' && ch != 'Q'){
	switch(ch){
		case KEY_HOME:
			lock_ncurses();
			if(selecting()){
				use_first_node_locked();
			}
			unlock_ncurses();
			break;
		case KEY_END:
			lock_ncurses();
			if(selecting()){
				use_last_node_locked();
			}
			unlock_ncurses();
			break;
		case KEY_PPAGE:
			lock_ncurses();
			if(selecting()){
				use_prev_nodepage_locked();
			}
			unlock_ncurses();
			break;
		case KEY_NPAGE:
			lock_ncurses();
			if(selecting()){
				use_next_nodepage_locked();
			}
			unlock_ncurses();
			break;
		case KEY_UP: case 'k':
			lock_ncurses();
			if(!selecting()){
				use_prev_iface_locked(w,&details);
			}else{
				use_prev_node_locked();
			}
			unlock_ncurses();
			break;
		case KEY_DOWN: case 'j':
			lock_ncurses();
			if(!selecting()){
				use_next_iface_locked(w,&details);
			}else{
				use_next_node_locked();
			}
			unlock_ncurses();
			break;
		case KEY_RESIZE:
			lock_ncurses();{
				resize_screen_locked(w);
			}unlock_ncurses();
			break;
		case 9: // Tab FIXME
			lock_ncurses();
				toggle_focus();
			unlock_ncurses();
			break;
		case 12: // Ctrl-L FIXME
			lock_ncurses();{
				redraw_screen_locked();
			}unlock_ncurses();
			break;
		case '\r': case '\n': case KEY_ENTER:
			lock_ncurses();{
				select_iface_locked();
			}unlock_ncurses();
			break;
		case KEY_ESC: case KEY_BACKSPACE:
			lock_ncurses();{
				deselect_iface_locked();
			}unlock_ncurses();
			break;
		case 'l':
			lock_ncurses();
				toggle_panel(w,&diags,display_diags_locked);
			unlock_ncurses();
			break;
		case 'D':
			lock_ncurses();
				resolve_selection(w);
			unlock_ncurses();
			break;
		case 'r':
			lock_ncurses();
				reset_current_interface_stats(w);
			unlock_ncurses();
			break;
		case 'P':
			lock_ncurses();
				toggle_subwindow_pinning();
			unlock_ncurses();
			break;
		case 'p':
			lock_ncurses();
				toggle_promisc_locked(w);
			unlock_ncurses();
			break;
		case 'd':
			lock_ncurses();
				down_interface_locked(w);
			unlock_ncurses();
			break;
		case 's':
			lock_ncurses();
				sniff_interface_locked(w);
			unlock_ncurses();
			break;
		case '+':
		case KEY_RIGHT:
			lock_ncurses();
				expand_iface_locked();
			unlock_ncurses();
			break;
		case '-':
		case KEY_LEFT:
			lock_ncurses();
				collapse_iface_locked();
			unlock_ncurses();
			break;
		case 'v':{
			lock_ncurses();
				toggle_panel(w,&details,display_details_locked);
			unlock_ncurses();
			break;
		}case 'n':{
			lock_ncurses();
				toggle_panel(w,&network,display_network_locked);
			unlock_ncurses();
			break;
		}case 'e':{
			lock_ncurses();
				toggle_panel(w,&environment,display_env_locked);
			unlock_ncurses();
			break;
		}case 'w':{
			lock_ncurses();
				toggle_panel(w,&channels,display_channels_locked);
			unlock_ncurses();
			break;
		}case 'b':{
			lock_ncurses();
				toggle_panel(w,&bridging,display_bridging_locked);
			unlock_ncurses();
			break;
		}case 'h':{
			lock_ncurses();
				toggle_panel(w,&help,display_help_locked);
			unlock_ncurses();
			break;
		}default:{
			const char *hstr = !help.p ? " ('h' for help)" : "";
			// wstatus() locks/unlocks, and calls screen_update()
			if(isprint(ch)){
				wstatus(w,"unknown command '%c'%s",ch,hstr);
			}else{
				wstatus(w,"unknown scancode %d%s",ch,hstr);
			}
			break;
		}
	}
	}
	wstatus(w,"%s","shutting down");
	// we can't use raise() here, as that sends the signal only
	// to ourselves, and we have it masked.
	pthread_kill(nim->maintid,SIGINT);
	pthread_exit(NULL);
}
示例#16
0
std::vector<item> game::multidrop(std::vector<item> &dropped_worn, int &freed_volume_capacity)
{
    WINDOW* w_inv = newwin(TERRAIN_WINDOW_HEIGHT, TERRAIN_WINDOW_WIDTH + (use_narrow_sidebar() ? 45 : 55), VIEW_OFFSET_Y, VIEW_OFFSET_X);
    const int maxitems = TERRAIN_WINDOW_HEIGHT - 5;
    freed_volume_capacity = 0;

    u.inv.restack(&u);
    u.inv.sort();
    int drp_line_width=getmaxx(w_inv)-90;
    const std::string drp_line_padding = ( drp_line_width > 1 ? std::string(drp_line_width, ' ') : " ");
    std::map<int, int> dropping; // Count of how many we'll drop from each position
    int count = 0; // The current count
    std::vector<char> dropped_armor; // Always single, not counted
    int dropped_weapon = 0;
    bool warned_about_bionic = false; // Printed add_msg re: dropping bionics
    print_inv_statics(w_inv, _("Multidrop:"), dropped_armor, dropped_weapon);
    int base_weight = u.weight_carried();
    int base_volume = u.volume_carried();

    int ch = (int)'.';
    int start = 0, cur_it = 0, max_it;
    indexed_invslice stacks = u.inv.slice_filter();
    CategoriesVector CATEGORIES;
    std::vector<int> firsts = find_firsts(stacks, CATEGORIES);
    int selected = -1;
    int selected_pos = INT_MIN;

    int next_category_at = 0;
    int prev_category_at = 0;
    bool inCategoryMode = false;

    std::vector<int> category_order;
    category_order.reserve(firsts.size());

    // Items are not guaranteed to be in the same order as their categories, in fact they almost never are.
    // So we sort the categories by which items actually show up first in the inventory.
    for (int current_item = 0; current_item < u.inv.size(); ++current_item) {
        for (int i = 1; i < CATEGORIES.size(); ++i) {
            if (current_item == firsts[i - 1]) {
                category_order.push_back(i - 1);
            }
        }
    }

    do {
        // Find the inventory position of the first item in the previous and next category (in relation
        // to the currently selected category).
        for (int i = 0; i < category_order.size(); ++i) {
            if (selected > firsts[category_order[i]] && prev_category_at <= firsts[category_order[i]]) {
                prev_category_at = firsts[category_order[i]];
            }

            if (selected < firsts[category_order[i]] && next_category_at <= selected) {
                next_category_at = firsts[category_order[i]];
            }
        }

        inventory drop_subset = u.inv.subset(dropping);
        int new_weight = base_weight - drop_subset.weight();
        int new_volume = base_volume - drop_subset.volume();
        for (int i = 0; i < dropped_armor.size(); ++i) {
            new_weight -= u.i_at(dropped_armor[i]).weight();
        }
        if (dropped_weapon == -1) {
            new_weight -= u.weapon.weight();
        } else if (dropped_weapon > 0) {
            item tmp(u.weapon);
            tmp.charges = dropped_weapon;
            new_weight -= tmp.weight();
        }
        print_inv_weight_vol(w_inv, new_weight, new_volume, calc_volume_capacity(dropped_armor));
        int cur_line = 2;
        max_it = 0;
        int drp_line = 1;
        // Print weapon to be dropped, the first position is reserved for high visibility
        mvwprintw(w_inv, 0, 90, "%s", drp_line_padding.c_str());
        if (dropped_weapon != 0) {
            if (dropped_weapon == -1) {
                mvwprintz(w_inv, 0, 90, c_ltblue, "%c + %s", u.weapon.invlet, u.weapname().c_str());
            } else {
                mvwprintz(w_inv, 0, 90, c_ltblue, "%c # %s {%d}", u.weapon.invlet, u.weapon.tname().c_str(), dropped_weapon);
            }
            mvwprintw(w_inv, drp_line, 90, "%s", drp_line_padding.c_str());
            drp_line++;
        }
        // Print worn items to be dropped
        bool dropping_a = false;
        if (u.worn.size() > 0){
            for (int k = 0; k < u.worn.size(); k++) {
                bool dropping_w = false;
                for (int j = 0; j < dropped_armor.size() && !dropping_w; j++) {
                    if (dropped_armor[j] == u.worn[k].invlet) {
                        dropping_w = true;
                        dropping_a = true;
                        mvwprintw(w_inv, drp_line, 90, "%s", drp_line_padding.c_str());
                        mvwprintz(w_inv, drp_line, 90, c_cyan, "%c + %s", u.worn[k].invlet, u.worn[k].tname().c_str());
                        drp_line++;
                    }
                }
            }
        }
        if(dropping_a) {
            mvwprintw(w_inv, drp_line, 90, "%s", drp_line_padding.c_str());
            drp_line++;
        }
        for (cur_it = start; cur_it < start + maxitems && cur_line < maxitems+3; cur_it++) {
            // Clear the current line;
            mvwprintw(w_inv, cur_line, 0, "                                             ");
            mvwprintw(w_inv, drp_line, 90, "%s", drp_line_padding.c_str());
            mvwprintw(w_inv, drp_line + 1, 90, "%s", drp_line_padding.c_str());
            // Print category header
            for (int i = 1; i < CATEGORIES.size(); i++) {
                if (cur_it == firsts[i-1]) {
                    mvwprintz(w_inv, cur_line, 0, c_magenta, CATEGORIES[i].name.c_str());
                    cur_line++;
                }
            }

            if ( selected < start && selected > -1 ) selected = start;

            if (cur_it < stacks.size()) {
                item& it = stacks[cur_it].first->front();
                if( cur_it == selected) {
                    selected_pos = stacks[cur_it].second;
                }
                const char invlet = it.invlet == 0 ? ' ' : it.invlet;
                nc_color selected_line_color = inCategoryMode ? c_white_red : h_white;
                mvwputch (w_inv, cur_line, 0, (cur_it == selected ? selected_line_color : c_white), invlet);
                char icon = '-';
                if (dropping[cur_it] >= (it.count_by_charges() ? it.charges : stacks[cur_it].first->size())) {
                    icon = '+';
                } else if (dropping[cur_it] > 0) {
                    icon = '#';
                }
                nc_color col = ( cur_it == selected ? selected_line_color : it.color_in_inventory() );
                mvwprintz(w_inv, cur_line, 1, col, " %c %s", icon,
                          it.tname().c_str());
                if (stacks[cur_it].first->size() > 1) {
                    wprintz(w_inv, col, " x %d", stacks[cur_it].first->size());
                }
                if (it.charges > 0) {
                    wprintz(w_inv, col, " (%d)", it.charges);
                } else if (it.contents.size() == 1 &&
                           it.contents[0].charges > 0) {
                    wprintw(w_inv, " (%d)", it.contents[0].charges);
                }
                if (icon=='+'||icon=='#') {
                    mvwprintz(w_inv, drp_line, 90, col, "%c %c %s", invlet, icon, it.tname().c_str());
                    if (icon=='+') {
                        if (stacks[cur_it].first->size() > 1) {
                            wprintz(w_inv, col, " x %d", stacks[cur_it].first->size());
                        }
                        if (it.charges > 0) {
                            wprintz(w_inv, col, " (%d)", it.charges);
                        }
                    }
                    if (icon=='#') {
                        wprintz(w_inv, col, " {%d}", dropping[cur_it]);
                    }
                    drp_line++;
                }
            }
            cur_line++;
            max_it=cur_it;
        }

        if (inCategoryMode) {
            mvwprintz(w_inv, maxitems + 4, 32, c_white_red, _("In category select mode! Press [TAB] to enter item select mode."));
        } else {
            mvwprintz(w_inv, maxitems + 4, 32, h_white, _("In item select mode! Press [TAB] to enter category select mode."));
        }

        if (start > 0) {
            mvwprintw(w_inv, maxitems + 4, 0, _("< Go Back"));
        }
        if (cur_it < u.inv.size()) {
            mvwprintw(w_inv, maxitems + 4, 12, _("> More items"));
        }
        wrefresh(w_inv);
/* back to (int)getch() as input() mangles arrow keys
  ch = input();
*/
        ch = getch();

        if (ch == '\t') {
            inCategoryMode = !inCategoryMode;
        }
        else if ( ch == '<' || ch == KEY_PPAGE ) {
            if( start > 0) {
                for (int i = 1; i < maxitems+4; i++)
                    mvwprintz(w_inv, i, 0, c_black, "                                             ");
                start -= maxitems;
                if (start < 0)
                    start = 0;
                mvwprintw(w_inv, maxitems + 4, 0, "         ");
                if ( selected > -1 ) selected = start; // oy, the cheese
            }
        } else if ( ch == '>' || ch == KEY_NPAGE ) {
            if ( cur_it < u.inv.size()) {
                start = cur_it;
                mvwprintw(w_inv, maxitems + 4, 12, "            ");
                for (int i = 1; i < maxitems+4; i++)
                    mvwprintz(w_inv, i, 0, c_black, "                                             ");
                if ( selected < start && selected > -1 ) selected = start;
            }
        } else if ( ch == KEY_DOWN ) {
            if ( selected < 0 ) {
                selected = start;
            } else {
                if (inCategoryMode) {
                    selected < firsts[category_order[category_order.size() - 1]] ? selected = next_category_at : 0;
                } else {
                    selected++;
                }

                next_category_at = prev_category_at = 0;
            }

            if ( selected > max_it ) {
                if( cur_it < u.inv.size() ) {
                    start = cur_it;
                    mvwprintw(w_inv, maxitems + 4, 12, "            ");
                    for (int i = 1; i < maxitems+4; i++)
                        mvwprintz(w_inv, i, 0, c_black, "                                             ");
                } else {
                    selected = u.inv.size() - 1; // wraparound?
                }
            }
        } else if ( ch == KEY_UP ) {
            inCategoryMode ? selected = prev_category_at : selected--;
            next_category_at = prev_category_at = 0;

            if ( selected < -1 ) {
                selected = -1; // wraparound?
            } else if ( selected < start ) {
                if ( start > 0 ) {
                    for (int i = 1; i < maxitems+4; i++)
                        mvwprintz(w_inv, i, 0, c_black, "                                             ");
                    start -= maxitems;
                    if (start < 0)
                        start = 0;
                    mvwprintw(w_inv, maxitems + 4, 0, "         ");
                }
            }
        } else if (ch >= '0'&& ch <= '9') {
            ch = (char)ch - '0';
            count *= 10;
            count += ch;
        } else { // todo: reformat and maybe rewrite
            item* it;
            int it_pos;
            if ( ch == '\t' || ch == KEY_RIGHT || ch == KEY_LEFT ) {
                it_pos = selected_pos;
                it = &u.inv.find_item(it_pos);
            } else {
                it = &u.inv.item_by_letter((char)ch);
                it_pos = u.inv.position_by_item(it);
            }
            if (it == 0 || it->is_null()) { // Not from inventory
                int found = false;
                for (int i = 0; i < dropped_armor.size() && !found; i++) {
                    if (dropped_armor[i] == ch) {
                        dropped_armor.erase(dropped_armor.begin() + i);
                        found = true;
                        print_inv_statics(w_inv, _("Multidrop:"), dropped_armor, dropped_weapon);
                    }
                }
                if (!found && ch == u.weapon.invlet && !u.weapon.is_null()) {
                    if (u.weapon.has_flag("NO_UNWIELD")) {
                        if (!warned_about_bionic) {
                            add_msg(_("You cannot drop your %s."), u.weapon.tname().c_str());
                            warned_about_bionic = true;
                        }
                    } else {
                        // user selected weapon, which is a normal item
                        if (count == 0) {
                            // No count given, invert the selection status: drop all <-> drop none
                            if (dropped_weapon == 0) {
                                dropped_weapon = -1;
                            } else {
                                dropped_weapon = 0;
                            }
                        } else if (u.weapon.count_by_charges() && count < u.weapon.charges) {
                            // can drop part of weapon and count is valid for this
                            dropped_weapon = count;
                        } else {
                            dropped_weapon = -1;
                        }
                        count = 0;
                        print_inv_statics(w_inv, _("Multidrop:"), dropped_armor, dropped_weapon);
                    }
                } else if (!found) {
                    dropped_armor.push_back(ch);
                    print_inv_statics(w_inv, _("Multidrop:"), dropped_armor, dropped_weapon);
                }
            } else {
                int index = -1;
                for (int i = 0; i < stacks.size(); ++i) {
                    if (&(stacks[i].first->front()) == it) {
                        index = i;
                        break;
                    }
                }
                if (index == -1) {
                    debugmsg("Inventory got out of sync with inventory slice?");
                }
                if (count == 0) {
                    if (it->count_by_charges()) {
                        if (dropping[it_pos] == 0) {
                            dropping[it_pos] = -1;
                        } else {
                            dropping[it_pos] = 0;
                        }
                    } else {
                        if (dropping[it_pos] == 0) {
                            dropping[it_pos] = stacks[index].first->size();
                        } else {
                            dropping[it_pos] = 0;
                        }
                    }
                } else if (count >= stacks[index].first->size() && !it->count_by_charges()) {
                    dropping[it_pos] = stacks[index].first->size();
                } else {
                    dropping[it_pos] = count;
                }

                count = 0;
            }
        }
    } while (ch != '\n' && ch != KEY_ESCAPE && ch != ' ');
    werase(w_inv);
    delwin(w_inv);
    erase();
    refresh_all();

    std::vector<item> ret;

    if (ch != '\n')
        return ret; // Canceled!

    // We iterate backwards because deletion will invalidate later indices.
    for (std::map<int,int>::reverse_iterator it = dropping.rbegin(); it != dropping.rend(); ++it) {
        if (it->second == -1)
            ret.push_back( u.inv.remove_item( it->first));
        else if (it->second && u.inv.find_item( it->first).count_by_charges()) {
            int charges = u.inv.find_item( it->first).charges;// >= it->second ? : it->second;
            ret.push_back( u.inv.reduce_charges( it->first, it->second > charges ? charges : it->second));
        } else if (it->second)
            for (int j = it->second; j > 0; j--)
                ret.push_back( u.inv.remove_item( it->first));
    }
    if (dropped_weapon == -1) {
        ret.push_back(u.remove_weapon());
    } else if (dropped_weapon > 0) {
        ret.push_back(u.weapon);
        u.weapon.charges -= dropped_weapon;
        ret.back().charges = dropped_weapon;
    }

    for (int i = 0; i < dropped_armor.size(); i++)
    {
        int wornpos = u.invlet_to_position(dropped_armor[i]);
        const it_armor *ita = dynamic_cast<const it_armor *>(u.i_at(dropped_armor[i]).type);
        if (wornpos == INT_MIN || !u.takeoff(wornpos, true))
        {
            continue;
        }
        u.moves -= 250; // same as in game::takeoff
        if(ita != 0) {
            freed_volume_capacity += ita->storage;
        }
        // Item could have been dropped after taking it off
        if (&u.inv.item_by_letter(dropped_armor[i]) != &u.inv.nullitem)
        {
            dropped_worn.push_back(u.i_rem(dropped_armor[i]));
        }
    }

    return ret;
}
示例#17
0
int main(int *argc, char *argv[])
{
	SOCKET sockfd; // Definimos un socket, lo llamamos sockfd
	struct sockaddr_in server_in; // Estructura basica para llamadas al sistema y funciones relacionada con direcciones de Internet
	char buffer_in[1024], buffer_out[1048],origen[15],destino[15],mensaje[500]="",asunto[20],copia[500]; // Buffers y entrada de datos
	int recibidos=0,enviados=0; // Variables para el envio y recepcion de los datos, ambas iniciadas a 0
	int estado=S_HELO; // Estados de la conexion iniciado a S_HELO
	char option; // Variable condicional para el bucle "do"
	WORD wVersionRequested; // Para trabajar con sockets en Windows
	WSADATA wsaData; // Para trabajar con sockets en Windows
	int err,fin=0,opcion; // Usamos "err" para la comprobacion de errores
    char ipdest[16];// Declaramos la direccion IP destino
	char default_ip[16]="127.0.0.1"; // Direccion IP establecida por defecto
	int i;
	/*Para la fecha y hora*/
	time_t tiempo = time(0);
	struct tm *tlocal = localtime(&tiempo);
	char zona[10];
	char output[20];

	//Inicialización Windows sockets
	wVersionRequested=MAKEWORD(1,1);
	err=WSAStartup(wVersionRequested,&wsaData);
	if(err!=0)
		return(0);

	if(LOBYTE(wsaData.wVersion)!=1||HIBYTE(wsaData.wVersion)!=1)
	{
		WSACleanup();  // Liberar recursos de la liberia
		return(0);
	}
	//Fin: Inicialización Windows sockets

	/* Con "do" se crea el socket en el que se recibiran y se enviaran los datos */

	do{
		sockfd=socket(AF_INET,SOCK_STREAM,0);  //Creamos socket

		if(sockfd==INVALID_SOCKET) // Si el socket es invalido, mostramos un error por pantalla.
		{
			printf("CLIENTE> ERROR AL CREAR SOCKET\r\n");
			exit(-1);
		} 
		else // Si el socket es valido, mostramos mensaje por pantalla
		{
			printf("CLIENTE> SOCKET CREADO CORRECTAMENTE\r\n");

			// Pedimos la IP de destino, si pulsamos "Enter" introduciremos la IP por defecto indicada en la parte superior del codigo		
			printf("CLIENTE> Introduzca la IP destino (pulsar enter para IP por defecto): ");
			gets(ipdest);

			// Para introducir la IP por defecto al pulsar "Enter"
			if(strcmp(ipdest,"")==0)
				strcpy(ipdest,default_ip);

			// Asignamos los valores a la estructura creada al inicio del codigo, "server_in"
			server_in.sin_family=AF_INET; // Familia de protocolos de Internet
			server_in.sin_port=htons(SMTP_SERVICE_PORT); // Puerto del servidor
			server_in.sin_addr.s_addr=inet_addr(ipdest); // Direccion IP del servidor
			
			estado=S_WELCOME; // Se reestablece el estado inicial
		
			// establece la conexion de transporte
			if(connect(sockfd,(struct sockaddr*)&server_in,sizeof(server_in))==0)
			{
				printf("CLIENTE> CONEXION ESTABLECIDA CON %s:%d\r\n",ipdest,SMTP_SERVICE_PORT);
				fin=0;
			
				//Inicio de la máquina de estados

				do{
					fflush(stdin); /*limpiamos el buffer de teclado*/

					/*Enviar más de un correo*/
						if(estado==S_QUIT  && strncmp(buffer_in,"2",1)==0)
						{
							char opcion;
							printf("¿Deseas enviar otro correo? S/N\n");
							opcion=getch();
							if(opcion=='s' || opcion=='S')
							{
							estado=S_MAIL; /*Pasamos al estado de destinatario*/
							}
						 }
				
					switch(estado)  //Maquina de estados
					{

					case S_WELCOME:
						// Se recibe el mensaje de bienvenida
						
						break;
					case S_HELO:
						// Se prepara el comando helo
						sprintf_s (buffer_out, sizeof(buffer_out), "HELO %s%s",ipdest,CRLF);
						break;

					case S_MAIL:
						// Establece la conexion de aplicacion 
						printf("CLIENTE> Introduzca su usuario: ");
						gets(origen);
						if(strlen(origen)==0) /*Si no se introduce nada, se vuelve a pedir*/
						{
							do{
								printf("CLIENTE> Introduzca su usuario: ");
								gets(origen);

							}while(strlen(origen)==0); //Repetimos la peticion de usuario hasta cumplir la condicion

						sprintf_s (buffer_out, sizeof(buffer_out), "MAIL FROM: %s%s",origen,CRLF);  //Guardamos MAIL FROM en el buffer junto al usuario origen

						}
						else
						{
						sprintf_s (buffer_out, sizeof(buffer_out), "MAIL FROM: %s%s",origen,CRLF); //Guardamos MAIL FROM en el buffer junto al usuario origen
						}
						break;

					case S_RCPT:
						// Introducimos el destinatario del mail
						printf("CLIENTE> Introduzca el destinatario: ");
						gets(destino);
						if(strlen(destino)==0)  /*Si no se introduce nada, se vuelve a pedir*/

						{ 
								do{
									printf("CLIENTE> Introduzca el destinatario: ");
									gets(destino);
								
								}while(strlen(destino)==0); //Repetimos la peticion de usuario hasta cumplir la condicion

							sprintf_s (buffer_out, sizeof(buffer_out), "RCPT TO: %s%s",destino,CRLF); //Guardamos RCPT TO en el buffer junto al destinatario
						}
						else
						{
							sprintf_s (buffer_out, sizeof(buffer_out), "RCPT TO: %s%s",destino,CRLF); //Guardamos RCPT TO en el buffer junto al destinatario
						}
						break;

					case S_DATA:
				// Empieza el envio del cuerpo del mensaje
						sprintf_s (buffer_out, sizeof(buffer_out), "DATA%s",CRLF);
						estado=S_MENSAJE;
						break;
				case S_MENSAJE:
					// Escribimos el mensaje
					 strftime(output,128,"%d/%m/%y %H:%M:%S",tlocal);				//Fecha, hora y zona horaria
					 printf("Introduce el asunto del mensaje:");
					 gets(asunto); // Asunto del email

					 /*Envio de las cabeceras*/
					 sprintf_s(buffer_out, sizeof(buffer_out), "Date: %s GMT:%d%sFrom: <%s>%sSubject: %s%sTo: <%s>%s%s",output,getTimeZone(),CRLF,origen,CRLF,asunto,CRLF,destino,CRLF,CRLF); // Cabeceras del correo según RFC

					 enviados=send(sockfd,buffer_out,(int)strlen(buffer_out),0);
					 /*Comprobacion de envío correcto*/
					 if(enviados==SOCKET_ERROR || enviados==0) // Si ha habido error en el socket o no hay datos enviados
						{
							if(enviados==SOCKET_ERROR)
							{
							DWORD error=GetLastError();
							printf("CLIENTE> Error %d en el envío de datos\r\n",error); // Error 
							fin=1;
							}
							else
							{
							printf("CLIENTE> Conexión con el servidor cerrada\r\n"); // Cerramos conexion
							fin=1;
							}
							continue;
						}
									 
					 printf("Introduce el mensaje: "); // Introducimos el mensaje
						do
						{
							gets(copia);
							sprintf_s(buffer_out, sizeof(buffer_out), "%s%s",copia,CRLF);
							if(strcmp(copia,".")!=0)  /*Solo se envia el mensaje si es distinto de '.'*/ 
							{
							enviados=send(sockfd,buffer_out,(int)strlen(buffer_out),0);
							/*Comprobacion de envio correcto*/
								if(enviados==SOCKET_ERROR || enviados==0) // Error o sin datos enviados
								{
									if(enviados==SOCKET_ERROR)
									{
										DWORD error=GetLastError();
										printf("CLIENTE> Error %d en el envío de datos\r\n",error);
										fin=1;
									}
									else
									{
										printf("CLIENTE> Conexión con el servidor cerrada\r\n");
										fin=1;
									}
								continue;
								}
							}
						}while(strcmp(copia,".")!=0); /*Se van enviando todas las cadenas que introduce el cliente hasta introducir un "."*/
										
						sprintf_s(buffer_out, sizeof(buffer_out), ".%s",CRLF); /*Metemos en el buffer_out el fin de mensaje*/
						
					break;

				case S_QUIT:
//Fin
					sprintf_s (buffer_out, sizeof(buffer_out), "QUIT%s",CRLF); 
					fin=1;
					break;
					}/*Cierre del switch*/
								
				
					if(estado!=S_WELCOME){ //Si no estamos en WELCOME, se produce el envio
						enviados=send(sockfd,buffer_out,(int)strlen(buffer_out),0);
						if(enviados==SOCKET_ERROR || enviados==0) // Si hay error o no hay datos enviados, mostramos los errores
						{
							if(enviados==SOCKET_ERROR)
							{
							DWORD error=GetLastError();
							printf("CLIENTE> Error %d en el envío de datos\r\n",error);
							fin=1;
							}
							else
							{
							printf("CLIENTE> Conexión con el servidor cerrada\r\n");
							fin=1;
							}
							continue;
						}
					}
						
					/*Recibimos los datos del servidor*/
					recibidos=recv(sockfd,buffer_in,512,0);
					
					if(recibidos<=0) // Si recibimos 0 o -1
					{
						DWORD error=GetLastError();
						if(recibidos<0) // Si recibimos un -1 o SOCKET_ERROR la operacion ha fallado
						{
							printf("CLIENTE> Error %d en la recepción de datos\r\n",error); 
							fin=1;
						}
						else // Si recibimos un 0, la conexion ha sido liberada de forma acordada
						{
							printf("CLIENTE> Conexión con el servidor cerrada\r\n");
							fin=1;
						
					
						}
					}else{  // Si recibimos la cantidad de bytes enviados
						
						buffer_in[recibidos]=0x00; // Iniciamos a 0 porque en C los arrays finalizan con el byte 0000 0000
						printf(buffer_in); // Imprimimos por pantalla el valor
 
						/*Comprobacion de envio correcto mediante las respuestas del servidor, todas empezaran por 2 (250,221) */
						if((estado==S_WELCOME || estado==S_HELO || estado==S_MAIL || estado==S_RCPT || estado==S_MENSAJE) && strncmp(buffer_in,"2",1)==0)
							estado++;
						/*La respuesta del servidor para DATA es 354*/
						if(estado==S_DATA && strncmp(buffer_in,"3",1)==0)
							estado++;
					}

				}while(fin!=1); 
			}
			else
			{
				printf("CLIENTE> ERROR AL CONECTAR CON %s:%d\r\n",ipdest,SMTP_SERVICE_PORT); // Muestra el mensaje de error al conectar el cliente con la IP destino y el puerto TCP escogidos
			}		
			// fin de la conexion de transporte
			closesocket(sockfd);
			
		}	
		do{
		printf("-----------------------\r\n\r\nCLIENTE> Volver a conectar (S/N)\r\n"); // Opcion para volver a realizar una conexion
		option=_getche();
		}while((option!='s' && option!='S') && (option!='n' && option!='N'));
		
	}while(option!='n' && option!='N');
	// Fin del primer "do", sale de el cuando se introduce por teclado una "n" o una "N"
	
	
	return(0);

}
示例#18
0
void game::compare(int iCompareX, int iCompareY)
{
 int examx, examy;
 std::vector <item> grounditems;
 int ch = (int)'.';

 if (iCompareX != -999 && iCompareY != -999) {
  examx = u.posx + iCompareX;
  examy = u.posy + iCompareY;
 } else if (!choose_adjacent(_("Compare where?"),examx,examy)) {
     return;
 }

 std::vector <item> here = m.i_at(examx, examy);
 //Filter out items with the same name (keep only one of them)
 std::map <std::string, bool> dups;
 for (int i = 0; i < here.size(); i++) {
  if (!dups[here[i].tname().c_str()]) {
   grounditems.push_back(here[i]);
   dups[here[i].tname().c_str()] = true;
  }
 }
 //Only the first 10 Items due to numbering 0-9
 const int groundsize = (grounditems.size() > 10 ? 10 : grounditems.size());
 u.inv.restack(&u);
 u.inv.sort();

 indexed_invslice stacks = u.inv.slice_filter();

 WINDOW* w_inv = newwin(TERMY-VIEW_OFFSET_Y*2, TERMX-VIEW_OFFSET_X*2, VIEW_OFFSET_Y, VIEW_OFFSET_X);
 int maxitems = TERMY-5-VIEW_OFFSET_Y*2;    // Number of items to show at one time.
 std::vector<int> compare_list; // Count of how many we'll drop from each stack
 bool bFirst = false; // First Item selected
 bool bShowCompare = false;
 char cLastCh = 0;
 compare_list.resize(u.inv.size() + groundsize, 0);
 std::vector<char> dropped_armor; // Always single, not counted
 int dropped_weapon = 0;
 print_inv_statics(w_inv, "Compare:", dropped_armor, dropped_weapon);
// Gun, ammo, weapon, armor, food, tool, book, other
 CategoriesVector CATEGORIES;
 std::vector<int> first = find_firsts(stacks, CATEGORIES);
 std::vector<int> firsts;
 if (groundsize > 0) {
  firsts.push_back(0);
 }
 for (int i = 0; i < first.size(); i++) {
  firsts.push_back((first[i] >= 0) ? first[i]+groundsize : -1);
 }
 ch = '.';
 int start = 0, cur_it = 0;
 do {
  if (( ch == '<' || ch == KEY_PPAGE ) && start > 0) {
   for (int i = 1; i < maxitems+4; i++)
    mvwprintz(w_inv, i, 0, c_black, "                                             ");
   start -= maxitems;
   if (start < 0)
    start = 0;
   mvwprintw(w_inv, maxitems + 4, 0, "         ");
  }
  if (( ch == '>' || ch == KEY_NPAGE ) && cur_it < u.inv.size() + groundsize) {
   start = cur_it;
   mvwprintw(w_inv, maxitems + 4, 12, "            ");
   for (int i = 1; i < maxitems+4; i++)
    mvwprintz(w_inv, i, 0, c_black, "                                             ");
  }
  int cur_line = 2;
  int iHeaderOffset = (groundsize > 0) ? 0 : 1;

  for (cur_it = start; cur_it < start + maxitems && cur_line < maxitems+3; cur_it++) {
// Clear the current line;
   mvwprintw(w_inv, cur_line, 0, "                                             ");
// Print category header
   for (int i = iHeaderOffset; i < CATEGORIES.size(); i++) {
    if (cur_it == firsts[i-iHeaderOffset]) {
     mvwprintz(w_inv, cur_line, 0, c_magenta, CATEGORIES[i].name.c_str());
     cur_line++;
    }
   }
   if (cur_it < u.inv.size() + groundsize) {
    char icon = '-';
    if (compare_list[cur_it] == 1)
     icon = '+';
    if (cur_it < groundsize) {
     mvwputch (w_inv, cur_line, 0, c_white, '1'+((cur_it<9) ? cur_it: -1));
     nc_color col = (compare_list[cur_it] == 0 ? c_ltgray : c_white);
     mvwprintz(w_inv, cur_line, 1, col, " %c %s", icon,
               grounditems[cur_it].tname().c_str());
    } else {
     item& it = stacks[cur_it-groundsize].first->front();
     const char invlet = it.invlet == 0 ? ' ' : it.invlet;
     mvwputch (w_inv, cur_line, 0, c_white, invlet);
     nc_color col = (compare_list[cur_it] == 0 ? c_ltgray : c_white);
     mvwprintz(w_inv, cur_line, 1, col, " %c %s", icon,
               it.tname().c_str());
     if (stacks[cur_it-groundsize].first->size() > 1)
      wprintz(w_inv, col, " x %d", stacks[cur_it-groundsize].first->size());
     if (it.charges > 0)
      wprintz(w_inv, col, " (%d)", it.charges);
     else if (it.contents.size() == 1 &&
              it.contents[0].charges > 0)
      wprintw(w_inv, " (%d)", it.contents[0].charges);
    }
   }
   cur_line++;
  }
  if (start > 0)
   mvwprintw(w_inv, maxitems + 4, 0, _("< Go Back"));
  if (cur_it < u.inv.size() + groundsize)
   mvwprintw(w_inv, maxitems + 4, 12, _("> More items"));
  wrefresh(w_inv);
  ch = getch();
  if (u.has_item((char)ch)) {
   item& it = u.inv.item_by_letter((char)ch);
   if (it.is_null()) { // Not from inventory
    bool found = false;
    for (int i = 0; i < dropped_armor.size() && !found; i++) {
     if (dropped_armor[i] == ch) {
      dropped_armor.erase(dropped_armor.begin() + i);
      found = true;
      bFirst = false;
      print_inv_statics(w_inv, "Compare:", dropped_armor, dropped_weapon);
     }
    }
    if (!found && dropped_weapon == -1 && ch == u.weapon.invlet) {
     found = true;
     bFirst = false;
     dropped_weapon = 0;
     print_inv_statics(w_inv, "Compare:", dropped_armor, dropped_weapon);
    }
    if (!found) {
      if (!bFirst)
      {
       dropped_weapon = -1;
       print_inv_statics(w_inv, "Compare:", dropped_armor, dropped_weapon);
       bFirst = true;
       cLastCh = ch;
      } else {
       bShowCompare = true;
      }
    }
   } else {
    int index = -1;
    for (int i = 0; i < stacks.size(); ++i) {
     if (&(stacks[i].first->front()) == &it) {
      index = i;
      break;
     }
    }
    if (index == -1) {
     debugmsg("Inventory got out of sync with inventory slice?");
    }
    if (compare_list[index+groundsize] == 1)
    {
     compare_list[index+groundsize] = 0;
     bFirst = false;
    } else {
     if (!bFirst)
     {
      compare_list[index+groundsize] = 1;
      bFirst = true;
      cLastCh = ch;
     } else {
      bShowCompare = true;
     }
    }
   }
  } else if ((ch >= '1' && ch <= '9' && ch-'1' < groundsize) || (ch == '0' && groundsize == 10)) {
   //Ground Items
   int iZero = 0;
   if (ch == '0') {
    iZero = 10;
   }
   if (compare_list[ch-'1'+iZero] == 1)
   {
    compare_list[ch-'1'+iZero] = 0;
    bFirst = false;
   } else {
    if (!bFirst)
    {
     compare_list[ch-'1'+iZero] = 1;
     bFirst = true;
     cLastCh = ch;
    } else {
     bShowCompare = true;
    }
   }
  }
  if (bShowCompare) {
   std::vector<iteminfo> vItemLastCh, vItemCh;
   std::string sItemLastCh, sItemCh;
   if (cLastCh >= '0' && cLastCh <= '9') {
    int iZero = 0;
    if (cLastCh == '0') {
     iZero = 10;
    }

    grounditems[cLastCh-'1'+iZero].info(true, &vItemLastCh);
    sItemLastCh = grounditems[cLastCh-'1'+iZero].tname();
   } else {
    u.i_at(cLastCh).info(true, &vItemLastCh);
    sItemLastCh = u.i_at(cLastCh).tname();
   }

   if (ch >= '0' && ch <= '9') {
    int iZero = 0;
    if (ch == '0') {
     iZero = 10;
    }

    grounditems[ch-'1'+iZero].info(true, &vItemCh);
    sItemCh = grounditems[ch-'1'+iZero].tname();
   } else {
    item& item = u.i_at((char)ch);
    item.info(true, &vItemCh);
    sItemCh = item.tname();
   }

   compare_split_screen_popup(0, (TERMX-VIEW_OFFSET_X*2)/2, TERMY-VIEW_OFFSET_Y*2, sItemLastCh, vItemLastCh, vItemCh
                              , -1, true);//without getch()
   compare_split_screen_popup((TERMX-VIEW_OFFSET_X*2)/2, (TERMX-VIEW_OFFSET_X*2)/2, TERMY-VIEW_OFFSET_Y*2, sItemCh, vItemCh, vItemLastCh);

   wclear(w_inv);
   print_inv_statics(w_inv, "Compare:", dropped_armor, dropped_weapon);
   bShowCompare = false;
  }
 } while (ch != '\n' && ch != KEY_ESCAPE && ch != ' ');
 werase(w_inv);
 delwin(w_inv);
 erase();
 refresh_all();
}
main()
{
clrscr();
 int a[4][3],b[4][3],r,c,sub[4][3];


    //FETCHING the Matrix

 for(r=0;r<4;r++)
  {
   cout<<"\nEnter the values in first matrice for row "<<r+1<<endl;
   for(c=0;c<3;c++)
    {
     cout<<"Enter value for column "<<c+1<<" ";
     cin>>a[r][c];
    }
   cout<<"------------------------------------";
  }
clrscr();
 for(r=0;r<4;r++)
  {
   cout<<"\nEnter the values in second matrix for row "<<r+1<<endl;
   for(c=0;c<3;c++)
    {
     cout<<"Enter value for column "<<c+1<<" ";
     cin>>b[r][c];
    }
   cout<<"------------------------------------";
  }
clrscr();


  //Printing first Matrix

 cout<<"\n Matrix 1 entered is "<<endl<<endl;
  for(int j=0;j<4;j++)
   {
    for(int k=0;k<1;k++)
      cout<<a[j][k]<<'\t'<<a[j][1]<<'\t'<<a[j][2]<<endl;
   }


  //Printing second matrix

  cout<<"\n Matrix 2 entered is "<<endl<<endl;
  for(int l=0;l<4;l++)
   {
    for(int m=0;m<1;m++)
      cout<<b[l][0]<<'\t'<<b[l][1]<<'\t'<<b[l][2]<<endl;
   }

 //SUBTRACTING THE MATRIX

 for(r=0,l=0;r<4;r++)
  {
   for(c=0;c<3;c++)
    {
     sub[r][c]=a[r][c]-b[r][c];
    }
  }

  //PRINTING RESULT

 cout<<"\n The subtraction of the two is "<<endl<<endl;
  for(l=0;l<4;l++)
   {
    for(int m=0;m<1;m++)
      cout<<sub[l][0]<<'\t'<<sub[l][1]<<'\t'<<sub[l][2]<<endl;
   }

getch();
}
示例#20
0
void main () {
	
	int n;										// ler quantidade n de elementos
	printf ("Entre com o valor de pontos a ser digitado em seguida, os pontos do seu vetor.\n\n");
	scanf ("%d",&n);
	
	if(n<2){									//teste para valor abaixo de 2
		printf("\nErro! Reinicie o programa e insira um valor maior que 1.\n");
	}
	
	if (n>1){									//condicao para necessitar do algoritmo
	
		int *x,*y,*ch;							// alocando memória para as 3 variaveis de um elemento
		x = (int*)malloc(n*sizeof(int));		// x é a coordenada horizontal		
		y = (int*)malloc(n*sizeof(int));		// y é a coordenada vertical
		ch = (int*)calloc(n,sizeof(int));		//ch é o vetor que armazena se o ponto pertence ou não ao fecho convexo, valor inicial para todos=0
		
		int i;									//lendo os n elementos
		for(i=0;i<n;i++){
			scanf("%d",&x[i]);
			scanf("%d",&y[i]);
		}
			
		quicksort2(x,y,0,n-1);					//ordenando o vetor em x com quick sort
		
		int j=0;								//ordenar y quando x for igual
		for(i=0;i<n-1;i++){
			if(x[i]==x[i+1]){ 					//localiza blocos onde varios elemntos possuem o mesmo valor de x
				j++;
				if(i+1==n-1){
					quicksort(y,i-j+1,i+1);		
					j=0;
				}
			}
			if(x[i]!=x[i+1]){
				quicksort(y,i-j,i);				//ordena os valores de y dentro do bloco de valores iguais para x
				j=0;
			}
		}
				
		int poscos;						//pegando o ponto inicial, usaremos o maior angulo para localizar o proximo ponto
		float cosm;						//quando um angulo está no intervalo [0,180], quanto maior ele for, menor sera seu cosseno
										//poscos = posicão do cosseno buscado, cosm=valor do cosseno buscado
		i=0;
		while(i<n-1){
			cosm=1.0;
			poscos=i;
			for(j=i+1;j<n;j++){
				if(cosseno(x,y,i,j)<=cosm){		//nesse caso buscamos o menor cosseno
					cosm=cosseno(x,y,i,j);
					poscos=j;
				}				
			}
			ch[poscos]=1;				//quando um ponto pertence ao fecho, seu ch é mudado de zero para um
			i=poscos;
			
		}								//a primeira parte gera a parte inferior do fecho entre o primeiro e o ultimo ponto
		
		i=n-1;
		while(i>0){
			cosm=-1.0;					//partindo agora do ultimo, buscamos fechar a parte superior
			poscos=i;
			for(j=i-1;j>=0;j--){
				if(cosseno(x,y,i,j)>=cosm){		//como mantemos o vetor comparacao para cima, mas estamos voltando, buscamos o menor angulo, ou seja, o maior cosseno
					cosm=cosseno(x,y,i,j);
					poscos=j;
				}				
			}
			ch[poscos]=1;				//pontos do fecho recebem ch=1
			i=poscos;
			
		}
		
		int k;							//essa parte remove alguns pontos colineares que não foram removidos na parte superior
		for(i=0;i<n;i++){
			if(ch[i]==1){				//pega apenas pontos do fecho
				for(j=0;j<n;j++){
					if(j!=i && ch[j]==1){
						for(k=0;k<n;k++){
							if(ch[k]==1 && k!=i && k!=j && cosseno(x,y,i,j)==-cosseno(x,y,i,k)){ 		//analisa se existem dois cossenos opostos,o que pode significar colinearidade
								if(y[j]>=y[i] && y[k]<=y[i] && x[j]>=x[i] && x[k]<=x[i]){				//analisando por quadrantes, podemos definir se esses angulos são ou não de colineares
									ch[i]=0;
								}
								if(y[j]>=y[i] && y[k]<=y[i] && x[j]<=x[i] && x[k]>=x[i]){
									ch[i]=0;
								}
								if(y[j]<=y[i] && y[k]>=y[i] && x[j]>=x[i] && x[k]<=x[i]){
									ch[i]=0;
								}
								if(y[j]<=y[i] && y[k]>=y[i] && x[j]<=x[i] && x[k]>=x[i]){
									ch[i]=0;
								}
							}
						}
					}
				}
			}
		}
		
		
		printf("\nVertices do fecho convexo:\n\n");
		for(i=0;i<n;i++){						//imprime os pontos do fecho convexo, ou seja, pontos com ch=1
			if(ch[i]==1){
				printf("%d %d\n",x[i],y[i]);
			}
		}
		
		
		free(x);
		free(y);	
		free(ch);							//liberando a memória utilizada
	}
	getch();
}
示例#21
0
//
// Scanner used to tokenize source stream.
//
// N.B. Invalid numeric suffixes are not consumed.//
// This is technically not correct, as the preprocessor should just
// accept the numeric literal along with whatever suffix it has, but
// currently, it stops on seeing a bad suffix, treating that as the
// next token. This effects things like token pasting, where it is
// relevant how many tokens something was broken into.
// See peekContinuedPasting().
//
int TPpContext::tStringInput::scan(TPpToken* ppToken)
{
    int AlreadyComplained = 0;
    int len = 0;
    int ch = 0;
    int ii = 0;
    unsigned long long ival = 0;
    const auto floatingPointChar = [&](int ch) { return ch == '.' || ch == 'e' || ch == 'E' ||
                                                                     ch == 'f' || ch == 'F' ||
                                                                     ch == 'h' || ch == 'H'; };

    static const char* const Int64_Extensions[] = {
        E_GL_ARB_gpu_shader_int64,
        E_GL_EXT_shader_explicit_arithmetic_types,
        E_GL_EXT_shader_explicit_arithmetic_types_int64 };
    static const int Num_Int64_Extensions = sizeof(Int64_Extensions) / sizeof(Int64_Extensions[0]);

    static const char* const Int16_Extensions[] = {
#ifdef AMD_EXTENSIONS
        E_GL_AMD_gpu_shader_int16,
#endif
        E_GL_EXT_shader_explicit_arithmetic_types,
        E_GL_EXT_shader_explicit_arithmetic_types_int16 };
    static const int Num_Int16_Extensions = sizeof(Int16_Extensions) / sizeof(Int16_Extensions[0]);

    ppToken->ival = 0;
    ppToken->i64val = 0;
    ppToken->space = false;
    ch = getch();
    for (;;) {
        while (ch == ' ' || ch == '\t') {
            ppToken->space = true;
            ch = getch();
        }

        ppToken->loc = pp->parseContext.getCurrentLoc();
        len = 0;
        switch (ch) {
        default:
            // Single character token, including EndOfInput, '#' and '\' (escaped newlines are handled at a lower level, so this is just a '\' token)
            if (ch > PpAtomMaxSingle)
                ch = PpAtomBadToken;
            return ch;

        case 'A': case 'B': case 'C': case 'D': case 'E':
        case 'F': case 'G': case 'H': case 'I': case 'J':
        case 'K': case 'L': case 'M': case 'N': case 'O':
        case 'P': case 'Q': case 'R': case 'S': case 'T':
        case 'U': case 'V': case 'W': case 'X': case 'Y':
        case 'Z': case '_':
        case 'a': case 'b': case 'c': case 'd': case 'e':
        case 'f': case 'g': case 'h': case 'i': case 'j':
        case 'k': case 'l': case 'm': case 'n': case 'o':
        case 'p': case 'q': case 'r': case 's': case 't':
        case 'u': case 'v': case 'w': case 'x': case 'y':
        case 'z':
            do {
                if (len < MaxTokenLength) {
                    ppToken->name[len++] = (char)ch;
                    ch = getch();
                } else {
                    if (! AlreadyComplained) {
                        pp->parseContext.ppError(ppToken->loc, "name too long", "", "");
                        AlreadyComplained = 1;
                    }
                    ch = getch();
                }
            } while ((ch >= 'a' && ch <= 'z') ||
                     (ch >= 'A' && ch <= 'Z') ||
                     (ch >= '0' && ch <= '9') ||
                     ch == '_');

            // line continuation with no token before or after makes len == 0, and need to start over skipping white space, etc.
            if (len == 0)
                continue;

            ppToken->name[len] = '\0';
            ungetch();
            return PpAtomIdentifier;
        case '0':
            ppToken->name[len++] = (char)ch;
            ch = getch();
            if (ch == 'x' || ch == 'X') {
                // must be hexadecimal

                bool isUnsigned = false;
                bool isInt64 = false;
                bool isInt16 = false;
                ppToken->name[len++] = (char)ch;
                ch = getch();
                if ((ch >= '0' && ch <= '9') ||
                    (ch >= 'A' && ch <= 'F') ||
                    (ch >= 'a' && ch <= 'f')) {

                    ival = 0;
                    do {
                        if (len < MaxTokenLength && ival <= 0x0fffffffffffffffull) {
                            ppToken->name[len++] = (char)ch;
                            if (ch >= '0' && ch <= '9') {
                                ii = ch - '0';
                            } else if (ch >= 'A' && ch <= 'F') {
                                ii = ch - 'A' + 10;
                            } else if (ch >= 'a' && ch <= 'f') {
                                ii = ch - 'a' + 10;
                            } else
                                pp->parseContext.ppError(ppToken->loc, "bad digit in hexadecimal literal", "", "");
                            ival = (ival << 4) | ii;
                        } else {
                            if (! AlreadyComplained) {
                                if(len < MaxTokenLength)
                                    pp->parseContext.ppError(ppToken->loc, "hexadecimal literal too big", "", "");
                                else
                                    pp->parseContext.ppError(ppToken->loc, "hexadecimal literal too long", "", "");
                                AlreadyComplained = 1;
                            }
                            ival = 0xffffffffffffffffull;
                        }
                        ch = getch();
                    } while ((ch >= '0' && ch <= '9') ||
                             (ch >= 'A' && ch <= 'F') ||
                             (ch >= 'a' && ch <= 'f'));
                } else {
                    pp->parseContext.ppError(ppToken->loc, "bad digit in hexadecimal literal", "", "");
                }
                if (ch == 'u' || ch == 'U') {
                    if (len < MaxTokenLength)
                        ppToken->name[len++] = (char)ch;
                    isUnsigned = true;

                    int nextCh = getch();
                    if (nextCh == 'l' || nextCh == 'L') {
                        if (len < MaxTokenLength)
                            ppToken->name[len++] = (char)nextCh;
                        isInt64 = true;
                    } else
                        ungetch();

#ifdef AMD_EXTENSIONS
                    nextCh = getch();
                    if ((nextCh == 's' || nextCh == 'S') &&
                            pp->parseContext.intermediate.getSource() == EShSourceGlsl) {
                        if (len < MaxTokenLength)
                            ppToken->name[len++] = (char)nextCh;
                        isInt16 = true;
                    } else
                        ungetch();
#endif
                } else if (ch == 'l' || ch == 'L') {
                    if (len < MaxTokenLength)
                        ppToken->name[len++] = (char)ch;
                    isInt64 = true;
#ifdef AMD_EXTENSIONS
                } else if ((ch == 's' || ch == 'S') &&
                           pp->parseContext.intermediate.getSource() == EShSourceGlsl) {
                    if (len < MaxTokenLength)
                        ppToken->name[len++] = (char)ch;
                    isInt16 = true;
#endif
                } else
                    ungetch();
                ppToken->name[len] = '\0';

                if (isInt64 && pp->parseContext.intermediate.getSource() == EShSourceGlsl) {
                    if (pp->ifdepth == 0) {
                        pp->parseContext.requireProfile(ppToken->loc, ~EEsProfile,
                                                        "64-bit hexadecimal literal");
                        pp->parseContext.profileRequires(ppToken->loc, ~EEsProfile, 0,
                            Num_Int64_Extensions, Int64_Extensions, "64-bit hexadecimal literal");
                    }
                    ppToken->i64val = ival;
                    return isUnsigned ? PpAtomConstUint64 : PpAtomConstInt64;
                } else if (isInt16) {
                    if (pp->ifdepth == 0) {
                        if (pp->parseContext.intermediate.getSource() == EShSourceGlsl) {
                            pp->parseContext.requireProfile(ppToken->loc, ~EEsProfile,
                                                             "16-bit hexadecimal literal");
                            pp->parseContext.profileRequires(ppToken->loc, ~EEsProfile, 0,
                                Num_Int16_Extensions, Int16_Extensions, "16-bit hexadecimal literal");
                        }
                    }
                    ppToken->ival = (int)ival;
                    return isUnsigned ? PpAtomConstUint16 : PpAtomConstInt16;
                } else {
                    if (ival > 0xffffffffu && !AlreadyComplained)
                        pp->parseContext.ppError(ppToken->loc, "hexadecimal literal too big", "", "");
                    ppToken->ival = (int)ival;
                    return isUnsigned ? PpAtomConstUint : PpAtomConstInt;
                }
            } else {
                // could be octal integer or floating point, speculative pursue octal until it must be floating point

                bool isUnsigned = false;
                bool isInt64 = false;
                bool isInt16 = false;
                bool octalOverflow = false;
                bool nonOctal = false;
                ival = 0;

                // see how much octal-like stuff we can read
                while (ch >= '0' && ch <= '7') {
                    if (len < MaxTokenLength)
                        ppToken->name[len++] = (char)ch;
                    else if (! AlreadyComplained) {
                        pp->parseContext.ppError(ppToken->loc, "numeric literal too long", "", "");
                        AlreadyComplained = 1;
                    }
                    if (ival <= 0x1fffffffffffffffull) {
                        ii = ch - '0';
                        ival = (ival << 3) | ii;
                    } else
                        octalOverflow = true;
                    ch = getch();
                }

                // could be part of a float...
                if (ch == '8' || ch == '9') {
                    nonOctal = true;
                    do {
                        if (len < MaxTokenLength)
                            ppToken->name[len++] = (char)ch;
                        else if (! AlreadyComplained) {
                            pp->parseContext.ppError(ppToken->loc, "numeric literal too long", "", "");
                            AlreadyComplained = 1;
                        }
                        ch = getch();
                    } while (ch >= '0' && ch <= '9');
                }
                if (floatingPointChar(ch))
                    return pp->lFloatConst(len, ch, ppToken);

                // wasn't a float, so must be octal...
                if (nonOctal)
                    pp->parseContext.ppError(ppToken->loc, "octal literal digit too large", "", "");

                if (ch == 'u' || ch == 'U') {
                    if (len < MaxTokenLength)
                        ppToken->name[len++] = (char)ch;
                    isUnsigned = true;

                    int nextCh = getch();
                    if (nextCh == 'l' || nextCh == 'L') {
                        if (len < MaxTokenLength)
                            ppToken->name[len++] = (char)nextCh;
                        isInt64 = true;
                    } else
                        ungetch();

#ifdef AMD_EXTENSIONS
                    nextCh = getch();
                    if ((nextCh == 's' || nextCh == 'S') && 
                                pp->parseContext.intermediate.getSource() == EShSourceGlsl) {
                        if (len < MaxTokenLength)
                            ppToken->name[len++] = (char)nextCh;
                        isInt16 = true;
                    } else
                        ungetch();
#endif
                } else if (ch == 'l' || ch == 'L') {
                    if (len < MaxTokenLength)
                        ppToken->name[len++] = (char)ch;
                    isInt64 = true;
#ifdef AMD_EXTENSIONS
                } else if ((ch == 's' || ch == 'S') && 
                                pp->parseContext.intermediate.getSource() == EShSourceGlsl) {
                    if (len < MaxTokenLength)
                        ppToken->name[len++] = (char)ch;
                    isInt16 = true;
#endif
                } else
                    ungetch();
                ppToken->name[len] = '\0';

                if (!isInt64 && ival > 0xffffffffu)
                    octalOverflow = true;

                if (octalOverflow)
                    pp->parseContext.ppError(ppToken->loc, "octal literal too big", "", "");

                if (isInt64 && pp->parseContext.intermediate.getSource() == EShSourceGlsl) {
                    if (pp->ifdepth == 0) {
                        pp->parseContext.requireProfile(ppToken->loc, ~EEsProfile,
                                                        "64-bit octal literal");
                        pp->parseContext.profileRequires(ppToken->loc, ~EEsProfile, 0,
                            Num_Int64_Extensions, Int64_Extensions, "64-bit octal literal");
                    }
                    ppToken->i64val = ival;
                    return isUnsigned ? PpAtomConstUint64 : PpAtomConstInt64;
                } else if (isInt16) {
                    if (pp->ifdepth == 0) {
                        if (pp->parseContext.intermediate.getSource() == EShSourceGlsl) {
                            pp->parseContext.requireProfile(ppToken->loc, ~EEsProfile,
                                                            "16-bit octal literal");
                            pp->parseContext.profileRequires(ppToken->loc, ~EEsProfile, 0,
                                Num_Int16_Extensions, Int16_Extensions, "16-bit octal literal");
                        }
                    }
                    ppToken->ival = (int)ival;
                    return isUnsigned ? PpAtomConstUint16 : PpAtomConstInt16;
                } else {
                    ppToken->ival = (int)ival;
                    return isUnsigned ? PpAtomConstUint : PpAtomConstInt;
                }
            }
            break;
        case '1': case '2': case '3': case '4':
        case '5': case '6': case '7': case '8': case '9':
            // can't be hexadecimal or octal, is either decimal or floating point

            do {
                if (len < MaxTokenLength)
                    ppToken->name[len++] = (char)ch;
                else if (! AlreadyComplained) {
                    pp->parseContext.ppError(ppToken->loc, "numeric literal too long", "", "");
                    AlreadyComplained = 1;
                }
                ch = getch();
            } while (ch >= '0' && ch <= '9');
            if (floatingPointChar(ch))
                return pp->lFloatConst(len, ch, ppToken);
            else {
                // Finish handling signed and unsigned integers
                int numericLen = len;
                bool isUnsigned = false;
                bool isInt64 = false;
                bool isInt16 = false;
                if (ch == 'u' || ch == 'U') {
                    if (len < MaxTokenLength)
                        ppToken->name[len++] = (char)ch;
                    isUnsigned = true;

                    int nextCh = getch();
                    if (nextCh == 'l' || nextCh == 'L') {
                        if (len < MaxTokenLength)
                            ppToken->name[len++] = (char)nextCh;
                        isInt64 = true;
                    } else
                        ungetch();

#ifdef AMD_EXTENSIONS
                    nextCh = getch();
                    if ((nextCh == 's' || nextCh == 'S') &&
                                pp->parseContext.intermediate.getSource() == EShSourceGlsl) {
                        if (len < MaxTokenLength)
                            ppToken->name[len++] = (char)nextCh;
                        isInt16 = true;
                    } else
                        ungetch();
#endif
                } else if (ch == 'l' || ch == 'L') {
                    if (len < MaxTokenLength)
                        ppToken->name[len++] = (char)ch;
                    isInt64 = true;
#ifdef AMD_EXTENSIONS
                } else if ((ch == 's' || ch == 'S') &&
                                pp->parseContext.intermediate.getSource() == EShSourceGlsl) {
                    if (len < MaxTokenLength)
                        ppToken->name[len++] = (char)ch;
                    isInt16 = true;
#endif
                } else
                    ungetch();

                ppToken->name[len] = '\0';
                ival = 0;
                const unsigned oneTenthMaxInt  = 0xFFFFFFFFu / 10;
                const unsigned remainderMaxInt = 0xFFFFFFFFu - 10 * oneTenthMaxInt;
                const unsigned long long oneTenthMaxInt64  = 0xFFFFFFFFFFFFFFFFull / 10;
                const unsigned long long remainderMaxInt64 = 0xFFFFFFFFFFFFFFFFull - 10 * oneTenthMaxInt64;
                const unsigned short oneTenthMaxInt16  = 0xFFFFu / 10;
                const unsigned short remainderMaxInt16 = 0xFFFFu - 10 * oneTenthMaxInt16;
                for (int i = 0; i < numericLen; i++) {
                    ch = ppToken->name[i] - '0';
                    bool overflow = false;
                    if (isInt64)
                        overflow = (ival > oneTenthMaxInt64 || (ival == oneTenthMaxInt64 && (unsigned long long)ch > remainderMaxInt64));
                    else if (isInt16)
                        overflow = (ival > oneTenthMaxInt16 || (ival == oneTenthMaxInt16 && (unsigned short)ch > remainderMaxInt16));
                    else
                        overflow = (ival > oneTenthMaxInt || (ival == oneTenthMaxInt && (unsigned)ch > remainderMaxInt));
                    if (overflow) {
                        pp->parseContext.ppError(ppToken->loc, "numeric literal too big", "", "");
                        ival = 0xFFFFFFFFFFFFFFFFull;
                        break;
                    } else
                        ival = ival * 10 + ch;
                }

                if (isInt64 && pp->parseContext.intermediate.getSource() == EShSourceGlsl) {
                    if (pp->ifdepth == 0) {
                        pp->parseContext.requireProfile(ppToken->loc, ~EEsProfile,
                                                        "64-bit literal");
                        pp->parseContext.profileRequires(ppToken->loc, ~EEsProfile, 0,
                            Num_Int64_Extensions, Int64_Extensions, "64-bit literal");
                    }
                    ppToken->i64val = ival;
                    return isUnsigned ? PpAtomConstUint64 : PpAtomConstInt64;
                } else if (isInt16) {
                    if (pp->ifdepth == 0 && pp->parseContext.intermediate.getSource() == EShSourceGlsl) {
                        pp->parseContext.requireProfile(ppToken->loc, ~EEsProfile,
                                                        "16-bit  literal");
                        pp->parseContext.profileRequires(ppToken->loc, ~EEsProfile, 0,
                            Num_Int16_Extensions, Int16_Extensions, "16-bit literal");
                    }
                    ppToken->ival = (int)ival;
                    return isUnsigned ? PpAtomConstUint16 : PpAtomConstInt16;
                } else {
                    ppToken->ival = (int)ival;
                    return isUnsigned ? PpAtomConstUint : PpAtomConstInt;
                }
            }
            break;
        case '-':
            ch = getch();
            if (ch == '-') {
                return PpAtomDecrement;
            } else if (ch == '=') {
                return PPAtomSubAssign;
            } else {
                ungetch();
                return '-';
            }
        case '+':
            ch = getch();
            if (ch == '+') {
                return PpAtomIncrement;
            } else if (ch == '=') {
                return PPAtomAddAssign;
            } else {
                ungetch();
                return '+';
            }
        case '*':
            ch = getch();
            if (ch == '=') {
                return PPAtomMulAssign;
            } else {
                ungetch();
                return '*';
            }
        case '%':
            ch = getch();
            if (ch == '=') {
                return PPAtomModAssign;
            } else {
                ungetch();
                return '%';
            }
        case '^':
            ch = getch();
            if (ch == '^') {
                return PpAtomXor;
            } else {
                if (ch == '=')
                    return PpAtomXorAssign;
                else{
                    ungetch();
                    return '^';
                }
            }

        case '=':
            ch = getch();
            if (ch == '=') {
                return PpAtomEQ;
            } else {
                ungetch();
                return '=';
            }
        case '!':
            ch = getch();
            if (ch == '=') {
                return PpAtomNE;
            } else {
                ungetch();
                return '!';
            }
        case '|':
            ch = getch();
            if (ch == '|') {
                return PpAtomOr;
            } else if (ch == '=') {
                return PpAtomOrAssign;
            } else {
                ungetch();
                return '|';
            }
        case '&':
            ch = getch();
            if (ch == '&') {
                return PpAtomAnd;
            } else if (ch == '=') {
                return PpAtomAndAssign;
            } else {
                ungetch();
                return '&';
            }
        case '<':
            ch = getch();
            if (ch == '<') {
                ch = getch();
                if (ch == '=')
                    return PpAtomLeftAssign;
                else {
                    ungetch();
                    return PpAtomLeft;
                }
            } else if (ch == '=') {
                return PpAtomLE;
            } else {
                ungetch();
                return '<';
            }
        case '>':
            ch = getch();
            if (ch == '>') {
                ch = getch();
                if (ch == '=')
                    return PpAtomRightAssign;
                else {
                    ungetch();
                    return PpAtomRight;
                }
            } else if (ch == '=') {
                return PpAtomGE;
            } else {
                ungetch();
                return '>';
            }
        case '.':
            ch = getch();
            if (ch >= '0' && ch <= '9') {
                ungetch();
                return pp->lFloatConst(0, '.', ppToken);
            } else {
                ungetch();
                return '.';
            }
        case '/':
            ch = getch();
            if (ch == '/') {
                pp->inComment = true;
                do {
                    ch = getch();
                } while (ch != '\n' && ch != EndOfInput);
                ppToken->space = true;
                pp->inComment = false;

                return ch;
            } else if (ch == '*') {
                ch = getch();
                do {
                    while (ch != '*') {
                        if (ch == EndOfInput) {
                            pp->parseContext.ppError(ppToken->loc, "End of input in comment", "comment", "");
                            return ch;
                        }
                        ch = getch();
                    }
                    ch = getch();
                    if (ch == EndOfInput) {
                        pp->parseContext.ppError(ppToken->loc, "End of input in comment", "comment", "");
                        return ch;
                    }
                } while (ch != '/');
                ppToken->space = true;
                // loop again to get the next token...
                break;
            } else if (ch == '=') {
                return PPAtomDivAssign;
            } else {
                ungetch();
                return '/';
            }
            break;
        case '\'':
            return pp->characterLiteral(ppToken);
        case '"':
            // TODO: If this gets enhanced to handle escape sequences, or
            // anything that is different than what #include needs, then
            // #include needs to use scanHeaderName() for this.
            ch = getch();
            while (ch != '"' && ch != '\n' && ch != EndOfInput) {
                if (len < MaxTokenLength) {
                    ppToken->name[len] = (char)ch;
                    len++;
                    ch = getch();
                } else
                    break;
            };
            ppToken->name[len] = '\0';
            if (ch != '"') {
                ungetch();
                pp->parseContext.ppError(ppToken->loc, "End of line in string", "string", "");
            }
            return PpAtomConstString;
        case ':':
            ch = getch();
            if (ch == ':')
                return PpAtomColonColon;
            ungetch();
            return ':';
        }

        ch = getch();
    }
}
示例#22
0
int main(int argc, char* argv[])
{
	int is_running = 1;
	int x_terminal_size, y_terminal_size;

	memset(client_buffer, '\0', sizeof(client_buffer));
	get_terminal_size(&x_terminal_size, &y_terminal_size);
	
	initscr();
	raw();
	keypad(stdscr, TRUE);
	noecho();

	transcript_window  = newwin(23,40,0,0);
	client_chat_window = newwin(MAX_ROWS,MAX_COLUMNS,20,40);

	write_to_transcript_window("Hello!\n");
	write_to_transcript_window("Hey all!\nI love BlackChat, it's so awesome!\n");
	write_to_transcript_window("Press the \'q\' key to quit!");

	while(is_running) {
		int ch = getch();
		switch(ch) {
			case 'q': 
				is_running = 0;
				break;

			/* Scroll the clients typing window down. */
			case KEY_DOWN:
				client_current_line ++;
				if(client_current_line*MAX_COLUMNS > strlen(client_buffer)) client_current_line --;

				wclear(client_chat_window);
				wprintw(client_chat_window, &client_buffer[client_current_line*MAX_COLUMNS]);
				break;
			/* Scroll the clients typing window up. */
			case KEY_UP:
				client_current_line --;
				if(client_current_line < 0) client_current_line = 0;

				wclear(client_chat_window);
				wprintw(client_chat_window, &client_buffer[client_current_line*MAX_COLUMNS]);
				break;
		
			/* Delete the previous chracter. */
			case KEY_BACKSPACE:
				client_buffer[ strlen(client_buffer)-1 ] = '\0';
				print_client_chat_buffer();
				break;

			/* If were here, that means we didn't press any "special" keys so that means were
			 * trying to write some generic characters to our chat window. */
			default:
				/* Store the new char in our buffer. */
				client_buffer[ strlen(client_buffer) ] = ch;
				
				/* Print our new chat buffer. */
				print_client_chat_buffer();
				break;
		}

		wrefresh(transcript_window);
		wrefresh(client_chat_window);
	}

	delwin(transcript_window);
	delwin(client_chat_window);
	endwin();

	return 0;
}
示例#23
0
int wait_char() {
	timeout( -1 );
	int result = getch();
	timeout( 0 );
	return result;
}
示例#24
0
booleano Messaggio(char * messaggio, booleano conferma)
{
    char c, *temp;
    int i,x,y;

    Stampa_Cornice_Piccola(ME_COLOR);
    Cambia_Colore(DEF_COLOR,ME_COLOR-8);
    //se è un messaggio di conferma aggiungi " (s/n)"
    if (conferma)
    {
        temp = malloc (sizeof(char)*(strlen(messaggio)+strlen(" (s/n)")));
        strcpy(temp,messaggio);
        strcat(temp," (s/n)");
    }
    else temp = messaggio;

    //stampa entro i bordi
    /* x indica la colonna in cui si sta scrivendo
       y indica la riga in cui si sta scrivendo   */
    y=0;
    x=0;
    gotoxy(MEX_X,MEX_Y+(y++));
    for (i=0; i<strlen(temp); i++)
    {
        /*se il contatore ha raggiunto un multiplo della larghezza dello
          schermo si va a capo, a meno che il carattere letto al momento
          non sia di newline */
        if (x==MEX_WIDTH && temp[i]!='\n')
        {
            gotoxy(MEX_X,MEX_Y+(y++));
            x=0;
        }
        //si va a capo in caso di newline
        if (temp[i]=='\n')
        {
            gotoxy(MEX_X,MEX_Y+(y++));
            x=0;
        }
        //altrimenti si stampa il carattere
        else
        {
            putchar(temp[i]);
            x++;
        }
    }

    //attendi l'utente
    if (conferma)
    {
        while (c!='s' && c!='S' && c!='n' && c!='N' && c!=ESC)
        {
            c=getch();
        }
    }
    else getch();

    //resetta colori default
    Cambia_Colore(DEF_COLOR,DEF_BACK_COLOR);
    //libera spazio
    free(temp);

    if (c=='s' || c=='S') return true;
    else return false;
}
示例#25
0
void print_cards(char language)
{
char list = 'a', response_gl;

if(language == 'e')
 while(response_gl != 'c')
 {

 if(list == 'a')
 {
  //window(1,11,80,24);
 // clrscr();
  printf("1.  Ambivalence                      20. Metamorphosis\n");
  printf("2.  Anthropomorphism                 21. Monetary Value\n");
  printf("3.  Art vs. Nature                   22. Myth\n");
  printf("4.  Fundamental Theorem of Calculus  23. Nature Tending\n");
  printf("5.  City as Artifact                       Towards Perfection\n");
printf("6.  Coding                           24. Ontogeny Recapitulating\n");
  printf("7.  Contemplation                          Phylogeny\n");
  printf("8   Creation                         25. Perspective\n");
  printf("9   Education                        26. Reaching out / Trying\n");
  printf("10  Emotional Manipulation           27. Return\n");
  printf("                       28. Society as active / Passive Hierarchy\n");
 }
 if(list == 'b')
 {
// window(1,11,80,24);
 clrscr();
 printf("11. Freedom                          29. Structural Strength\n");
printf("12. Gestalt                          30. Structured Improvisation\n");
 printf("13. Harmoney                         31. Struggle\n");
 printf("14. Struggle                         32. Synergy\n");
 printf("15. Hidden Potential                 33. Syntax\n");
 printf("16. Intuition                        34. Unwanted Relationships\n");
 printf("17. Joy                              35. Wavicle\n");
 printf("18. Magic\n");
 printf("19. Multiplicatio of Mechanical Advantage");
 printf("\n");
 }
 printf("\nChoose card? Toggle list? (c,t) ");
 response_gl = getch();
 clrscr();
 if(response_gl == 't')
    {

      if(list == 'a')
	 list = 'b';
      else
	 if(list == 'b')
	 list = 'a';
    }
  }   // endwhile in English
  //window(1,11,80,24);
  clrscr();
if(language == 'g')
 while(response_gl != 'c')
 {
  if(list == 'a')
  {
    // window(1,11,80,24);
     clrscr();
     printf("1.  Ambivalenz\n");
     printf("2.  Anthropomorphismus\n");
     printf("3.  Der Gegensatz von Kunst und Natur\n");
     printf("4.  Unerw�nschte Verbindung\n");
     printf("5.  Die Stadt als Kunstwerk\n");
     printf("6.  Coding\n");
     printf("7.  Kontemplation\n");
     printf("8.  Sch\"pfung\n");
     printf("9.  Ausbildung und Erziehung\n");
     printf("10. Manipulation von Gef�hlen\n");
  }
  if(list == 'b')
  {
  //   window(1,11,80,24);
     clrscr();
     printf("11. Freiheit\n");
     printf("12. Gestalt\n");
     printf("13. Harmonie\n");
     printf("14. Kampf\n");
     printf("15. Unentdeckte M\"glichkeiten\n");
     printf("16. Intuition\n");
     printf("17. Freude\n");
     printf("18. Magik\n");
     printf("19. Multiplikation des mechanishen Vorteils\n");
     printf("20. Metamorphosis\n");
  }
  if(list == 'c')
      {
  //    window(1,11,80,24);
      clrscr();
      printf("21. Geldwert\n");
      printf("22. Mythen\n");
      printf("23. Natur entwickelt sich zur Perfektion\n");
      printf("24. Ontogenie wiederholt Phylogenie\n");
      printf("25. Perspektive\n");
      printf("26. Sich Ausstrecken\n");
      printf("27. R�ckkehr\n");
      printf("28.  (like 16)\n");
      printf("29. St�rke von Struktur\n");
      printf("30. Strukturelle Improvisation\n");
      }
   if(list == 'd')
      {
  //    window(1,11,80,24);
      clrscr();
      printf("31.  (like some other card)\n");
      printf("32. Synergetik\n");
      printf("33. Syntax\n");
      printf("34.  (like 4)\n");
      printf("35. Welle-Teilchen Dualismus\n");
      }
   printf("\nChoose card? Toggle list? (c,t) ");
   response_gl = getch();
   clrscr();
   if(response_gl == 't')
      {
	switch(list)
	{
	  case 'a' :
	  {
	    list = 'b';
	    break;
	  }
	  case 'b' :
	  {
	    list = 'c';
	    break;
	  }
	  case 'c' :
	  {
	    list = 'd';
	    break;
	  }
	  case 'd' :
	  {
	    list = 'a';
	    break;
	  }
	}
      }  /*  endif toggle  */
  }  /*  endwhile in German */
//  window(1,11,80,24);
  clrscr();
}
示例#26
0
int main(){
    char op;
    Lista* listaAlunos = NULL;
    Arvore* ArvoreCodigo = NULL;
    Arvore* ArvoreNome = NULL;
    Arvore* ArvoreMedia = NULL;

    ///*
    listaAlunos = addL(listaAlunos, 5, "ADeise\n", 8.2);
    listaAlunos = addL(listaAlunos, 1, "BMaria\n", 6.1);
    listaAlunos = addL(listaAlunos, 10, "DJoao\n", 4.9);
    listaAlunos = addL(listaAlunos, 12, "CPaulo\n", 5.8);


    do{
        system("cls");
        printf("Digite: \n");
        printf("1 - Adicionar alunos;\n");
        printf("2 - Remover alunos;\n");
        printf("3 - Mostrar lista de alunos;\n");
        printf("4 - Mostrar arvore ordenada por codigo;\n");
        printf("5 - Mostrar arvore ordenada por nome;\n");
        printf("6 - Mostrar arvore ordenada por media\n");
        printf("0 - Sair\n\n");
        op = getch();

        switch(op){
            case '1':
                listaAlunos = adicionar_aluno(listaAlunos);
            break;

            case '2':
                listaAlunos = remover_aluno(listaAlunos);
            break;

            case '3':
                printLista(listaAlunos);
            break;

            case '4':
                ArvoreCodigo = atualizarArvoreDeCodigo(ArvoreCodigo, listaAlunos);
                system("cls");
                printf("Arvore ordenada por codigo:\n\n\n");
                printArvore(ArvoreCodigo);
                system("pause");
            break;

            case '5':
                ArvoreNome = atualizarArvoreDeNome(ArvoreNome, listaAlunos);
                system("cls");
                printf("Arvore ordenada por nome:\n\n\n");
                printArvore(ArvoreNome);
                system("pause");
            break;

            case '6':
                ArvoreMedia = atualizarArvoreDeMedia(ArvoreMedia, listaAlunos);
                system("cls");
                printf("Arvore ordenada por media:\n\n\n");
                printArvore(ArvoreMedia);
                system("pause");
            break;

        }
    } while(op != '0');
    //*/
    return 0;
}
示例#27
0
/* getop - get next operator or numeric operand 
 *
 *    numbers and operators are separated by white space:
 *        2 3 + 3.4 5.3 * %
 *
 *    numbers may be prefixed by an optional plus or minus sign:
 *        -2.34 7.1 / +23.1 -3 - *
 *
 *    operators are followed by a white space character
 *        standard --> + - * / %
 *           stack --> ! (clear)  @ (swap)  # (duplicate)  & (print)
 *            math --> S (sin) C (cos) T (tan)  X (exp) L (log10) 
 *                     E (log) R (sqrt) P (pow)
 *    
 *    variables a-z and $ for last printed value
 */
int getop(char s[])
{
    int i, c;
    static int cb = -1;    /* char buffer persists between calls */

    if (cb > 0 && cb != ' ' && cb != '\t')
    {
        s[0] = c = cb;
        cb = -1;
    }
    else
    {

        /* skip space and horizontal tabs 
         */
        while ((s[0] = c = getch()) == ' ' || c == '\t')  
            ;
    }

    if (c == '-' || c == '+')
    {
        /* need to decide if the plus or minus specifies
         * the sign of a number or is itself an operator
         */
        s[1] = c = getch();             /* get next char */
        if (isdigit(c))                 /* is a sign */
        {
            s[2] = '\0';                    /* terminate string */
            i = 1;                          /* prep index into s */
        }
        else
        {
            cb = c;                         /* store it for next time */
            c = s[0];                       /* must be an operator */
            s[1] = '\0';                    /* terminate string */
            i = 0;                          /* prep index into s */
        }
    }
    else
    {
        s[1] = '\0';                    /* terminate string */
        i = 0;                          /* prep index into s */
    }

    if (!isdigit(c) && c != '.')        /* not a number or period */
        return c;                       /* must be an operator or variable */

    /* collect integer part 
     */    
    if (isdigit(c))
        while (isdigit(s[++i] = c = getch()))
            ;
    /* collect fraction part 
     */    
    if (c == '.')
        while (isdigit(s[++i] = c = getch()))
            ;
    s[i] = '\0';                        /* terminate string */
    if (c != EOF)
        cb = c;
    return NUMBER;
}
示例#28
0
int _tmain(int argc, _TCHAR* argv[])
{
	system("title LABIRINTiT 1x - PRODUÇÃO - RODRIGO MARTINS ! FELIPE MASIOLI");
	int tecla,variado;
	int result;
	char mapa_a[10][40], jogador[100];
    int i, j,pont=0;
	clock_t start, end;
    double elapsed;

	FILE *arquivo;
	srand(time(NULL));
	variado = random(0,3);
	
	arquivo = f_rand(variado);	

	printf("\n\n\t\tLABIRINTiT 1x");
	printf("\n\n\tQual o seu nome jogador???\n\t\t");
	scanf("%s", jogador);


	start = clock();      
	do{
		system(LIMPARTELA);

		//printf("\t\t\tLABIRINTiT 1x\n\n");

		/* Abre o arquivo */
		if(!arquivo)
		  {
			printf("Erro ao abrir arquivo!!!");
			exit(1);
		  }	
		/* Escreve a matriz no arquivo */
		for (i=0; i<10; i++)
		{
			for (j=0; j<40; j++)
			{
				fscanf(arquivo, "%d",&mapa_a[i][j]);
			}
		}
		mapa_a[linha_atual][coluna_atual] = nome;
		for(i=0;i<10;i++)
		{
			for(j=0;j<40;j++)
				printf("%c",mapa_a[i][j]);
			puts("");
		}
/* O Mapa */
        printf("\n##################### L A B I R I N T i T - 1x ################################\n");
        printf("\n\n    ( %c )\n\n( %c ) + ( %c )\n\n    ( %c )\n",30,17,16,31); /* Imprime as direcoes */
        printf("\nPressione ESC para sair\n");
        printf("\n------------------------------------------------------------------------------\n");

        tecla = getch();
		
        if ( tecla == ACIMA ) {
	     	  printf("%c",mapa_a[linha_atual][coluna_atual]);
		      mapa_a[linha_atual][coluna_atual]=0;
		      linha_atual = linha_atual - 1;
		      printf("%c",mapa_a[linha_atual][coluna_atual]);
          /* Se não for chao ou grama ele volta pra posicao anterior */
              if ((mapa_a[linha_atual][coluna_atual] != 0) && (mapa_a[linha_atual][coluna_atual] != 176) && (mapa_a[linha_atual][coluna_atual] != 4)) 
			  {
					linha_atual = linha_atual + 1;
		      }
        }
        if ( tecla == ABAIXO ) {
		      printf("%c",mapa_a[linha_atual][coluna_atual]);
		      mapa_a[linha_atual][coluna_atual]=0;
              linha_atual = linha_atual + 1;
          /* Se não for chao ou grama ou saida ele volta pra posicao anterior */
              if ((mapa_a[linha_atual][coluna_atual] != 0) && (mapa_a[linha_atual][coluna_atual] != 176) && (mapa_a[linha_atual][coluna_atual] != 4)) 
			  {
					linha_atual = linha_atual - 1;
			  }
        }
        if ( tecla == DIREITA ) {
              printf("%c",mapa_a[linha_atual][coluna_atual]);
              mapa_a[linha_atual][coluna_atual]=0;
              coluna_atual = coluna_atual + 1;
          /* Se não for chao ou grama ou saida ele volta pra posicao anterior */
              if ((mapa_a[linha_atual][coluna_atual] != 0) && (mapa_a[linha_atual][coluna_atual] != 176) && (mapa_a[linha_atual][coluna_atual] != 4)) 
			  {
					coluna_atual = coluna_atual - 1;
              }
        }
        if ( tecla == ESQUERDA ) {
              printf("%c",mapa_a[linha_atual][coluna_atual]);
              mapa_a[linha_atual][coluna_atual]=0;
              coluna_atual = coluna_atual - 1;
          /* Se não for chao ou grama ou saida ele volta pra posicao anterior */
              if ((mapa_a[linha_atual][coluna_atual] != 0) && (mapa_a[linha_atual][coluna_atual] != 176) && (mapa_a[linha_atual][coluna_atual] != 4)) 
			  {
					coluna_atual = coluna_atual + 1;
              }
        }
		if (mapa_a[linha_atual][coluna_atual] !=4 )
	    {
			pont++;
	    }
       
	}while(  (tecla != ESC) && (mapa_a[linha_atual][coluna_atual] != 4) );
	
	result = pont/2;
	end = clock(); 
	elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
		
	if (mapa_a[linha_atual][coluna_atual] == 4)
	{	
	    printf ("%s,\n",jogador);

			if (variado == 0)
			{
				if (result == 34)
				{
					printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed);
					printf("\t\tVoce foi excelente!!!\n");
					printf ("\t!!!!!!!!!!!!!!PARABENSSSSSSSSS!!!!!!!!!!!!!!\n\n");
				}
				if (result > 34)
				{
					printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed);
					printf("\tVoce prescisa melhorar!!!\n");
				}
			}
			if (variado == 1)
			{
				if (result == 51)
				{
					printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed);
					printf("\t\tVoce foi excelente!!!\n");
					printf ("\t!!!!!!!!!!!!!!PARABENSSSSSSSSS!!!!!!!!!!!!!!\n\n");
				}
				if (result > 51)
				{
					printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed);
					printf("\tVoce prescisa melhorar!!!\n");
				}
			}
			if (variado == 2)
			{
				if (result == 68)
				{
					printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed);
					printf("\t\tVoce foi excelente!!!\n");
					printf ("\t!!!!!!!!!!!!!!PARABENSSSSSSSSS!!!!!!!!!!!!!!\n\n");
				}
				if (result > 68)
				{
					printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed);
					printf("\tVoce prescisa melhorar!!!\n");
				}
			}
			if (variado == 3)
			{
				if (result == 71)
				{
					printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed);
					printf("\t\tVoce foi excelente!!!\n");
					printf ("\t!!!!!!!!!!!!!!PARABENSSSSSSSSS!!!!!!!!!!!!!!\n\n");
				}
				if (result > 71)
				{
					printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed);
					printf("\tVoce prescisa melhorar!!!\n");
				}
			}

		system("pause");
		system(acaba);
	}		

	fclose(arquivo);
	return 0;
}
示例#29
0
list_selection *do_selection(list_selection * sel, const char *title,
    void(*perform) (list_selection *, void *), void *data)
{
    WINDOW *wn;
    bool update = true;
    list_selection *s;
    list_selection *top = sel;
    list_selection *current = top;
    int i;
    int height = 0, width = (int)strlen(title) + 8;
    for (s = sel; s; s = s->next) {
        if ((int)strlen(s->str) > width) {
            width = (int)strlen(s->str);
        }
        ++height;
        log_debug("s %s w %d h %d\n", s->str, width, height);
    }
    if (height == 0 || width == 0)
        return 0;
    if (width + 3 > SX)
        width = SX - 4;
    if (height + 2 > SY)
        height = SY - 2;

    log_debug("w %d h %d\n", width, height);

    wn =
        newwin(height + 2, width + 4, (SY - height - 2) / 2, (SX - width - 4) / 2);

    for (;;) {
        int input;
        if (update) {
            for (s = top; s != NULL && top->index + height != s->index; s = s->next) {
                i = s->index - top->index;
                wmove(wn, i + 1, 4);
                waddnstr(wn, s->str, -1);
                wclrtoeol(wn);
            }
            wclrtobot(wn);
            wxborder(wn);
            mvwprintw(wn, 0, 2, "[ %s ]", title);
            update = false;
        }
        i = current->index - top->index;
        wattron(wn, A_BOLD | COLOR_PAIR(COLOR_YELLOW));
        wmove(wn, i + 1, 2);
        waddstr(wn, "->");
        wmove(wn, i + 1, 4);
        waddnstr(wn, current->str, width - 2);
        wattroff(wn, A_BOLD | COLOR_PAIR(COLOR_YELLOW));

        wrefresh(wn);

        input = getch();

        wmove(wn, i + 1, 2);
        waddstr(wn, "  ");
        wmove(wn, i + 1, 4);
        waddnstr(wn, current->str, width);

        switch (input) {
        case KEY_NPAGE:
            for (i = 0; i != height / 2; ++i) {
                if (current->next) {
                    current = current->next;
                    if (current->index - height >= top->index) {
                        top = current;
                        update = true;
                    }
                }
            }
            break;
        case KEY_PPAGE:
            for (i = 0; i != height / 2; ++i) {
                if (current->prev) {
                    if (current == top) {
                        top = sel;
                        while (top->index + height < current->index)
                            top = top->next;
                        update = true;
                    }
                    current = current->prev;
                }
            }
            break;
        case KEY_DOWN:
            if (current->next) {
                current = current->next;
                if (current->index - height >= top->index) {
                    top = current;
                    update = true;
                }
            }
            break;
        case KEY_UP:
            if (current->prev) {
                if (current == top) {
                    top = sel;
                    while (top->index + height < current->index)
                        top = top->next;
                    update = true;
                }
                current = current->prev;
            }
            break;
        case 27:
        case 'q':
            delwin(wn);
            return NULL;
        case 10:
        case 13:
            if (perform)
                perform(current, data);
            else {
                delwin(wn);
                return current;
            }
            break;
        default:
            s = current->next;
            if (s == NULL)
                s = top;
            while (s != current) {
                if (tolower(s->str[0]) == tolower(input)) {
                    current = s;
                    update = true;
                }
                else {
                    s = s->next;
                    if (s == NULL)
                        s = top;
                }
            }
            if (current->index - height >= top->index) {
                top = current;
                update = true;
            }
        }
    }
}
void main()
{
QUAT     q1={0,0,0,0}, 
         q1tmp={0,0,0,}, 
         q2={0,0,0,0}, 
         q2tmp={0,0,0,}, 
         qtmp={0,0,0,},  
         qv={0,0,0,}; // our working quaterions
VECTOR3D v={0,0,0}, vtmp;   // working vectors
POINT3D  p={0,0,0}, ptmp;   // working points
float theta;                // general angle

// open the error system, so we can see output
// notice the last parameter "stdout" this tell the error
// system that we don't want to write errors to a text file
// but straight out to the screen!
Open_Error_File("", stdout);


printf("\nQuaternion Lab");
printf("\nNote: the lab uses a number of variables to perform various operations");
printf("\nThey are quaterions q1,q2, and qtmp, along with the vector v.");
printf("\nMany operations will be stored in the temporary quaternion qtmp\n");

int sel;    // user selection
int done=0; // exit flag


// main loop
while(!done)
{
// draw menu
printf("\nQuaternion Lab Menu - (c) Alien Programmers Inc. - We're ready to invade you!");
printf("\n(1) Enter q1 in general format:  w1,x1,y1,z1?");
printf("\n(2) Enter in rotation quaterion and store in q1");
printf("\n(3) Enter q2 in general format:  w1,x1,y1,z1?");
printf("\n(4) Enter vector v in format:  x,y,z?");
printf("\n(5) Print q1");
printf("\n(6) Print q2");
printf("\n(7) Print qtmp");
printf("\n(8) Print v");
printf("\n(9) Add q1+q2, note result is stored in qtmp");
printf("\n(10) Subtract q1-q2, note result is stored in qtmp");
printf("\n(11) Normalize q1 (note alters q1)");
printf("\n(12) Normalize q2 (note alters q1)");
printf("\n(13) Compute conjugate of q1, note result is stored in qtmp");
printf("\n(14) Compute conjugate of q2, note result is stored in qtmp");
printf("\n(15) Compute inverse of q1, note result is stored in qtmp");
printf("\n(16) Compute inverse of q2, note result is stored in qtmp");
printf("\n(17) Multiply q1*q2, note result is stored in qtmp");
printf("\n(18) Multiply q2*q1, note result is stored in qtmp");
printf("\n(19) Compute triple product q1*vector*q1(-1) and store in qtmp, ");
printf("\nthis will rotate v assuming q1 is a unit rotation quaterion");
printf("\n(20) Clear All");
printf("\n(21) Exit");
printf("\nMake Selection and Press Enter?");
scanf("%d",&sel);


// what to do?
switch(sel)
      {
        case 1: // printf("\n(1) Enter q1 in general format:  w1,x1,y1,z1?");
        {
        printf("\nEnter q1 in general format:  w1,x1,y1,z1?");
        scanf("%f, %f, %f, %f", &q1.w, &q1.x, &q1.y, &q1.z);
    
        } break;

        case 2: // printf("\n(2) Enter in rotation quaterion and store in q1");
        {
        printf("\nEnter in direction vector v you wish to rotate about in form: x,y,z");
        printf("\n(system will normalize, so it need not have unit length)?");
        scanf("%f, %f, %f", &vtmp.x, &vtmp.y, &vtmp.z);

        printf("\nEnter in angle of rotation in degrees (0-360)?");
        scanf("%f",&theta);

        printf("\nGenerating rotation quaterion %f degree around vector (%f, %f, %f)...", 
                theta, vtmp.x, vtmp.y, vtmp.z);

        // normalize v
        VECTOR3D_Normalize(&vtmp);
        
        // compute quaterion
        VECTOR3D_Theta_To_QUAT(&q1, &vtmp, DEG_TO_RAD(theta));         

        QUAT_Print(&q1,"q1 in rotation format");

        } break;

        case 3: // printf("\n(3) Enter q2 in general format:  w1,x1,y1,z1?");
        {
        printf("\nEnter q2 in general format:  w1,x1,y1,z1?");
        scanf("%f, %f, %f, %f", &q2.w, &q2.x, &q2.y, &q2.z);
        } break;

        case 4: // printf("\n(4) Enter vector v in format:  x,y,z?");
        {
        printf("\nEnter vector v in format:  x,y,z?");
        scanf("%f, %f, %f", &v.x, &v.y, &v.z);
        } break;

        case 5: // printf("\n(5) Print q1");
        {
        QUAT_Print(&q1,"q1");
        } break;

        case 6: // printf("\n(6) Print q2");
        {
        QUAT_Print(&q2,"q2");
        } break;

        case 7: // printf("\n(7) Print qtmp");
        {
        QUAT_Print(&qtmp,"qtmp");
        } break;

        case 8: // printf("\n(8) Print v");
        {
        VECTOR3D_Print(&v,"v");
        } break;

        case 9: // printf("\n(9) Add q1+q2, note result is stored in qtmp");
        {
        QUAT_Add(&q1, &q2, &qtmp);
        QUAT_Print(&qtmp,"qtmp=q1+q2");
        } break;

        case 10: // printf("\n(10) Subtract q1-q2, note result is stored in qtmp");
        {
        QUAT_Sub(&q1, &q2, &qtmp);
        QUAT_Print(&qtmp,"qtmp=q1-q2");
        } break;

        case 11: // printf("\n(11) Normalize q1 (note alters q1)");
        {
        QUAT_Normalize(&q1);
        QUAT_Print(&q1,"q1");
        } break;

        case 12: // printf("\n(12) Normalize q2 (note alters q1)");
        {
        QUAT_Normalize(&q1);
        QUAT_Print(&q1,"q1");
        } break;

        case 13: // printf("\n(13) Compute conjugate of q1, note result is stored in qtmp");
        {
        QUAT_Conjugate(&q1, &qtmp);
        QUAT_Print(&qtmp,"qtmp = q1*");
        } break;

        case 14: // printf("\n(14) Compute conjugate of q2, note result is stored in qtmp");
        {
        QUAT_Conjugate(&q2, &qtmp);
        QUAT_Print(&qtmp,"qtmp = q2*");
        } break;

        case 15: // printf("\n(15) Compute inverse of q1, note result is stored in qtmp");
        {
        QUAT_Inverse(&q1, &qtmp);
        QUAT_Print(&qtmp,"qtmp = q1(-1)");
        } break;

        case 16: // printf("\n(16) Compute inverse of q2, note result is stored in qtmp");
        {
        QUAT_Inverse(&q2, &qtmp);
        QUAT_Print(&qtmp,"qtmp = q2(-1)");
        } break;

        case 17: // printf("\n(17) Multiply q1*q2, note result is stored in qtmp");
        {
        QUAT_Mul(&q1, &q2, &qtmp);
        QUAT_Print(&qtmp,"qtmp=q1 * q2");
        } break;

        case 18: // printf("\n(18) Multiply q2*q1, note result is stored in qtmp");
        {
        QUAT_Mul(&q2, &q1, &qtmp);
        QUAT_Print(&qtmp,"qtmp=q2 * q1");
        } break;

        case 19: // printf("\n(19) Compute triple product q1*vector*q1(-1) and store in qtmp, 
                 // this will rotate v assuming q1 is a unit rotation quaterion");
        {
        printf("\nComputing triple product...note q1 will be normalized if length <> 1");
        QUAT_Normalize(&q1);
        printf("\nAssuming q1 represents rotation quaternion, value is:");
        QUAT_Print(&q1,"q1");
        
        printf("\nVector v represent point or vector to be rotated, value is:");
        VECTOR3D_Print(&v,"v");
        printf("\nv after conversion to quaternion format is:");
 
        // vector must be converted to a quaternion
        QUAT_INIT_VECTOR3D(&qv, &v);
        QUAT_Print(&qv,"qv"); 

        // now perform triple product, but conjugate = inverse for unit quaterions
        // so all we need for inverse is to compute conjugate of q1
        QUAT_Conjugate(&q1, &q1tmp);

        // now perform triple multiply q1 * v(in q format) * q1(-1)
        // this will rotate v
        QUAT_Triple_Product(&q1, &qv, &q1tmp, &qtmp);
  
        printf("\nResulting quaternion after multiplication is v rotated which equals:");
        QUAT_Print(&qtmp,"v rotated in quaternion format");

        } break;
        case 20: // printf("\n(20) Clear All");
        {
        // simply clear all values
        VECTOR3D_ZERO(&v);
        QUAT_ZERO(&q1);
        QUAT_ZERO(&q2);
        QUAT_ZERO(&qtmp);
        } break;
        case 21: // printf("\n(21) Exit");
        {
        // set exit flag
        done=1;
        } break;

      default: break;

      } // end switch

printf("\nPress Spacebar to continue...");
getch();

} // end while

// close error system
Close_Error_File();

} // end main