bool interrupt_test(_WORD CardNr, string &ErrorMessage, bool ScreenOut, int loop)
{
	_DWORD Status	  = 0;
	_DWORD ErrorStatus = 0;
	_DWORD IntAktiv	  = 0;
	_WORD ErrorCounter = 0;

	_DWORD InMask; 
	_WORD myDta_Rdy = 0x2;
	_WORD myDta_Req = 0x4;

	_BYTE ErrorChar [24];

	string ausgabe;

	bool EVFifoNotEmpty = true;
	bool error = false;
	
	COORD coordScreen;

// -------------- Windows Version (NT oder 2000) ------------------

	OSVERSIONINFO lVerInfo;
	lVerInfo.dwOSVersionInfoSize = sizeof (lVerInfo);
	GetVersionEx (&lVerInfo);
	

// ----------------------------------------------------------------

	if(ScreenOut)
	{
		ClearScreen();
		InMask = 0x6; // Auf Dta_Rdy oder Dta_Req interrupten
	}
	else
	{
		InMask = 0x2; // Nur auf Dta_Rdy interrupten
	}

	PCI_PCIcardReset(CardNr, ErrorStatus);

	if(ScreenOut)
	{
		SetConsoleTextAttribute(hConsoleOut, BACKGROUND_BLUE | FOREGROUND_WHITE);   
		cout<<"Kleiner Interrupt Test auf Karten Nr.: "<<CardNr<<endl<<endl;
		SetConsoleTextAttribute(hConsoleOut, BACKGROUND_BLACK | FOREGROUND_WHITE);

		SetConsoleTextAttribute(hConsoleOut, BACKGROUND_RED | FOREGROUND_WHITE);   
		cout<<"Bitte einen Mil-Bus-Monitor mit der PCI-Mil-Karte verbinden.        "<<endl;
		cout<<"Mit den Tastern DRDY oder DREQ koennen interrupts ausgeloest werden."<<endl<<endl;

		SetConsoleTextAttribute(hConsoleOut, BACKGROUND_BLACK | FOREGROUND_WHITE);


		cout<<"Press Enter to go on...."<<endl;
		getchar();
		getchar();

		ClearScreen();
	}

	
	// Text Ausgabe
	// -------------
	if(ScreenOut)
	{
		SetConsoleTextAttribute(hConsoleOut, BACKGROUND_GREEN | FOREGROUND_RED);  
		cout<<"\nHinweis : Sollte der Rechner haengen bleiben, so koennte keine      "<<endl;

		coordScreen.X = 9;
		coordScreen.Y = 2;
		SetConsoleCursorPosition(hConsoleOut, coordScreen);
		
		cout<<" Verbindung zum Mil-Monitor da sein, ansonsten viel glueck."<<endl<<endl;
		SetConsoleTextAttribute(hConsoleOut, BACKGROUND_BLACK | FOREGROUND_WHITE);

		cout <<"Interrupts enabeln         :"<<endl;
		cout <<"Interrupt Maske definieren :"<<endl;
		cout <<"Wait interrupt             :"<<endl;
		cout <<"Interrupts disabeln        :"<<endl;
		cout <<""<<endl;

		coordScreen.X = 28;
		coordScreen.Y = 3;
		SetConsoleCursorPosition(hConsoleOut, coordScreen);
    }

	// Interrupts enabeln
	Status = PCI_IntEnable (CardNr, NULL, NULL, IntSetPriorityNormal,ErrorStatus);
	
	if(ScreenOut)
	{
		coordScreen.X = 28;
		coordScreen.Y = 4;
		SetConsoleCursorPosition(hConsoleOut, coordScreen);
	}

	if(Status != StatusOK)
	{
		if(ScreenOut)
		{
			SetConsoleTextAttribute(hConsoleOut, BACKGROUND_RED | FOREGROUND_WHITE);  
			PCI_ErrorString (Status, ErrorChar);
			cout<<ErrorChar<<endl<<endl;
				SetConsoleTextAttribute(hConsoleOut, BACKGROUND_BLACK | FOREGROUND_WHITE);
			cout<<endl<<endl<<"... Press Enter to abort...";
			PCI_IntDisable(CardNr, ErrorStatus);
			getchar();
			PCI_PCIcardReset(CardNr, ErrorStatus);
			return false;
		}
		else 
		{
			ErrorMessage = " FAILURE ! set Interrupt enable ! ";
			PCI_IntDisable(CardNr, ErrorStatus);
			PCI_PCIcardReset(CardNr, ErrorStatus);
			return false;
		}
	}
	else
	{
		if(ScreenOut)
		{
			SetConsoleTextAttribute(hConsoleOut, BACKGROUND_GREEN | FOREGROUND_WHITE);  
			cout<<" OK "<<endl;
		}
	}

	// Interrupt Maske definieren
	Status = PCI_IntMaskWrite(CardNr, InMask, ErrorStatus);

	if(ScreenOut)
	{
		coordScreen.X = 28;
		coordScreen.Y = 5;
		SetConsoleCursorPosition(hConsoleOut, coordScreen);
	}

	if(Status != StatusOK)
	{
		if(ScreenOut)
		{
			SetConsoleTextAttribute(hConsoleOut, BACKGROUND_RED | FOREGROUND_WHITE);  
			PCI_ErrorString (Status, ErrorChar);
			cout<<ErrorChar<<endl<<endl;
			PCI_IntDisable (CardNr, ErrorStatus);
			SetConsoleTextAttribute(hConsoleOut, BACKGROUND_BLACK | FOREGROUND_WHITE);
			cout<<endl<<endl<<"... Press Enter to abort...";
			PCI_IntDisable(CardNr, ErrorStatus);
			getchar();
			PCI_PCIcardReset(CardNr, ErrorStatus);
			return false;		
		}
		else 
		{
			ErrorMessage = " FAILURE ! set Interrupt Mask ! ";
			PCI_IntDisable(CardNr, ErrorStatus);
			PCI_PCIcardReset(CardNr, ErrorStatus);
			return false;
		}
	}
	else
	{
		if(ScreenOut)
		{
			SetConsoleTextAttribute(hConsoleOut, BACKGROUND_GREEN | FOREGROUND_WHITE);  
			cout<<" OK "<<endl;
		}
	}

	if(lVerInfo.dwMajorVersion == 5 )
	{
		Status = PCI_IntWait(CardNr, IntAktiv, ErrorStatus);

		if((IntAktiv != myDta_Rdy) && (IntAktiv != myDta_Req))
		{
			Status = PCI_IntWait(CardNr, IntAktiv, ErrorStatus);
		}
	}
	else
	{
		Status = PCI_IntWait(CardNr, IntAktiv, ErrorStatus);
	}

	if(ScreenOut)
	{
		coordScreen.X = 28;
		coordScreen.Y = 6;
		SetConsoleCursorPosition(hConsoleOut, coordScreen);
	}
	
	if(Status != StatusOK)
	{
		if(ScreenOut)
		{
			SetConsoleTextAttribute(hConsoleOut, BACKGROUND_RED | FOREGROUND_WHITE);  
			PCI_ErrorString (Status, ErrorChar);
			cout<<ErrorChar<<endl<<endl;
			PCI_IntDisable (CardNr, ErrorStatus);
			SetConsoleTextAttribute(hConsoleOut, BACKGROUND_BLACK | FOREGROUND_WHITE);
			cout<<endl<<endl<<"... Press Enter to abort...";
			PCI_IntDisable(CardNr, ErrorStatus);
			getchar();
			PCI_PCIcardReset(CardNr, ErrorStatus);
			return false;		
		}
		else
		{
			ErrorMessage = " FAILURE ! wait Interrupt ! ";
			PCI_IntDisable(CardNr, ErrorStatus);
			PCI_PCIcardReset(CardNr, ErrorStatus);
			return false;
		}
	}
	else if(IntAktiv == myDta_Rdy)
	{
		ausgabe = "Data Ready";
		error = false;
	}
	else if (IntAktiv == myDta_Req)
	{
		ausgabe = "Data Request";
		error = false;
	}
	else 
	{
		error = true;
	}


	if(error == false)
	{
		if(ScreenOut)
		{
			SetConsoleTextAttribute(hConsoleOut, BACKGROUND_GREEN | FOREGROUND_WHITE);  
			cout<<" OK : "<<ausgabe<<endl;
		}
	}
	else
	{
		if(ScreenOut)
		{
			SetConsoleTextAttribute(hConsoleOut, BACKGROUND_RED | FOREGROUND_WHITE);  
			cout<<" FALSE : "<<hex<<(int)IntAktiv<<endl;
		}
		else
		{
			ErrorMessage = " ERROR ! Wrong Interrupt ! ";
			PCI_IntDisable(CardNr, ErrorStatus);
			PCI_PCIcardReset(CardNr, ErrorStatus);
			return false;
		}
	}

	// Interrupts disabeln
	Status = PCI_IntDisable(CardNr, ErrorStatus);
	if(ScreenOut)
	{
		coordScreen.X = 28;
		coordScreen.Y = 7;
		SetConsoleCursorPosition(hConsoleOut, coordScreen);
	}

	if(Status != StatusOK)
	{
		if(ScreenOut)
		{
			SetConsoleTextAttribute(hConsoleOut, BACKGROUND_RED | FOREGROUND_WHITE);  
			PCI_ErrorString (Status, ErrorChar);
			cout<<ErrorChar<<endl<<endl;
			SetConsoleTextAttribute(hConsoleOut, BACKGROUND_BLACK | FOREGROUND_WHITE);
			cout<<endl<<endl<<"... Press Enter to abort...";
			PCI_IntDisable(CardNr, ErrorStatus);
			getchar();
			PCI_PCIcardReset(CardNr, ErrorStatus);
			return false;		
		}
		else
		{
			ErrorMessage = " FAILURE ! Interrupt disable ! ";
			PCI_IntDisable(CardNr, ErrorStatus);
			PCI_PCIcardReset(CardNr, ErrorStatus);
			return false;
		}
	}
	else
	{
		if(ScreenOut)
		{
			SetConsoleTextAttribute(hConsoleOut, BACKGROUND_GREEN | FOREGROUND_WHITE);  
			cout<<" OK "<<endl;
		}
	}

	if(ScreenOut)
	{
		coordScreen.X = 0;
		coordScreen.Y = 10;
		SetConsoleCursorPosition(hConsoleOut, coordScreen);
		SetConsoleTextAttribute(hConsoleOut, BACKGROUND_GREEN | FOREGROUND_WHITE);  
		cout<<" Test beendet"<<endl<<endl;
		SetConsoleTextAttribute(hConsoleOut, BACKGROUND_BLACK | FOREGROUND_WHITE);
		cout<<".... press Enter to go back ....";
		PCI_IntDisable(CardNr, ErrorStatus);
		getchar();
		PCI_PCIcardReset(CardNr, ErrorStatus);
		
	}

	return true;
}
Beispiel #2
0
int main(void)
{
	struct Hero mage = {
		"",
		MAGE,
		450,
		0,
		50,
		200,
		30,
		10,
		1,
		1,
		0,
		0, 
		NULL,
		NULL
	};
	struct Hero warrior = {
		"",
		WARRIOR,
		550,
		60,
		0,
		0,
		5,
		25,
		1.3,
		1,
		0,
		0, 
		NULL,
		NULL
	};
	struct Hero thief = {
		"",
		THIEF,
		400,
		60,
		0,
		0,
		10,
		15,
		1,
		1.2,
		5,
		0, 
		NULL,
		NULL
	};
	struct Hero bot1 = {
		"Mage",
		ANY,
		500,
		0,
		45,
		0,
		15,
		15,
		1.4,
		1.5,
		10,
		0, 
		NULL,
		NULL
	};
	struct Hero bot2 = {
		"Guard",
		ANY,
		400,
		65,
		0,
		0,
		15,
		35,
		1.8,
		1,
		0,
		0, 
		NULL,
		NULL
	};
	struct Hero bot3 = {
		"Black knight",
		ANY,
		700,
		100,
		0,
		0,
		25,
		25,
		1,
		1.2,
		5,
		0, 
		NULL,
		NULL
	};
	struct Hero * hero;
	struct Hero * bot = &(bot3);
	COORD posHead;
	int a;
	int b;
	int p = 0;
	int status = 0;
	int true = 0;
	const char * Interface[3] = {
		"New game",
		"Load",
		"Records"
	};
	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
	metka: a = move (hConsole, 3, Interface, 7, hero, &(mage), &(warrior), &(thief));
	switch (a){
		case 0 : createHero(&(hero), &(mage), &(warrior), &(thief)); true = 1; break;
		case 1 :
			system("cls");
			FILE * fp = NULL;
			printf("enter full name of file what you will open to load\n");
			char str[30];
			gets(str);
			fp = fopen(str, "r");
			if (NULL == fp)
				status = 1;
			if (status == 0)
			{
				fscanf(fp, "%i", &(b));
				switch (b)
				{
					case MAGE: hero = &(mage); break;
					case WARRIOR: hero = &(warrior); break;
					case THIEF: hero = &(thief); break;
				}
				int Weapon_type;
				int Armor_type;
				fscanf(fp, "%i %i %i", &(Weapon_type), &(Armor_type), &(hero->gold));
				switch (Armor_type)
				{
					case -1: status = 1; break;
					case 6: hero->Armor = &(steel_armor); break;
					case 7: hero->Armor = &(mage_robe); break;
					case 8: hero->Armor = &(lether_armor); break;
					case 9: hero->Armor = &(dragon_armor); break;
					case 10: hero->Armor = &(arcgmage_robe); break;
					case 11: hero->Armor = &(elven_armor); break;
				}
				if (status != 1){
					hero->health += hero->Armor->health;
					hero->damage += hero->Armor->damage;
					hero->mag_damage += hero->Armor->mag_damage;
					hero->mana += hero->Armor->mana;
					hero->magic_protect += hero->Armor->magic_protect;
					hero->armor += hero->Armor->armor;
					hero->critical_damage += hero->Armor->critical_damage - 1;
					hero->critical_chanse += hero->Armor->critical_chanse;
				}
				switch (Weapon_type)
				{
					case -1: status = -1; break;
					case 0: hero->Weapon = &(steel_sword); break;
					case 1: hero->Weapon = &(magic_stick); break;
					case 2: hero->Weapon = &(steel_dagger); break;
					case 3: hero->Weapon = &(great_sword); break;
					case 4: hero->Weapon = &(wood_scepter); break;
					case 5: hero->Weapon = &(thief_dagger); break;
				}
				if (status != -1){
					hero->health += hero->Weapon->health;
					hero->damage += hero->Weapon->damage;
					hero->mag_damage += hero->Weapon->mag_damage;
					hero->mana += hero->Weapon->mana;
					hero->magic_protect += hero->Weapon->magic_protect;
					hero->armor += hero->Weapon->armor;
					hero->attack_speed = hero->Weapon->attack_speed;
					hero->critical_damage += hero->Weapon->critical_damage - 1;
					hero->critical_chanse += hero->Weapon->critical_chanse;
				}
				true = 1;
				
			}
			else 
				printf("error input");
			fclose(fp);	
			break;
		case 2 : printRec(); goto metka;break;
		
	}
	
	
	while (true)
	{
		shop(hero, &(mage), &(warrior), &(thief));
		true = battle(hero, &(bot1), &(bot2), &(bot3));
		if (true == 2)
			;
		else if (true)
			printf("WIN\n");
		else
			printf("LOSE\n");
		getchar();
	}
	system("cls");
	posHead.X = 34;
	posHead.Y = 10;
	SetConsoleCursorPosition(hConsole, posHead);
	SetConsoleTextAttribute(hConsole, FOREGROUND_RED);
	puts("GAME OVER");
	posHead.Y = 11;
	SetConsoleCursorPosition(hConsole, posHead);
	printf("your result is %i", hero->gold);
	posHead.Y++;
	SetConsoleCursorPosition(hConsole, posHead);
	printf("enter your nickname\n");
	char nick[20];
	posHead.Y++;
	SetConsoleCursorPosition(hConsole, posHead);
	gets(nick);
	if (nick[0] == '\0')
		strcpy(nick, "noName");
	int record[10];
	char temp[10][20];
	FILE * fp = NULL;
	fp = fopen("reclab4.txt", "r");
	if (NULL == fp)
		return 0;
	for (int i = 0; i < 10; i++){
		fscanf(fp, "%i %s", &record[i], temp[i]);
		//printf("%i. %8i  %s\n", i + 1, record, nick);
		if (record[i] > hero->gold)
			p = i;
	}
	fclose(fp);
	fp = fopen("reclab4.txt", "w");
	for (int i = 0; i < 10; i++){
		if (p == i - 1)
			fprintf(fp, "%i %s\n", hero->gold, nick);
		fprintf(fp, "%i %s\n", record[i], temp[i]);
	}
	SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN);
	getchar();
	fclose(fp);
	return EXIT_SUCCESS;
}
int gotoxy(int x, int y)
{
    COORD cd;
    cd.X = x;cd.Y = y;
    return SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),cd);
}
Beispiel #4
0
void gotoxy(int x,int y)// a function controls the coordenates of the outputs
{
    coord.X=x;
    coord.Y=y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
/*!
    Adds all pending keyboard input to the internal buffer.   The
    implementation uses ReadConsoleInput() which is a non-blocking function.
    All non-keyboard events are ignored.
 */
void ConsoleInputBuffer::AddPendingInputToBuffer() {
  //
  // Read pending events
  //
  DWORD dwRead;
  INPUT_RECORD inRecords[128];
  ::ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &inRecords[0], 128, &dwRead);
  //
  // Process the events
  //
  for (unsigned int i = 0; i < dwRead; ++i) {
    if (inRecords[i].EventType == KEY_EVENT) {
      // Key events include non-character keys like SHIFT.  Filter
      // these out.
      const KEY_EVENT_RECORD& evt = inRecords[i].Event.KeyEvent;
      const char c = evt.uChar.AsciiChar;
      if (evt.bKeyDown) {
        if (c != 0) {
          // Unfortunately since keyboard input is being handled manually
          // behavior such as backspace needs to be manually emulated.
          if (c == '\b') {
            // Do not let the prompt be erased
            if (buffer_.empty())
              continue;

            // Emulate the default behavior by echoing the typed characters
            std::cout << c;

            HANDLE hStdOut = ::GetStdHandle(STD_OUTPUT_HANDLE);
            CONSOLE_SCREEN_BUFFER_INFO info;
            DWORD dwWritten;
            ::GetConsoleScreenBufferInfo(hStdOut, &info);
            ::WriteConsoleOutputCharacter(hStdOut, L" ", 1,
                info.dwCursorPosition, &dwWritten);
            buffer_.pop_back(); // pop the last character
          } else {
            // Emulate the default behavior by echoing the typed characters
            std::cout << c;

            // Add to the buffer
            buffer_ += c;
          }
        } else if (evt.wVirtualKeyCode == VK_UP ||
                   evt.wVirtualKeyCode == VK_DOWN) {
          // Move up/down the history
          bool up = (evt.wVirtualKeyCode == VK_UP);
          if (up) {
            if (history_index_ == 0)
              history_index_ = history_.size();
            else
              --history_index_;
          } else {
            if (history_index_ >= history_.size())
              history_index_ = 0;
            else
              ++history_index_;
          }
          std::string new_command;
          if (history_index_ < history_.size())
            new_command = history_[history_index_];
          // else empty string
          
          HANDLE hStdOut = ::GetStdHandle(STD_OUTPUT_HANDLE);
          CONSOLE_SCREEN_BUFFER_INFO info;
          ::GetConsoleScreenBufferInfo(hStdOut, &info);
          // Clear first
          std::wstring clearStr(buffer_.size(), L' ');
          COORD pos = info.dwCursorPosition;
          pos.X -= static_cast<short>(clearStr.size());
          DWORD dwWritten;
          ::WriteConsoleOutputCharacter(hStdOut, clearStr.c_str(),
                                        static_cast<DWORD>(clearStr.size()),
                                        pos, &dwWritten);
          // Set cursor to the beginning
          SetConsoleCursorPosition(hStdOut, pos);
          // Write the new line
          std::cout << new_command;
          buffer_ = new_command;
        }
      }
    }
  }
}
Beispiel #6
0
void Position(int x, int y)
{
    COORD pos = { x - 1, y - 1 };
    HANDLE Out = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(Out, pos);
}
Beispiel #7
0
int Execute(HANDLE hPlugin,char *CmdStr,int HideOutput,int Silent,int ShowTitle,char *ListFileName)
{
  STARTUPINFO si;
  PROCESS_INFORMATION pi;
  int ExitCode,ExitCode2,LastError;

  memset(&si,0,sizeof(si));
  si.cb=sizeof(si);

  HANDLE hChildStdoutRd,hChildStdoutWr;
  HANDLE StdInput=GetStdHandle(STD_INPUT_HANDLE);
  HANDLE StdOutput=GetStdHandle(STD_OUTPUT_HANDLE);
  HANDLE StdError=GetStdHandle(STD_ERROR_HANDLE);
  HANDLE hScreen=NULL;
  CONSOLE_SCREEN_BUFFER_INFO csbi;

  if (HideOutput)
  {
    SECURITY_ATTRIBUTES saAttr;
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle = TRUE;
    saAttr.lpSecurityDescriptor = NULL;

    if (CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 32768))
    {
      if (Silent)
      {
        /*hScreen=Info.SaveScreen(0,0,-1,0);
        Info.Text(2,0,LIGHTGRAY,GetMsg(MWaitForExternalProgram))*/;
      }
      else
      {
        hScreen=Info.SaveScreen(0,0,-1,-1);
        const char *MsgItems[]={"",GetMsg(MWaitForExternalProgram)};
        Info.Message(Info.ModuleNumber,0,NULL,MsgItems,
                      ARRAYSIZE(MsgItems),0);
      }
      SetStdHandle(STD_OUTPUT_HANDLE,hChildStdoutWr);
      SetStdHandle(STD_ERROR_HANDLE,hChildStdoutWr);
    }
    else
      HideOutput=FALSE;
  }
  else
  {
    Info.Control(hPlugin, FCTL_GETUSERSCREEN, NULL);
    GetConsoleScreenBufferInfo(StdOutput, &csbi);
    COORD C = { 0, csbi.dwCursorPosition.Y };
    SetConsoleCursorPosition(StdOutput, C);
  }


  DWORD ConsoleMode;
  GetConsoleMode(StdInput,&ConsoleMode);
  SetConsoleMode(StdInput,ENABLE_PROCESSED_INPUT|ENABLE_LINE_INPUT|
                 ENABLE_ECHO_INPUT|ENABLE_MOUSE_INPUT);

  char ExpandedCmd[MAX_COMMAND_LENGTH];
  ExpandEnvironmentStrings(CmdStr,ExpandedCmd,sizeof(ExpandedCmd));
  FSF.LTrim(ExpandedCmd); //$ AA 12.11.2001

  char SaveTitle[512];
  GetConsoleTitle(SaveTitle,sizeof(SaveTitle));
  if (ShowTitle)
    SetConsoleTitle(ExpandedCmd);

  /* $ 14.02.2001 raVen
     делать окошку minimize, если в фоне */
  if (Opt.Background)
  {
    si.dwFlags=si.dwFlags | STARTF_USESHOWWINDOW;
    si.wShowWindow=SW_MINIMIZE;
  }
  /* raVen $ */

  ExitCode2=ExitCode=CreateProcess(NULL,ExpandedCmd,NULL,NULL,HideOutput,
            (Opt.Background?CREATE_NEW_CONSOLE:0)|PriorityProcessCode[Opt.PriorityClass],
            NULL,NULL,&si,&pi);

  LastError=!ExitCode?GetLastError():0;
  if (HideOutput)
  {
    SetStdHandle(STD_OUTPUT_HANDLE,StdOutput);
    SetStdHandle(STD_ERROR_HANDLE,StdError);
    CloseHandle(hChildStdoutWr);
  }

  SetLastError(LastError);
  if(!ExitCode2 /*|| !FindExecuteFile(ExecuteName,NULL,0)*/) //$ 06.03.2002 AA
  {
    char Msg[100];
    char ExecuteName[NM];
    lstrcpyn(ExecuteName,ExpandedCmd+(*ExpandedCmd=='"'), NM);
    char *Ptr;
    Ptr=strchr(ExecuteName,(*ExpandedCmd=='"')?'"':' ');
    if(Ptr)
      *Ptr=0;
    FindExecuteFile(ExecuteName,NULL,0);

    char NameMsg[NM];
    FSF.TruncPathStr(lstrcpyn(NameMsg,ExecuteName,sizeof(NameMsg)),MAX_WIDTH_MESSAGE);
    FSF.sprintf(Msg,GetMsg(MCannotFindArchivator),NameMsg);
    const char *MsgItems[]={GetMsg(MError),Msg, GetMsg(MOk)};
    Info.Message(Info.ModuleNumber,FMSG_WARNING|FMSG_ERRORTYPE,
                 NULL,MsgItems,ARRAYSIZE(MsgItems),1);
    ExitCode=RETEXEC_ARCNOTFOUND;
  }

  if (ExitCode && ExitCode!=RETEXEC_ARCNOTFOUND)
  {
    if (HideOutput)
    {
      WaitForSingleObject(pi.hProcess,1000);

      char PipeBuf[32768];
      DWORD Read;
      while (ReadFile(hChildStdoutRd,PipeBuf,sizeof(PipeBuf),&Read,NULL))
        ;
      CloseHandle(hChildStdoutRd);
    }
    /* $ 13.09.2000 tran
       фоновой выполнение */
    if ( !Opt.Background )
    {
        WaitForSingleObject(pi.hProcess,INFINITE);
        GetExitCodeProcess(pi.hProcess,(LPDWORD)&ExitCode);
        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);
    }
    else
    {
        StartThreadForKillListFile(&pi,ListFileName); // нехай за процессом тред следит, и файл бъет тапком
        ExitCode=0;
    }
    /* tran 13.09.2000 $ */
  }
  SetConsoleTitle(SaveTitle);
  SetConsoleMode(StdInput,ConsoleMode);
  if (!HideOutput)
  {
    Info.Control(hPlugin,FCTL_SETUSERSCREEN,NULL);
  }
  if (hScreen)
  {
    Info.RestoreScreen(NULL);
    Info.RestoreScreen(hScreen);
  }

  return ExitCode;
}
Beispiel #8
0
// TODO: 在 STDAFX.H 中
//引用任何所需的附加头文件,而不是在此文件中引用
void gotoXY( int x, int y )
{
	COORD pos = { x*2, y };
	SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), pos );
}
Beispiel #9
0
void Consola::gotoxy(int x, int y) {
	COORD coord;
	coord.X = x;
	coord.Y = y;
	SetConsoleCursorPosition(hconsola,coord);
}
Beispiel #10
0
// Console cursor À̵¿.
void gotoxy(int x, int y)
{
	COORD pos = { static_cast< short >( x ), static_cast< short >( y ) };
	SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), pos );
}
Beispiel #11
0
void consoleGoTo(short int x, short int y) {
	COORD pos = { x, y };
	HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleCursorPosition(output, pos);
}
void gotoxy(short x, short y) {
    COORD pos = {x, y};
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
Beispiel #13
0
//-----------------------------------------------------------------------------
void graphics::set_cursor_pos(int xCo, int yCo)
{
	COORD cursor_pos = {xCo-1, yCo-1};
	SetConsoleCursorPosition(hConsole, cursor_pos);
}
Beispiel #14
0
/*
==================
CON_Show
==================
*/
static void CON_Show( void )
{
	CONSOLE_SCREEN_BUFFER_INFO binfo;
	COORD writeSize = { MAX_EDIT_LINE, 1 };
	COORD writePos = { 0, 0 };
	SMALL_RECT writeArea = { 0, 0, 0, 0 };
	COORD cursorPos;
	int i;
	CHAR_INFO line[ MAX_EDIT_LINE ];
	WORD attrib;

	GetConsoleScreenBufferInfo( qconsole_hout, &binfo );

	// if we're in the middle of printf, don't bother writing the buffer
	if( !qconsole_drawinput )
		return;

	writeArea.Left = 0;
	writeArea.Top = binfo.dwCursorPosition.Y; 
	writeArea.Bottom = binfo.dwCursorPosition.Y; 
	writeArea.Right = MAX_EDIT_LINE;

	// set color to white
	attrib = CON_ColorCharToAttrib( COLOR_WHITE );

	// build a space-padded CHAR_INFO array
	for( i = 0; i < MAX_EDIT_LINE; i++ )
	{
		if( i < qconsole_linelen )
		{
			if( i + 1 < qconsole_linelen && Q_IsColorString( qconsole_line + i ) )
				attrib = CON_ColorCharToAttrib( *( qconsole_line + i + 1 ) );

			line[ i ].Char.AsciiChar = qconsole_line[ i ];
		}
		else
			line[ i ].Char.AsciiChar = ' ';

		line[ i ].Attributes = attrib;
	}

	if( qconsole_linelen > binfo.srWindow.Right )
	{
		WriteConsoleOutput( qconsole_hout, 
			line + (qconsole_linelen - binfo.srWindow.Right ),
			writeSize, writePos, &writeArea );
	}
	else
	{
		WriteConsoleOutput( qconsole_hout, line, writeSize,
			writePos, &writeArea );
	}

	// set curor position
	cursorPos.Y = binfo.dwCursorPosition.Y;
	cursorPos.X = qconsole_cursor < qconsole_linelen
		? qconsole_cursor
		: qconsole_linelen > binfo.srWindow.Right
		        ? binfo.srWindow.Right
		        : qconsole_linelen;

	SetConsoleCursorPosition( qconsole_hout, cursorPos );
}
Beispiel #15
0
void gotoXY(COORD c)
{
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c);
}
Beispiel #16
0
bool Console::initialize()
{
    std::wstring title=L"ckw";

    std::string conf_title = "";
    if(!conf_title.empty()){
        std::vector<wchar_t> buf(conf_title.size(), 0);
        MultiByteToWideChar(CP_ACP, 0, &conf_title[0], (int)conf_title.size(), 
                &title[0], (int)(sizeof(wchar_t) * title.size()) );
        title=std::wstring(buf.begin(), buf.end());
    }

    bool bResult=__hide_alloc_console();
	while((gConWnd = GetConsoleWindow()) == NULL) {
		Sleep(10);
	}
    assert(gConWnd);

	if (!bResult){
		while (!IsWindowVisible(gConWnd)) {
			Sleep(10);
		}
		while(IsWindowVisible(gConWnd)) {
			ShowWindow(gConWnd, SW_HIDE);
			Sleep(10);
		}
	}

    SetConsoleTitle(title.c_str());

    SetConsoleCtrlHandler(sig_handler, TRUE);

    SECURITY_ATTRIBUTES sa;
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;

    gStdIn  = CreateFile(L"CONIN$",  GENERIC_READ|GENERIC_WRITE,
            FILE_SHARE_READ|FILE_SHARE_WRITE,
            &sa, OPEN_EXISTING, 0, NULL);
    if(!gStdIn){
        return(FALSE);
    }

    gStdOut = CreateFile(L"CONOUT$",  GENERIC_READ|GENERIC_WRITE,
            FILE_SHARE_READ|FILE_SHARE_WRITE,
            &sa, OPEN_EXISTING, 0, NULL);
    if(!gStdOut){
        return(FALSE);
    }

    gStdErr = CreateFile(L"CONOUT$",  GENERIC_READ|GENERIC_WRITE,
            FILE_SHARE_READ|FILE_SHARE_WRITE,
            &sa, OPEN_EXISTING, 0, NULL);
    if(!gStdErr){
        return(FALSE);
    }

    HINSTANCE hLib = LoadLibraryW( L"KERNEL32.DLL" );
    if (hLib == NULL)
        goto done;

#define GetProc( proc ) \
    do { \
        proc = (proc##T)GetProcAddress( hLib, #proc ); \
        if (proc == NULL) \
        goto freelib; \
    } while (0)
    GetProc( GetConsoleFontInfo );
    GetProc( GetNumberOfConsoleFonts );
    GetProc( SetConsoleFont );
#undef GetProc

    {
        CONSOLE_FONT font[MAX_FONTS];
        DWORD fonts = GetNumberOfConsoleFonts();
        if (fonts > MAX_FONTS){
            fonts = MAX_FONTS;
        }

        GetConsoleFontInfo(gStdOut, 0, fonts, font);
        CONSOLE_FONT minimalFont = { 0, {0, 0}};
        for(DWORD i=0;i<fonts;i++){
            if(minimalFont.dim.X < font[i].dim.X && minimalFont.dim.Y < font[i].dim.Y)
                minimalFont = font[i];
        }
        SetConsoleFont(gStdOut, minimalFont.index);
    }
freelib:
    FreeLibrary( hLib );
done:

    /* set buffer & window size */
    SMALL_RECT sr = {0,0,0,0};
    SetConsoleWindowInfo(gStdOut, TRUE, &sr);
    COORD size;
    size.X = 80;;
    size.Y = 24 + 500;
    SetConsoleScreenBufferSize(gStdOut, size);
    sr.Left = 0;
    sr.Right = 80-1;
    sr.Top = size.Y - 24;
    sr.Bottom = size.Y-1;
    SetConsoleWindowInfo(gStdOut, TRUE, &sr);
    size.X = sr.Left;
    size.Y = sr.Top;
    SetConsoleCursorPosition(gStdOut, size);

    return true;
}
Beispiel #17
0
void ComboBox::Show() {
	//chosenText->Show();
	if (!firstShow) coord = { coord.X - 1, coord.Y };
	else firstShow = false;
	SetConsoleCursorPosition(handle, coord);
	SetConsoleTextAttribute(handle, chosenText->GetColor());
	char luCorner, ruCorner, ldCorner, rdCorner, vertical, horizontal;
	if (border == BorderType::Single) {
		luCorner = '\xDA';
		horizontal = '\xC4';
		ruCorner = '\xBF';
		vertical = '\xB3';
		rdCorner = '\xD9';
		ldCorner = '\xC0';
	}
	else if (border == BorderType::Double) {
		luCorner = '\xC9';
		horizontal = '\xCD';
		ruCorner = '\xBB';
		vertical = '\xBA';
		rdCorner = '\xBC';
		ldCorner = '\xC8';
	}
	else
	{
		chosenText->Show();
		return;
	}
	short length = (short)chosenText->GetWidth();
	for (short j = coord.Y; j < coord.Y + listSize + 3; j++) {
		for (short i = coord.X; i < coord.X + length + 2; i++) {
			COORD tmpCoord = { i,j };
			SetConsoleCursorPosition(handle, tmpCoord);
			SetConsoleTextAttribute(handle, chosenText->GetColor());
			if (i == coord.X) {
				if (j == coord.Y) {
					cout << luCorner;
				}
				else if (j == coord.Y + listSize + 2) {
					cout << ldCorner;
				}
				else
				{
					cout << vertical;
				}
				continue;
			}
			if (i == coord.X + length + 1) {
				if (j == coord.Y) {
					cout << ruCorner;
				}
				else if (j == coord.Y + listSize + 2) {
					cout << rdCorner;
				}
				else
				{
					cout << vertical;
				}
				continue;
			}
			else {
				if (j == coord.Y || j == coord.Y + listSize + 2) cout << horizontal;
				else cout << ' ';
			}
		}
	}
	SetCoordinates(coord.X + 1, coord.Y + 1);
	SetConsoleCursorPosition(handle, coord);
	chosenText->Print();
	SetConsoleCursorPosition(handle, coord);
}
Beispiel #18
0
//Funkcija za prikaz trenutnog vremena
void CurrentWeather(wstring city)
{
	WeatherInfo weather;
	auto result(async(SendRequest, L"weather?q=" + city));//future kupi return iz funkcije da ga mogu posle iskoristiti
	cls();
	Center(16, true); cout << "Fetching data";
	cursorPos = getCursorPos();
	for (int i = 0; result.wait_for(span) != future_status::ready; i++)
	{
		SetConsoleCursorPosition(ConsoleH, cursorPos);
		switch (i % 4)
		{
			case 0:
				cout << "   ";
				break;
			case 1:
				cout << ".  ";
				break;
			case 2:
				cout << ".. ";
				break;
			case 3:
				cout << "...";
		}
		if (i > 50)
		{
			Center(16, true);
			cout << "  Fetch failed  ";
			SetConsoleTextAttribute(ConsoleH, 240);
			Center(4, 4);
			cout << "Back";
			SetConsoleTextAttribute(ConsoleH, 15);
			while (_getch() != 13);
			return;
		}
	}
	weather = ParseCurrent(result.get());
	if (weather.cityName.size() < 1)
	{
		Center(16, true);
		cout << "  Fetch failed  ";
		SetConsoleTextAttribute(ConsoleH, 240);
		Center(4, 4);
		cout << "Back";
		SetConsoleTextAttribute(ConsoleH, 15);
		while (_getch() != 13);
		return;
	}
	cls();
	Center(19 + city.size()); cout << "Current Weather in " << weather.cityName << "\n";
	Center(38); PrintNow(); PrintNum(static_cast<int>(weather.weather[0].temp)); cout << endl;
	Center(26); cout << "Max temp: " << weather.weather[0].tempMax << "  Min temp: " << weather.weather[0].tempMin << "\n\n\n";
	Center(19); cout << "Weather: " << weather.weather[0].main << endl;
	Center(19); cout << "Cloudiness: " << weather.weather[0].cloudiness << "%" << endl;
	Center(19); cout << "Wind speed: " << weather.weather[0].windSpeed << " m/s" << endl;
	SetConsoleTextAttribute(ConsoleH, 240);
	Center(4, 4);
	cout << "Back";
	SetConsoleTextAttribute(ConsoleH, 15);
	while (_getch() != 13);
}
Beispiel #19
0
void CPlayer::showPlayer()
{
	SetConsoleCursorPosition(m_hStdout, m_pos);
	std::cout << (unsigned char)m_symbol;
}
Beispiel #20
0
void FiveDayForecast(wstring city)
{
	WeatherInfo weather;
	Weather weatherI;
	auto result(async(SendRequest, L"forecast?q=" + city));
	cls();
	Center(16, true); cout << "Fetching data";
	cursorPos = getCursorPos();
	for (int i = 0; result.wait_for(span) != future_status::ready; i++)
	{
		SetConsoleCursorPosition(ConsoleH, cursorPos);
		switch (i % 4)
		{
		case 0:
			cout << "   ";
			break;
		case 1:
			cout << ".  ";
			break;
		case 2:
			cout << ".. ";
			break;
		case 3:
			cout << "...";
		}
		if (i > 50)
		{
			Center(16, true);
			cout << "  Fetch failed  ";
			SetConsoleTextAttribute(ConsoleH, 240);
			Center(4, 4);
			cout << "Back";
			SetConsoleTextAttribute(ConsoleH, 15);
			while (_getch() != 13);
			return;
		}
	}
	weather = ParseFiveDay(result.get());
	if (weather.cityName.size() < 1)
	{
		Center(16, true);
		cout << "  Fetch failed  ";
		SetConsoleTextAttribute(ConsoleH, 240);
		Center(4, 4);
		cout << "Back";
		SetConsoleTextAttribute(ConsoleH, 15);
		while (_getch() != 13);
		return;
	}
	int choice;
	for (;;)
	{
		choice = WeatherList(weather);
		if (choice != weather.ToDateTimeList().size())
		{
			weatherI = TimeList(weather.ToDateTimeList()[choice], weather.cityName);
			if (weatherI.main != "back")
				PrintWeather(weatherI, weather.cityName);
		}
		else break;
	}
}
Beispiel #21
0
int __cdecl main(int argc, char* argv[])
{
	InstallCrashHandle();

	if( argc > 1 )
	{
		for( int i = 1; i < argc; ++i )
		{
			char *filename = argv[i];

			unsigned char bssid[16];
			sscanf( filename, "%02x-%02x-%02x_%02x-%02x-%02x.ivs", &bssid[0], &bssid[1], &bssid[2], &bssid[3], &bssid[4], &bssid[5] );
			getap( bssid );
		}
	}

	ULONG ret;
	ULONG adapterIndex = 0;

	setlocale( LC_ALL, "chs" );
	HANDLE myCaptureEngine;
	ret = NmOpenCaptureEngine(&myCaptureEngine);
	if(ret != ERROR_SUCCESS)
	{
		wprintf(L"Error openning capture engine, 0x%X\n", ret);
		return ret;
	}

	ULONG adapterCount;
	NM_NIC_ADAPTER_INFO AdapterInfo;
	AdapterInfo.Size = sizeof(AdapterInfo);

	ret = NmGetAdapterCount( myCaptureEngine, &adapterCount );
	if( ret != ERROR_SUCCESS || adapterCount == 0 )
	{
		printf("no adapter.\n");
		_getch();
		return ret;
	}

	int n80211 = 0;
	for( ULONG i = 0; i < adapterCount; ++i )
	{
		NmGetAdapter( myCaptureEngine, i, &AdapterInfo );
		if( AdapterInfo.MediumType == NdisMediumNative802_11 && AdapterInfo.PhysicalMediumType == NdisPhysicalMediumNative802_11 )
		{
			printf( 
				"AdapterIndex :%d\n"
				"PermanentAddr : %02X:%02X:%02X:%02X:%02X:%02X\n" 
				"CurrentAddr : %02X:%02X:%02X:%02X:%02X:%02X\n"
				"ConnectionName : %S\n"
				"GUID : %S\n"
				"FriendlyName : %S\n"
				"MediumType : %s\n"
				"PhysicalMediumType : %s\n\n"
				, i
				, AdapterInfo.PermanentAddr[0],AdapterInfo.PermanentAddr[1],AdapterInfo.PermanentAddr[2]
				, AdapterInfo.PermanentAddr[3],AdapterInfo.PermanentAddr[4],AdapterInfo.PermanentAddr[5]
				, AdapterInfo.CurrentAddr[0],AdapterInfo.CurrentAddr[1],AdapterInfo.CurrentAddr[2]
				, AdapterInfo.CurrentAddr[3],AdapterInfo.CurrentAddr[4],AdapterInfo.CurrentAddr[5]
				, AdapterInfo.ConnectionName
				, AdapterInfo.Guid
				, AdapterInfo.FriendlyName
				, MediumName[AdapterInfo.MediumType]
				, PhysicalMediumName[AdapterInfo.PhysicalMediumType]
				);

			++n80211;
		}
	}

	if( n80211 == 0 )
	{
		puts( "Cannot found wifi card." );
		return -1;
	}

	TCHAR szBuffer[256];
	DWORD dwRead = 0;
	if( ReadConsole( GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL ) == FALSE )
	{
		puts( "error input." );
		return -1;
	}

	if( dwRead == 0 )
	{
		puts( "cancel input." );
		return -1;
	}

	szBuffer[dwRead] = 0;
	ULONG nChoice = _ttol( szBuffer );

	//int nChoice = 0;
	if( nChoice > adapterCount )
	{
		puts( "error input." );
		return -1;
	}

	NmGetAdapter( myCaptureEngine, nChoice, &AdapterInfo );

	WCHAR szGuid[MAX_PATH];
	WCHAR *beg = wcschr( AdapterInfo.Guid, '{' ) + 1;
	WCHAR *end = wcschr( AdapterInfo.Guid, '}' );
	wcsncpy( szGuid, beg, end - beg );
	szGuid[end-beg] = 0;

	GUID guidIntf;
	// get the interface GUID
	if (UuidFromStringW((RPC_WSTR)szGuid, &guidIntf) != RPC_S_OK)
	{
		puts( "guid got error." );
		return 0;
	}

	// GetProfile( guidIntf, L"Albert" );
	// SetProfile( guidIntf, "Albert", "0123456789012" );
	global G;
	memset( &G, 0, sizeof(global) );
	ret = NmConfigAdapter(myCaptureEngine, nChoice, myFrameIndication, (void*)&G );
	if(ret != ERROR_SUCCESS)
	{
		wprintf(L"Error configuring the adapter.\n");
		NmCloseHandle(myCaptureEngine);
		return ret;
	}

	NmStartCapture( myCaptureEngine, nChoice, NmPromiscuous );

	clock_t c = clock();
	while( true )
	{
		if( _kbhit() )
		{
			char ch = _getch();
			if( ch == 27 )
				break;
		}
		if( clock() - c > 2000 )
		{
			cls( GetStdHandle( STD_OUTPUT_HANDLE ) );

			COORD POS;
			POS.X = 0;
			POS.Y = 0;
			SetConsoleCursorPosition( GetStdHandle(STD_OUTPUT_HANDLE), POS );
			printf( "Capture frame : %ld\n", FrameCount );
			printf( "%17s|%4s|%3s|%3s(M)|%6s|%6s|%6s|%8s", "ESSID", "CHAN", "POW", "SPD", "PACKET", "MGMT", "DATA", "SECURITY" );

			POS.Y = 2;
			apinfo * ap = aplst;
			while( ap )
			{
				if( ap->security & STD_WEP )
				{
					SetConsoleCursorPosition( GetStdHandle(STD_OUTPUT_HANDLE), POS );
					puts("------------------------------------------------------------");

					char szMac[32];
					char szKeyHex[256];
					char szKeyAscii[64];
					_snprintf( szMac, sizeof(szMac), "%02x-%02x-%02x %02x-%02x-%02x", ap->bssid[0], ap->bssid[1], ap->bssid[2], ap->bssid[3], ap->bssid[4], ap->bssid[5] );
					int n = 0;
					for( int i = 0; i < 13; ++i )
					{
						n += _snprintf( szKeyHex+n, sizeof(szKeyHex)-n, "%02X ", ap->key[i] );
						szKeyAscii[i] = isprint( ap->key[i] )?ap->key[i]:'.';
					}
					szKeyAscii[ap->keylen] = 0;

					printf( "[%-16s|%4d|%3d|%5dM|%6d|%6d|%6d|%8s]\n\t[MAC:%s] [%d/%d]\n\tCrack [HEX %s| ASC %s]",
						ap->essid, ap->channel, ap->power, ap->max_speed, ap->pkt, ap->bcn, ap->nb_data, (ap->security&STD_WEP?"WEP":"OTHER"), 
						szMac, ap->nb_ivs_clean, ap->nb_ivs_vague, szKeyHex, szKeyAscii );

					if( ap->crack_result )
					{
						POS.Y += 1;
						printf( "\n%s cracked key = %s profile %s", ap->essid, ap->key, ap->profile_state?"set":"not set" );
						if( ap->profile_state == false )
						{
							SetProfile( guidIntf, (char*)ap->essid, (char*)ap->key );
							ap->profile_state = true;
						}
					}

					POS.Y += 4;
				}

				ap = ap->next;
			}

			c = clock();
		}
		Sleep(1);
	}
	NmStopCapture( myCaptureEngine, nChoice );
	NmCloseHandle( myCaptureEngine );

	apinfo * ap = aplst;
	while( ap )
	{
		apinfo *aptmp = ap;
		ap = ap->next;

		fclose( aptmp->ivs );
		uniqueiv_wipe( aptmp->uiv_root );
		DeleteCriticalSection( &aptmp->lock );
		free( aptmp );
	}
	return 0;
}
Beispiel #22
0
void draw(COORD posXY, char symbol) {
   	/* Draw the something */
   	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), posXY);
   	printf("%c", symbol);
}
Beispiel #23
0
void setCursorPosition(int x, int y)
{
    COORD coord = {x, y};
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(hConsole, coord);
}
Beispiel #24
0
extern void ConsoleSetCursor(int y, int x)
{
	COORD coPos = {(SHORT)x, (SHORT)y};
	SetConsoleCursorPosition(m_hWork, coPos);
}
Beispiel #25
0
void gotoxy(int x, int y) {
	COORD pos = { (SHORT)x,(SHORT)y };
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void GoToPosZero()
{
	COORD cur={0,0};
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),cur);
}
Beispiel #27
0
ICRESULT SkeeBall::WiiMoteLoop(void*)
{
    // let's load a couple of samples:
    wiimote_sample sine_sample, daisy_sample;

    // simple callback example (we use polling for almost everything here):
    remote.ChangedCallback		= on_state_change;
    //  notify us only when something related to the extension changes
    remote.CallbackTriggerFlags = (state_change_flags)( EXTENSION_CHANGED |
                                  MOTIONPLUS_CHANGED);

reconnect:
    COORD pos = { 0, 6 };
    SetConsoleCursorPosition(console, pos);

    // try to connect the first available wiimote in the system
    //  (available means 'installed, and currently Bluetooth-connected'):
    COLWHITE;
    _tprintf(_T("  Looking for a Wiimote     "));

    static const TCHAR* wait_str[] = { _T(".  "), _T(".. "), _T("...") };
    unsigned count = 0;
    while(!remote.Connect(wiimote::FIRST_AVAILABLE)) {
        _tprintf(_T("\b\b\b\b%s "), wait_str[count%3]);
        count++;
#ifdef USE_BEEPS_AND_DELAYS
        Beep(500, 30);
        Sleep(1000);
#endif
    }

    wiimote = true;

    // connected - light all LEDs
    remote.SetLEDs(0x0f);
    BRIGHT_CYAN;
    _tprintf(_T("\b\b\b\b... connected!"));
    if(remote.IsBalanceBoard()) {
        BRIGHT_WHITE;
        _tprintf(_T("  (Balance Board)"));
    }

#ifdef USE_BEEPS_AND_DELAYS
    Beep(1000, 300);
    Sleep(2000);
#endif

    COORD cursor_pos = { 0, 6 };


    // ask the wiimote to report everything (using the 'non-continous updates'
    //  default mode - updates will be frequent anyway due to the acceleration/IR
    //  values changing):

    // note1: you don't need to set a report type for Balance Board - the library
    //         takes care of it (there is only one).
    // note2: for wiimotes, the report mode that includes the extension data
    //		   unfortunately only reports the 'BASIC' IR info (ie. no dot sizes) -
    //		   so let's choose the best mode based on the extension status (we also
    //		   toggle modes as needed in the callback above):
    if(!remote.IsBalanceBoard())
    {
        if(remote.bExtension)
            remote.SetReportType(wiimote::IN_BUTTONS_ACCEL_IR_EXT); // no IR dots
        else
            remote.SetReportType(wiimote::IN_BUTTONS_ACCEL_IR);		//    IR dots
    }

    // (stuff for animations)
    DWORD	 last_rumble_time = timeGetTime(); // for rumble text animation
    DWORD    last_led_time    = timeGetTime(); // for led         animation
    bool	 rumble_text	  = true;
    unsigned lit_led          = 0;

    // display the wiimote state data until 'Home' is pressed:
    bool caliubrate_atrest_once = true;
    while(playing)// && !GetAsyncKeyState(VK_ESCAPE))
    {
        // the wiimote state needs to be refreshed for each pass
        while(remote.RefreshState() == NO_CHANGE)
            Sleep(1); // // don't hog the CPU if nothing changed

        cursor_pos.Y = 8;
        SetConsoleCursorPosition(console, cursor_pos);

        // did we loose the connection?
        if(remote.ConnectionLost())
        {
            BRIGHT_RED;
            _tprintf(
                _T("   *** connection lost! ***                                          \n")
                BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE
                BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE
                BLANK_LINE BLANK_LINE BLANK_LINE);
            Beep(100, 1000);
            Sleep(2000);
            COORD pos = { 0, 6 };
            SetConsoleCursorPosition(console, pos);
            _tprintf(BLANK_LINE BLANK_LINE BLANK_LINE);
            goto reconnect;
        }

        // rumble if 'B' (trigger) is pressed
        remote.SetRumble(remote.Button.B());

        // disable MotionPlus (if connected) to allow its own extension port
        //  to work
        if(remote.Button.Minus())
            remote.DisableMotionPlus();

        // actions for buttons just pressed/released:
        static bool last_A = false, last_One = false, last_Two = false;

#define ON_PRESS_RELEASE(button, pressed_action, released_action)	\
        { bool pressed = remote.Button.button();						\
        if(pressed)													\
        {				   /* just pressed? */						\
        if(!last_##button) pressed_action;							\
        }															\
        else if(last_##button) /* just released */						\
        released_action;											\
        /* remember the current button state for next time */			\
        last_##button = pressed; }

        // Battery level:
        CYAN;
        _tprintf(_T("  Battery: "));
        // (the green/yellow colour ranges are rough guesses - my wiimote
        //  with rechargeable battery pack fails at around 15%)
        (remote.bBatteryDrained	    )? BRIGHT_RED   :
        (remote.BatteryPercent >= 30)? BRIGHT_GREEN : BRIGHT_YELLOW;
        _tprintf(_T("%3u%%   "), remote.BatteryPercent);

        DWORD current_time = timeGetTime();

        // LEDs:
        //  animate them every second
        if((current_time - last_led_time) >= 1000) {
            remote.SetLEDs((BYTE)(1<<lit_led));
            lit_led		  = (++lit_led) % 4;
            last_led_time = timeGetTime();
        }

        CYAN;
        _tprintf(_T("LEDs: "));
        COLWHITE;
        _tprintf(_T("["));
        for(unsigned led=0; led<4; led++)
        {
            if(remote.LED.Lit(led)) {
                BRIGHT_CYAN;
                _tprintf(_T("*"));
            }
            else {
                COLWHITE      ;
                _tprintf(_T("-"));//_T("%c"), '0'+led);
            }
        }

        // Rumble
        COLWHITE;
        _tprintf(_T("]    "));
        if(remote.bRumble) {
            BRIGHT_WHITE;
            _tprintf(rumble_text? _T(" RUMBLE") : _T("RUMBLE "));
            // animate the text
            if((current_time - last_rumble_time) >= 110) {
                rumble_text		 = !rumble_text;
                last_rumble_time = current_time;
            }
        }
        else
            _tprintf(_T("       "));

        // Output method:
        CYAN;
        _tprintf( _T("    using %s\n"), (remote.IsUsingHIDwrites()?
                                         _T("HID writes") : _T("WriteFile()")));

        // Buttons:
        CYAN;
        _tprintf(_T("\n  Buttons: "));
        COLWHITE;
        _tprintf(_T("["));
        for(unsigned bit=0; bit<16; bit++)
        {
            WORD mask = (WORD)(1 << bit);
            // skip unused bits
            if((wiimote_state::buttons::ALL & mask) == 0)
                continue;

            const TCHAR* button_name = wiimote::ButtonNameFromBit[bit];
            bool		 pressed	 = ((remote.Button.Bits & mask) != 0);
            if(bit > 0) {
                CYAN;
                _tprintf(_T("|")); // seperator
            }
            if(pressed) {
                BRIGHT_WHITE;
                _tprintf(_T("%s")  , button_name);
            }
            else {
                COLWHITE       ;
                _tprintf(_T("%*s"), _tcslen(button_name), _T(""));
            }
        }
        COLWHITE;
        _tprintf(_T("]\n"));

        // Acceleration:
        CYAN ;
        _tprintf(_T("    Accel:"));
        remote.IsBalanceBoard()? RED : COLWHITE;
        _tprintf(_T("  X %+2.3f  Y %+2.3f  Z %+2.3f  \n"),
                 remote.Acceleration.X,
                 remote.Acceleration.Y,
                 remote.Acceleration.Z);

        // Orientation estimate (shown red if last valid update is aging):
        CYAN ;
        _tprintf(_T("   Orient:"));
        remote.IsBalanceBoard()? RED : COLWHITE;
        _tprintf(_T("  UpdateAge %3u  "), remote.Acceleration.Orientation.UpdateAge);

        //  show if the last orientation update is considered out-of-date
        //   (using an arbitrary threshold)
        if(remote.Acceleration.Orientation.UpdateAge > 10)
            RED;

        _tprintf(_T("Pitch:%4ddeg  Roll:%4ddeg  \n")
                 _T("                           (X %+.3f  Y %+.3f  Z %+.3f)      \n"),
                 (int)remote.Acceleration.Orientation.Pitch,
                 (int)remote.Acceleration.Orientation.Roll ,
                 remote.Acceleration.Orientation.X,
                 remote.Acceleration.Orientation.Y,
                 remote.Acceleration.Orientation.Z);

        // IR:
        CYAN ;
        _tprintf(_T("       IR:"));
        remote.IsBalanceBoard()? RED : COLWHITE;
        _tprintf(_T("  Mode %s  "),
                 ((remote.IR.Mode == wiimote_state::ir::OFF     )? _T("OFF  ") :
                  (remote.IR.Mode == wiimote_state::ir::BASIC   )? _T("BASIC") :
                  (remote.IR.Mode == wiimote_state::ir::EXTENDED)? _T("EXT. ") :
                  _T("FULL ")));
        // IR dot sizes are only reported in EXTENDED IR mode (FULL isn't supported yet)
        bool dot_sizes = (remote.IR.Mode == wiimote_state::ir::EXTENDED);

        for(unsigned index=0; index<4; index++)
        {
            wiimote_state::ir::dot &dot = remote.IR.Dot[index];

            if(!remote.IsBalanceBoard()) COLWHITE;
            _tprintf(_T("%u: "), index);

            if(dot.bVisible) {
                COLWHITE;
                _tprintf(_T("Seen       "));
            }
            else {
                RED  ;
                _tprintf(_T("Not seen   "));
            }

            _tprintf(_T("Size"));
            if(dot_sizes)
                _tprintf(_T("%3d "), dot.Size);
            else {
                RED;
                _tprintf(_T(" n/a"));
                if(dot.bVisible) COLWHITE;
            }

            _tprintf(_T("  X %.3f  Y %.3f\n"), dot.X, dot.Y);

            if(index < 3)
                _tprintf(_T("                        "));
        }

        // Speaker:
        CYAN ;
        _tprintf(_T("  Speaker:"));
        remote.IsBalanceBoard()? RED : COLWHITE;
        _tprintf(_T("  %s | %s    "), (remote.Speaker.bEnabled? _T("On ") :
                                       _T("Off")),
                 (remote.Speaker.bMuted  ? _T("Muted") :
                  _T("     ")));
        if(!remote.Speaker.bEnabled || remote.Speaker.bMuted)
            RED;
        else//if(remote.IsPlayingAudio()) BRIGHT_WHITE; else COLWHITE;
            COLWHITE;
        _tprintf(_T("Frequency %4u Hz   Volume 0x%02x\n"),
                 wiimote::FreqLookup[remote.Speaker.Freq],
                 remote.Speaker.Volume);

        // -- Extensions --:
        CYAN ;
        _tprintf(_T("__________\n  Extnsn.:  "));
        switch(remote.ExtensionType)
        {
        case wiimote_state::NONE:
        {
            RED;
            _tprintf(_T("None                                                             \n"));
            _tprintf(BLANK_LINE BLANK_LINE BLANK_LINE);
        }
        break;

        case wiimote_state::PARTIALLY_INSERTED:
        {
            BRIGHT_RED;
            _tprintf(_T("Partially Inserted                                               \n"));
            _tprintf(BLANK_LINE BLANK_LINE BLANK_LINE);
        }
        break;

        // -- Nunchuk --
        case wiimote_state::NUNCHUK:
        {
            BRIGHT_WHITE;
            _tprintf(_T("Nunchuk   "));

            // Buttons:
            CYAN		;
            _tprintf(_T("Buttons: "));
            COLWHITE;
            _tprintf(_T("["));
            BRIGHT_WHITE;
            _tprintf(remote.Nunchuk.C? _T("C") : _T(" "));
            CYAN		;
            _tprintf(_T("|"));
            BRIGHT_WHITE;
            _tprintf(remote.Nunchuk.Z? _T("Z") : _T(" "));
            COLWHITE		;
            _tprintf(_T("]   "));
            // Joystick:
            CYAN		;
            _tprintf(_T("Joystick:  "));
            COLWHITE		;
            _tprintf(_T("X %+2.3f  Y %+2.3f\n"),
                     remote.Nunchuk.Joystick.X,
                     remote.Nunchuk.Joystick.Y);
            // Acceleration:
            CYAN		;
            _tprintf(_T("    Accel:"));
            COLWHITE		;
            _tprintf(_T("  X %+2.3f  Y %+2.3f  Z %+2.3f  \n"),
                     remote.Nunchuk.Acceleration.X,
                     remote.Nunchuk.Acceleration.Y,
                     remote.Nunchuk.Acceleration.Z);

            // Orientation estimate (shown red if last valid update is aging):
            CYAN		;
            _tprintf(_T("   Orient:"));
            COLWHITE		;
            _tprintf(_T("  UpdateAge %3u  "),
                     remote.Nunchuk.Acceleration.Orientation.UpdateAge);
            //  show if the last orientation update is aging
            if(remote.Nunchuk.Acceleration.Orientation.UpdateAge > 10)
                RED;
            _tprintf(_T("Pitch %4ddeg  Roll %4ddeg  \n")
                     _T("                           (X %+.2f  Y %+.2f  Z %+.2f)      \n"),
                     (int)remote.Nunchuk.Acceleration.Orientation.Pitch,
                     (int)remote.Nunchuk.Acceleration.Orientation.Roll ,
                     remote.Nunchuk.Acceleration.Orientation.X,
                     remote.Nunchuk.Acceleration.Orientation.Y,
                     remote.Nunchuk.Acceleration.Orientation.Z);
        }
        break;

        // -- Classic Controller --
        case wiimote_state::CLASSIC:
        case wiimote_state::GH3_GHWT_GUITAR:
        case wiimote_state::GHWT_DRUMS:
        {
            BRIGHT_WHITE;
            // the Guitar Hero controller is just a classic controller with
            //  another ID
            if(remote.ExtensionType == wiimote_state::CLASSIC)
                _tprintf(_T("Classic Controller   "));
            else if(remote.ExtensionType == wiimote_state::GH3_GHWT_GUITAR)
                _tprintf(_T("GH3/GHWT Guitar      "));
            else
                _tprintf(_T("GHWT Drums           "));

            // L: Joystick/Trigger
            COLWHITE;
            _tprintf(_T("L:  "));
            CYAN ;
            _tprintf(_T("Joy "));
            COLWHITE;
            _tprintf(_T("X %+2.3f  Y %+2.3f  "),
                     remote.ClassicController.JoystickL.X,
                     remote.ClassicController.JoystickL.Y);
            CYAN ;
            _tprintf(_T("Trig "));
            COLWHITE;
            _tprintf(_T("%+2.3f\n"),
                     remote.ClassicController.TriggerL);
            // R: Joystick/Trigger
            COLWHITE;
            _tprintf(_T("                                 R:  "));
            CYAN ;
            _tprintf(_T("Joy "));
            COLWHITE;
            _tprintf(_T("X %+2.3f  Y %+2.3f  "),
                     remote.ClassicController.JoystickR.X,
                     remote.ClassicController.JoystickR.Y);
            CYAN ;
            _tprintf(_T("Trig "));
            COLWHITE;
            _tprintf(_T("%+2.3f\n"),
                     remote.ClassicController.TriggerR);

            // Buttons:
            CYAN;
            _tprintf(_T("  Buttons: "));
            COLWHITE;
            _tprintf(_T("["));
            for(unsigned bit=0; bit<16; bit++)
            {
                WORD mask = (WORD)(1 << bit);
                // skip unused bits
                if((wiimote_state::classic_controller::buttons::ALL & mask) == 0)
                    continue;

                const TCHAR* button_name = wiimote::ClassicButtonNameFromBit[bit];
                const TCHAR* seperator	 = (bit==0)? _T("") : _T("|");
                bool		 pressed	 = ((remote.ClassicController.Button.Bits & mask) != 0);
                CYAN;
                _tprintf(seperator);
                if(pressed) {
                    BRIGHT_WHITE;
                    _tprintf(_T("%s")  , button_name);
                }
                else {
                    COLWHITE	;
                    _tprintf(_T("%*s"), _tcslen(button_name), _T(""));
                }
            }
            COLWHITE;
            _tprintf(_T("]"));
        }
        break;

        case wiimote_state::BALANCE_BOARD:
        {
            BRIGHT_WHITE;
            _tprintf(_T("Balance Board"));

            // Weights:
            CYAN ;
            _tprintf(_T("   Weight: "));
            COLWHITE;
            _tprintf(_T("TL    "));
            _tprintf(_T("%6.2f"), remote.BalanceBoard.Kg.TopL);
            CYAN ;
            _tprintf(_T(" kg"));
            COLWHITE; ;
            _tprintf(_T("  TR "));
            _tprintf(_T("%6.2f"), remote.BalanceBoard.Kg.TopR);
            CYAN;
            _tprintf(_T(" kg\n"));
            COLWHITE;
            _tprintf(_T("                                    BL    "));
            _tprintf(_T("%6.2f"), remote.BalanceBoard.Kg.BottomL);
            CYAN;
            _tprintf(_T(" kg"));
            COLWHITE;
            _tprintf(_T("  BR "));
            _tprintf(_T("%6.2f"), remote.BalanceBoard.Kg.BottomR);
            CYAN;
            _tprintf(_T(" kg \n"));
            COLWHITE;
            _tprintf(_T("                                    Total "));
            _tprintf(_T("%6.2f"), remote.BalanceBoard.Kg.Total);
            CYAN;
            _tprintf(_T(" kg"));
        }
        break;

        case wiimote_state::MOTION_PLUS:
        {
            BRIGHT_WHITE;
            _tprintf(_T("Motion Plus"));

            CYAN ;
            _tprintf(_T("    Raw: "));
            COLWHITE;
            _tprintf(_T("Yaw: %04hx  ")   , remote.MotionPlus.Raw.Yaw);
            COLWHITE;
            _tprintf(_T("Pitch: %04hx  ") , remote.MotionPlus.Raw.Pitch);
            COLWHITE;
            _tprintf(_T("Roll: %04hx  \n"), remote.MotionPlus.Raw.Roll);
            CYAN ;
            _tprintf(_T("                         Float: "));
            COLWHITE;
            _tprintf(_T("  %8.3fdeg")     , remote.MotionPlus.Speed.Yaw);
            COLWHITE;
            _tprintf(_T("  %8.3fdeg")   , remote.MotionPlus.Speed.Pitch);
            COLWHITE;
            _tprintf(_T(" %8.3fdeg\n")   , remote.MotionPlus.Speed.Roll);
            _tprintf(BLANK_LINE BLANK_LINE);
            //Sleep(500);
        }
        break;
        }
    }


    // disconnect (auto-happens on wiimote destruction anyway, but let's play nice)
    remote.Disconnect();
    Beep(1000, 200);

    return IC_OK;
}
void GoToPos(int x, int y)
{
	COORD cur={x,y};
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),cur);
}
Beispiel #29
0
int	VFPRINTF(HANDLE handle, const char *fmt, va_list argptr)
{
	/////////////////////////////////////////////////////////////////
	/* XXX Two streams are being used. Disabled to avoid inconsistency [flaviojs]
	static COORD saveposition = {0,0};
	*/

	/////////////////////////////////////////////////////////////////
	DWORD written;
	char *p, *q;
	NEWBUF(tempbuf); // temporary buffer

	if(!fmt || !*fmt)
		return 0;

	// Print everything to the buffer
	BUFVPRINTF(tempbuf,fmt,argptr);

	if( !is_console(handle) && stdout_with_ansisequence )
	{
		WriteFile(handle, BUFVAL(tempbuf), BUFLEN(tempbuf), &written, 0);
		return 0;
	}

	// start with processing
	p = BUFVAL(tempbuf);
	while ((q = strchr(p, 0x1b)) != NULL)
	{	// find the escape character
		if( 0==WriteConsole(handle, p, (DWORD)(q-p), &written, 0) ) // write up to the escape
			WriteFile(handle, p, (DWORD)(q-p), &written, 0);

		if( q[1]!='[' )
		{	// write the escape char (whatever purpose it has) 
			if(0==WriteConsole(handle, q, 1, &written, 0) )
				WriteFile(handle,q, 1, &written, 0);
			p=q+1;	//and start searching again
		}
		else
		{	// from here, we will skip the '\033['
			// we break at the first unprocessible position
			// assuming regular text is starting there
			uint8 numbers[16], numpoint=0;
			CONSOLE_SCREEN_BUFFER_INFO info;

			// initialize
			GetConsoleScreenBufferInfo(handle, &info);
			memset(numbers,0,sizeof(numbers));

			// skip escape and bracket
			q=q+2;
			for(;;)
			{
				if( ISDIGIT(*q) ) 
				{	// add number to number array, only accept 2digits, shift out the rest
					// so // \033[123456789m will become \033[89m
					numbers[numpoint] = (numbers[numpoint]<<4) | (*q-'0');
					++q;
					// and next character
					continue;
				}
				else if( *q == ';' )
				{	// delimiter
					if(numpoint<sizeof(numbers)/sizeof(*numbers))
					{	// go to next array position
						numpoint++;
					}
					else
					{	// array is full, so we 'forget' the first value
						memmove(numbers,numbers+1,sizeof(numbers)/sizeof(*numbers)-1);
						numbers[sizeof(numbers)/sizeof(*numbers)-1]=0;
					}
					++q;
					// and next number
					continue;
				}
				else if( *q == 'm' )
				{	// \033[#;...;#m - Set Graphics Rendition (SGR)
					uint8 i;
					for(i=0; i<= numpoint; ++i)
					{
						if( 0x00 == (0xF0 & numbers[i]) )
						{	// upper nibble 0
							if( 0 == numbers[i] )
							{	// reset
								info.wAttributes = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
							}
							else if( 1==numbers[i] )
							{	// set foreground intensity
								info.wAttributes |= FOREGROUND_INTENSITY;
							}
							else if( 5==numbers[i] )
							{	// set background intensity
								info.wAttributes |= BACKGROUND_INTENSITY;
							}
							else if( 7==numbers[i] )
							{	// reverse colors (just xor them)
								info.wAttributes ^= FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE |
													BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE;
							}
							//case '2': // not existing
							//case '3':	// blinking (not implemented)
							//case '4':	// unterline (not implemented)
							//case '6': // not existing
							//case '8': // concealed (not implemented)
							//case '9': // not existing
						}
						else if( 0x20 == (0xF0 & numbers[i]) )
						{	// off

							if( 1==numbers[i] )
							{	// set foreground intensity off
								info.wAttributes &= ~FOREGROUND_INTENSITY;
							}
							else if( 5==numbers[i] )
							{	// set background intensity off
								info.wAttributes &= ~BACKGROUND_INTENSITY;
							}
							else if( 7==numbers[i] )
							{	// reverse colors (just xor them)
								info.wAttributes ^= FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE |
													BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE;
							}
						}
						else if( 0x30 == (0xF0 & numbers[i]) )
						{	// foreground
							uint8 num = numbers[i]&0x0F;
							if(num==9) info.wAttributes |= FOREGROUND_INTENSITY;
							if(num>7) num=7;	// set white for 37, 38 and 39
							info.wAttributes &= ~(FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
							if( (num & 0x01)>0 ) // lowest bit set = red
								info.wAttributes |= FOREGROUND_RED;
							if( (num & 0x02)>0 ) // second bit set = green
								info.wAttributes |= FOREGROUND_GREEN;
							if( (num & 0x04)>0 ) // third bit set = blue
								info.wAttributes |= FOREGROUND_BLUE;
						}
						else if( 0x40 == (0xF0 & numbers[i]) )
						{	// background
							uint8 num = numbers[i]&0x0F;
							if(num==9) info.wAttributes |= BACKGROUND_INTENSITY;
							if(num>7) num=7;	// set white for 47, 48 and 49
							info.wAttributes &= ~(BACKGROUND_RED|BACKGROUND_GREEN|BACKGROUND_BLUE);
							if( (num & 0x01)>0 ) // lowest bit set = red
								info.wAttributes |= BACKGROUND_RED;
							if( (num & 0x02)>0 ) // second bit set = green
								info.wAttributes |= BACKGROUND_GREEN;
							if( (num & 0x04)>0 ) // third bit set = blue
								info.wAttributes |= BACKGROUND_BLUE;
						}
					}
					// set the attributes
					SetConsoleTextAttribute(handle, info.wAttributes);
				}
				else if( *q=='J' )
				{	// \033[#J - Erase Display (ED)
					//    \033[0J - Clears the screen from cursor to end of display. The cursor position is unchanged.
					//    \033[1J - Clears the screen from start to cursor. The cursor position is unchanged.
					//    \033[2J - Clears the screen and moves the cursor to the home position (line 1, column 1).
					uint8 num = (numbers[numpoint]>>4)*10+(numbers[numpoint]&0x0F);
					int cnt;
					DWORD tmp;
					COORD origin = {0,0};
					if(num==1)
					{	// chars from start up to and including cursor
						cnt = info.dwSize.X * info.dwCursorPosition.Y + info.dwCursorPosition.X + 1;
					}
					else if(num==2)
					{	// Number of chars on screen.
						cnt = info.dwSize.X * info.dwSize.Y;
						SetConsoleCursorPosition(handle, origin); 
					}
					else// 0 and default
					{	// number of chars from cursor to end
						origin = info.dwCursorPosition;
						cnt = info.dwSize.X * (info.dwSize.Y - info.dwCursorPosition.Y) - info.dwCursorPosition.X; 
					}
					FillConsoleOutputAttribute(handle, info.wAttributes, cnt, origin, &tmp);
					FillConsoleOutputCharacter(handle, ' ',              cnt, origin, &tmp);
				}
				else if( *q=='K' )
				{	// \033[K  : clear line from actual position to end of the line
					//    \033[0K - Clears all characters from the cursor position to the end of the line.
					//    \033[1K - Clears all characters from start of line to the cursor position.
					//    \033[2K - Clears all characters of the whole line.

					uint8 num = (numbers[numpoint]>>4)*10+(numbers[numpoint]&0x0F);
					COORD origin = {0,info.dwCursorPosition.Y}; //warning C4204
					SHORT cnt;
					DWORD tmp;
					if(num==1)
					{
						cnt = info.dwCursorPosition.X + 1;
					}
					else if(num==2)
					{
						cnt = info.dwSize.X;
					}
					else// 0 and default
					{
						origin = info.dwCursorPosition;
						cnt = info.dwSize.X - info.dwCursorPosition.X; // how many spaces until line is full
					}
					FillConsoleOutputAttribute(handle, info.wAttributes, cnt, origin, &tmp);
					FillConsoleOutputCharacter(handle, ' ',              cnt, origin, &tmp);
				}
				else if( *q == 'H' || *q == 'f' )
void score(int uhealth,int chealth,int ubullets,int uboomerang,int uwall,int boost,int nofboost)   ///prints score
{
    HANDLE out;
    out=GetStdHandle(STD_OUTPUT_HANDLE);
    COORD ctext={68,4},utext={68,16},utext1={68,17},utext2={68,18},utext3={68,19},utext4={68,20};
    SetConsoleCursorPosition(out,ctext);
    printf("   ");
    SetConsoleCursorPosition(out,utext);
    printf("   ");
    SetConsoleCursorPosition(out,utext1);
    printf("   ");
    SetConsoleCursorPosition(out,utext2);
    printf("  ");
    SetConsoleCursorPosition(out,utext3);
    printf("  ");
    SetConsoleCursorPosition(out,utext4);
    printf("   ");
    SetConsoleCursorPosition(out,ctext);
    printf("%d",chealth);
    SetConsoleCursorPosition(out,utext);
    printf("%d",uhealth);
    SetConsoleCursorPosition(out,utext1);
    printf("%d",ubullets);
    SetConsoleCursorPosition(out,utext2);
    printf("%d",uboomerang);
    SetConsoleCursorPosition(out,utext3);
    printf("%d",uwall);
    if(nofboost==1 && boost==0)
    {
        SetConsoleCursorPosition(out,utext4);
        SetConsoleTextAttribute(out,12);
        printf("OFF");
        SetConsoleTextAttribute(out,7);
    }
    else if(nofboost==0 && boost==1)
    {
        SetConsoleCursorPosition(out,utext4);
        SetConsoleTextAttribute(out,10);
        printf("ON");
        SetConsoleTextAttribute(out,7);
    }
    else if(nofboost==0 && boost==0)
    {
        SetConsoleCursorPosition(out,utext4);
        SetConsoleTextAttribute(out,14);
        printf("...");
        SetConsoleTextAttribute(out,7);
    }
}