// Example 'keyboard'
// Tommy Grandefors
// 2D32 Graphic library
// Beta v1.0
// November 1996

#include <graphix.hh>
#include <videodef.hh>
#include <keydefs.hh> //Contains defines for the most common keyboard codes.
#include <keyboard.hh>

#include <conio.h>
#include <iostream.h>

#define TRANSPARENCY_ON	   1

void UserText(void);

Graphix myGfx; //Create the main object of this library.
Keyboard myKbd; //Use the special keyboard handler.

void main(void)
{
   UserText();

   volatile int* kbdPtr = myKbd.InstallKeyboard(); //Set pointer to key-pressed/released vector

   myGfx.SetVideoMode(VGA320x200x256);
   
   Bitmap Sprite;
   Bitmap EnemySprite;
   Palette SpritePal;
   
   myGfx.LoadPCX("ship.pcx", Sprite, SpritePal, TRANSPARENCY_ON, 192);

   EnemySprite = Sprite; //Let the enemy use the same bitmap.
   
   myGfx.SetPalette(SpritePal);
   
   myGfx.SetVisiblePage(0);
   myGfx.SetDrawPage(0);
   
   int playerX = 150;
   int playerY = 150;
   int enemyX = 100;
   int enemyY = 100;
   int playerWidth = Sprite.GetWidth();
   int playerHeight = Sprite.GetHeight();

   Sprite.SetCollisionSensitivity(80); //60% sensitivity in collisions.

   while(1)
   {
      if( *(kbdPtr + PRESS_LEFT) ) //Did the user press the 'left-arrow' key?
	 playerX -= 2;
      else
	 if( *(kbdPtr+PRESS_RIGHT) )//Did the user press the 'right-arrow' key?
	    playerX += 2;

      if( *(kbdPtr + PRESS_UP) ) //Did the user press the 'up-arrow' key?
	 playerY -= 2;
      else
	 if( *(kbdPtr+PRESS_DOWN) ) //Did the user press the 'down-arrow' key?
	    playerY += 2;

      if( *(kbdPtr + PRESS_ESC) ) //Did the user press the 'Esc' key?
	 break; //Quit

      if( playerX <= 0 ) //We don't want to move the sprite outside the border
	 playerX = 0;
      else
	 if( (playerX + playerWidth) >= 320 )
	    playerX = 320 - playerWidth;
      if( playerY <= 0 )
	 playerY = 0;
      else
	 if( (playerY + playerHeight) >= 200 )
	    playerY = 200 - playerHeight;

      //Check if the player collided with the enemy
      if( Sprite.DetectBitmapCollision(playerX, playerY, EnemySprite, enemyX, enemyY) )
	 myGfx.Print(0, 0, "Collision detected!");
      else
	 myGfx.FilledBox(0, 0, 160, 8, 0); //Hide the text!
      
      myGfx.DrawBitmap(playerX, playerY, Sprite);
      myGfx.DrawBitmap(enemyX, enemyY, EnemySprite);
      myGfx.WaitVerticalRetrace();
      myGfx.FilledBox(playerX, playerY, playerX + playerWidth, playerY + playerHeight, 0); //Erase the sprite
   }
   
   myKbd.UnInstallKeyboard(); //Use the old keyboard handler again.

   myGfx.SetVideoMode(TEXT);
}

void UserText(void)
{
   cout << "This example will show you how to use the new keyboard handler contained within\nthis package. Use the arrow keys to move the bitmap on the screen and press\nthe 'Esc' key when you want to quit the example program." << endl;
   cout << "Press a key to continue!" << endl;

   getch();
}
