#ifndef GAME_H
#define GAME_H
int cont=0;
#include "Nim.h"
#include "world.h"
#include "ItemList.h"
#define numAreas 5

#include "Packet.h"
#define numviews			1
#define numworlds			1
int minconter=0;

string  edittext;						   // an empty string for editting
string::iterator iter = edittext.begin(); // string iterator
int x=100;
int caret = x-87;                       // tracks the text caret
bool insert = true;                    // true of should text be inserted
int tra=0;




class Game
{
private:
	
	View views[numviews];
	
	World worlds;
TileAnimeList animations;
DATAFILE *music;

string severmsg;
public:
	int miniMap_x;
	int miniMap_y;
	
	UnitList logonUnits;
ItemList gameitems;
Item potion;

BITMAP *shrunk;
BITMAP *GUI;
BITMAP *world; // for the mini-map
BITMAP *miniMap; // for the mini-map
void switchArea(int);
	//Game gets
string areasingame[numAreas];

string get_severmsg();
View *get_views();
World *get_worlds();
void hide_MiniMap();

//sets
//void set_severmsg(string);           
DATAFILE *data;
void do_game_logic();
void do_game_networking();
void do_game_gfx();
void deleteWorld();
void create_world(int w,int h);
void drawMiniMap();
void updateMiniMap(int);
void play_song(int s);
void play_sound(int s);
void stop_song();
void show_MiniMap(int w,int h);
void move_MiniMap(int x, int y);
//// Game construters
Game();
//Game destructor

~Game()
{
unload_datafile(music);
unload_datafile(data);

//delete views;
//delete worlds;
}

};
///end of Game 
void do_trans(BITMAP *dest){//makes the bitmap transparent to a certin degree
    int i=0; //the current column of the bitmap we're in
    for(int t = 0; t<dest->h; t++){//go through all the rows in the bitmap
        for(i; i<dest->w; i+=4){//go thorough the row placing a transp pixel every 4  pixel
            putpixel(dest, i, t, makecol(255,0,255));//put the transp pixel
        }
        if(t%2 == 0)//keep rows alternating
           i = 0;
        else
           i = 1;
    }
}
void do_trans3(BITMAP *dest){//makes the bitmap transparent to a certin degree
    int i=0; //the current column of the bitmap we're in
    for(int t = 0; t<dest->h; t++){//go through all the rows in the bitmap
        for(i; i<dest->w; i++){//+=4){//go thorough the row placing a transp pixel every 4  pixel
            putpixel(dest, i, t, makecol(255,0,255));//put the transp pixel
        }
        if(t%2 == 0)//keep rows alternating
           i = 0;
        else
           i = 1;
    }
}
////// newer transs code

void do_trans2(BITMAP *dest){
    int color = makecol(255,0,255);
    int fourth_width = dest->w/4;
    for(int y = 0; y <= dest->h; ++y) 
	{
        unsigned short *pixel_ptr = (unsigned short *)dest->line[y];
        int x = 0;
        if( y & 1 ) {
            ++x;
            ++pixel_ptr;
        
        for(; x <= fourth_width; ++x ) 
		{
            *pixel_ptr = color;
            pixel_ptr += 4;
        }
		}
    }

}

void do_trans4(BITMAP *dest){
	int pixel;
    int x = 0;
    int color = makecol(255,0,255);
    int go_to = dest -> w /2;
    int color_depth = bitmap_color_depth(dest);

    for(int y = 0; y <= dest -> h; ++y){
        
        if(color_depth == 8)  
            unsigned char *pixel = dest -> line[y]; //this is if you're in 8 bpp
        if(color_depth == 15 || color_depth == 16) 
           unsigned short *pixel = (unsigned short *)dest -> line[y]; //this is if you're in 16 or 15 bpp
        else
            unsigned long *pixel = (unsigned long *)dest -> line[y]; //this is if you're in 32 bpp

        if(y & 1){
            ++pixel;
            ++x;
        }
        
        for(; x <= go_to; ++x){
		//*pixel = color;
            pixel = color; 

	//	color *pixel  ; // i put this in becaues  *pixel = color; dont work
            pixel += 2;
        }
    }

}
void Game::updateMiniMap(int lay)
{
	//seperate draw from update
	if(miniMapon == true)
	{
	int i,j,p,t,x,y,c;

	for (i=0; i<views[0].WORLD_X; i++)
	{
		for (j=0; j<views[0].WORLD_Y; j++)
		{
			if(worlds.areas.layers.cells[j][i].get_layer(lay-1)==lay)
			{
			p=worlds.areas.layers.cells[j][i].get_value(lay-1);
			t=worlds.areas.layers.cells[j][i].get_tileset(lay-1);
			x=p/32;
			y=p%32;
			c=getpixel(shrunk,t*8+x,y);
			//if (getpixel(world,i,j)>0)drawing fog of war on mini map
			//{
			if(p!=247)
				{
				putpixel(miniMap,miniMap_x+i,miniMap_y+j,c);	
				}
			//}
			}
		}
	}
	drawRectangle(miniMap,miniMap_x,miniMap_y,views[0].WORLD_X,views[0].WORLD_Y,makecol(128,128,128),0,0);
	//putpixel(bmp,miniMap_x+px/32,miniMap_y+py/32,makecol(255,255,255)); //put whit pictle for play placment
	drawRectangle(miniMap,miniMap_x+views[0].get_screen_pos_x(),miniMap_y+views[0].get_screen_pos_y(),views[0].get_GRID_WIDTH()-1,views[0].get_GRID_WIDTH()-1,makecol(255,255,255),0,0);
	}
}
void Game::drawMiniMap()
{
	//seperate draw from update
	if(miniMapon == true)
	{
		masked_blit(miniMap,views[0].get_buffer(),4,4,4,4,views[0].get_GRID_WIDTH()*32-8,views[0].get_GRID_HEIGHT()*32-8);
	}
}
// move the map with the mouse as the center
void Game::move_MiniMap(int x, int y)
{
	if(miniMapon == true)
	{
		views[0].set_screen_pos_x((x-miniMap_x)-(views[0].get_GRID_WIDTH()/2));
		views[0].set_screen_pos_y((y-miniMap_y)-(views[0].get_GRID_WIDTH()/2));

		if (views[0].get_screen_pos_x()<1) views[0].set_screen_pos_x(1);
		if (views[0].get_screen_pos_x()>(views[0].WORLD_X-views[0].get_GRID_WIDTH())) views[0].set_screen_pos_x((views[0].WORLD_X-views[0].get_GRID_WIDTH()));
		if (views[0].get_screen_pos_y()<1) views[0].set_screen_pos_y(1);
		if (views[0].get_screen_pos_y()>(views[0].WORLD_Y-views[0].get_GRID_HEIGHT())) views[0].set_screen_pos_y((views[0].WORLD_Y-views[0].get_GRID_HEIGHT()));
	}
}

void Game::hide_MiniMap()
{
miniMapon= false;
	destroy_bitmap(shrunk);
destroy_bitmap(world);
}

void Game::show_MiniMap(int w,int h)
{
	miniMapon= true;
	shrunk=create_bitmap(24,32);
//data = load_datafile("data.dat");
	if (world!=NULL)
	{
		//destroy_bitmap(world);
	}
	world=create_bitmap(w,h);
	clear(world);

	stretch_blit((BITMAP*)data[TILES1].dat,shrunk,0,0,256,1024,0,0,8,32);
	stretch_blit((BITMAP*)data[TILES2].dat,shrunk,0,0,256,1024,8,0,8,32);
	stretch_blit((BITMAP*)data[TILES3].dat,shrunk,0,0,256,1024,16,0,8,32);
}

//// Game construters

Game::Game()
{
	
music = load_datafile("music.dat");
data = load_datafile("data.dat");

GUI= create_bitmap(SCREEN_W,SCREEN_H);
miniMap = create_bitmap(SCREEN_W,SCREEN_H);
do_trans3(miniMap);
do_trans3(GUI);

	 miniMap_x= 10;
	 miniMap_y= 360;
	 

if(computerId==0)
{
	logonUnits.load("serverunit.txt");
//logonUnits.save("serverunit.txt");
}

	areasingame[0] = "area1.txt";
	areasingame[1] = "area2.txt";
	areasingame[2]= "area3.txt";
	areasingame[3]= "area4.txt";
	areasingame[4]= "area5.txt";
 animations.load();

//DEFALT GETS ASINGE automaticly
//views[0]= View();
//worlds.world_setup(views[0]);
gameitems.load("gameitems.txt");/////////////////////////////////////
}

void Game::switchArea(int a)
{
current_area=a;
areasingame[0] = "area1.txt";
	areasingame[1] = "area2.txt";
	areasingame[2]= "area3.txt";
	areasingame[3]= "area4.txt";
areasingame[4]= "area5.txt";
worlds.areas.reload(areasingame[a-1]);
get_views()[0].set_screen_pos_x(1);
get_views()[0].set_screen_pos_y(5);
}


//Game gets
string Game::get_severmsg()
{
	return severmsg;
}
View *Game::get_views()
{
	return views;
}

World *Game::get_worlds()
{
	return &worlds;
}

//sets
/*
void Game::set_severmsg(string msg)
{
	severmsg = msg;
}
*/

void blitBuffer(BITMAP *bmp)
{
	
	acquire_screen();
	blit(bmp,screen,0,0,0,0,SCREEN_W,SCREEN_H);
	release_screen();
}

//timer shit
/* these must be declared volatile so the optimiser doesn't mess up */
volatile int xt = 1;
/* timer interrupt handler */

void inc_xt(void)
{
   xt++;
   if (xt>60)
   {
	   xt=1;
   }
}
END_OF_FUNCTION(inc_xt);

unsigned short fps =0;
unsigned short new_fps =0;
unsigned short timer = 1;
////////////////////////////////////////////////////////////////////////////////////////////
void Game::do_game_logic()
{

	draw_mainGUI(GUI);
	if(trademenu==true)
	{
		int asd=draw_trade(GUI,gameitems,((Character*)logonUnits.Get_Unit( traderName )),((Character*)logonUnits.Get_Unit( charnetId )));
		if ( asd==-2 )
		{
			logonUnits.doTrade(((Character*)logonUnits.Get_Unit( traderName ))->Get_id(),((Character*)logonUnits.Get_Unit( charnetId ))->Get_id(), &gameitems);
		trademenu=false;
		}
		if ( asd==-1 )
		{
			trademenu=false;
		}
	}

	if(invnetomenu==true)
	{
	
		draw_backpack(GUI,((Character*)logonUnits.Get_Unit( charnetId ))->inven,gameitems,((Character*)logonUnits.Get_Unit( charnetId ))->itembag);
	}

	if(equiped==true)
	{
		//draw_nimgui(screen,((Character*)logonUnits.Get_Unit( computerId ))->inven,gameitems,((Character*)logonUnits.Get_Unit( computerId ))->itembag);

	draw_paperdoll(GUI,((Character*)logonUnits.Get_Unit( charnetId ))->inven,gameitems,((Character*)logonUnits.Get_Unit( charnetId ))->itembag,logonUnits.Get_Unit( charnetId )->attributess);
	}

	if(inputConter==10)
	{

	//if(computerId!=severId)	
	//{

		if (key[KEY_F10]) 
		{
		
			if(equiped==true)
			{
				equiped= false;
				
			}
			else
			{
				equiped=true;
			}

	
		}
		if (key[KEY_F9]) 
		{
			if(trademenu==true)
			{
				trademenu= false;
				
			}
			else
			{
			trademenu=true;
			}

	
		}

//}
		if(selected_Id==charnetId)
		{
			show_comands= true;
		}
		else
		{
			show_comands= false;
		}

		if (key[KEY_F5])
		{
			((Character*)logonUnits.Get_Unit( charnetId ))->Set_layer(((Character*)logonUnits.Get_Unit( charnetId ))->Get_layer()+1);
			Projectile *p1 =  new Projectile();
			netId++;
			p1->Set_name("projectile");
									p1->Set_id(netId);
			p1->Set_X(((Character*)logonUnits.Get_Unit( charnetId ))->Get_X() +50);
			p1->Set_Y(((Character*)logonUnits.Get_Unit( charnetId ))->Get_Y()+50 );
			p1->Set_inarea(	((Character*)logonUnits.Get_Unit( charnetId ))->Get_inarea() ) ;




			p1->Set_destx(((Character*)logonUnits.Get_Unit( charnetId ))->Get_X()+500);
			p1->Set_desty(((Character*)logonUnits.Get_Unit( charnetId ))->Get_Y()+500);

						inboxbuffer += "0|"+NumberToString(computerId)+"|001|"+p1->toString()+"~";//mite need to send stats here


			inboxbuffer +="0|"+NumberToString(charnetId)+"|002|"+NumberToString(netId)+ ','+ NumberToString(((Character*)logonUnits.Get_Unit( netId ))->Get_X()+500) +','+ NumberToString(((Character*)logonUnits.Get_Unit( netId ))->Get_Y()+500) +
			','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_X())+','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_Y())+
			','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_direction() )+','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_frame())+','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_inarea())+"`~";
								

			/*if(computerId!=0)
			{

				outboxbuffer +="0|" + NumberToString(computerId) + "|011|" + NumberToString(computerId)+"`~";
	
			}*/						
		}




if (key[KEY_F7]) 
			{
			if(text==true)
			{
text= false;
				
			}
			else
			{
			text=true;
			}
			}

if(graphic == false)
{
	textprintf(screen, font, 250, 220, makecol(255, 0, 0),"Press the F6 key to Enable the Graphics");
}
			if (key[KEY_F6])
			{
				if (graphic != false)
				{
					
						stop_song();
					
					graphic = false;
				}
				else if( graphic != true)
				{
					
					
						play_song(MIDI_SPIKKO);
					
					graphic = true;
				}
				
			}	
if (ch_current_area!= 0)
{
	if(current_area!= ch_current_area)
	{
		switchArea(ch_current_area);
	}

	ch_current_area = 0;
}

			if (key[KEY_F1]) 
			{

				switchArea(1);

			}
			
			if (key[KEY_F2]) 
			{

				switchArea(2);

			}
			if (key[KEY_F3]) 
			{

				switchArea(3);

			}
			if (key[KEY_F4]) 
			{

				//switchArea(4);
			}
			if (key[KEY_F4]) 
			{



				switchArea(5);
			}
get_views()[0].WORLD_X =get_worlds()->areas.layers.WORLD_X ;
get_views()[0].WORLD_Y =get_worlds()->areas.layers.WORLD_Y ;


if(key[KEY_F8]) 
{
	if(miniMaponc==true)
	{
		miniMaponc=false;

	}
	else
	{
		miniMaponc=true;
	}
}


	if(miniMaponc==true)
	{

		if(miniMapon==true)
		{
			
			hide_MiniMap();

		}
		else
		{
		
			show_MiniMap(views[0].WORLD_X,views[0].WORLD_Y);
		}
		miniMaponc=false;
	}

		if (mouse_b & 1 && clicked==false)
		{
			clicked= true;
			

			if(mousePointer==1)
			{
			if (worlds.areas.layers.cells[((mouse_y+get_views()[0].get_scroll_y())/TILESIZE)+get_views()[0].get_screen_pos_y()]
							[((mouse_x+get_views()[0].get_scroll_x())/TILESIZE)+get_views()[0].get_screen_pos_x()].get_passable(0)==0)
				{
					
					string pointx = NumberToString(mouse_x+get_views()[0].get_scroll_x()+get_views()[0].get_screen_pos_x()*TILESIZE) ;
					string pointy = NumberToString(mouse_y+get_views()[0].get_scroll_y()+get_views()[0].get_screen_pos_y()*TILESIZE);
					



				//move object that callss move on chritor

		


					if (logonUnits.IsInList( charnetId ))
					{






inboxbuffer +="0|"+NumberToString(charnetId)+"|002|"+NumberToString(charnetId)+ ','+ pointx +','+ pointy +
','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_X())+','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_Y())+
','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_direction() )+','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_frame())+','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_inarea())+"`~";
					textprintf_centre(screen, font, 40, 200, makecol(255, 255, 255), outboxbuffer.c_str());
				//sleep(200);

					}



					
				}
				
			mousePointer=0;
			}
			else
			{

				if (mouse_x>=miniMap_x && mouse_x<miniMap_x+views[0].WORLD_X && 
					mouse_y>=miniMap_y && mouse_y<miniMap_y+views[0].WORLD_Y) 
				{
					move_MiniMap(mouse_x,mouse_y);
				}
				else
				{
					swing= true;
				}
			}
			
		}
		else if(!(mouse_b &2)&&!(mouse_b &1))
		{
		clicked=false;
		}


	if (computerId == 0)//if (computerId != 0)
	{
		if (mouse_b & 2 && clicked==false)
		{
			clicked= true;
			
			// check to see if after we pressed the mouse if we
			// are inside of the grid
			
				// if the area that we clicked is passable
				// then put down crosshairs and tell the player
				// to begin walking in that direction
				// Added the A* algorithm class to find the path to 
				// the crosshairs. It works about 85% accuracy. 

if(selected_Id==charnetId)
		{

				if (worlds.areas.layers.cells[((mouse_y+get_views()[0].get_scroll_y())/TILESIZE)+get_views()[0].get_screen_pos_y()]
							[((mouse_x+get_views()[0].get_scroll_x())/TILESIZE)+get_views()[0].get_screen_pos_x()].get_passable(0)==0)
				{
					
					string pointx = NumberToString(mouse_x+get_views()[0].get_scroll_x()+get_views()[0].get_screen_pos_x()*TILESIZE) ;
					string pointy = NumberToString(mouse_y+get_views()[0].get_scroll_y()+get_views()[0].get_screen_pos_y()*TILESIZE);
					



				//move object that callss move on chritor

		


					if (logonUnits.IsInList( charnetId ))
					{






inboxbuffer +="0|"+NumberToString(charnetId)+"|002|"+NumberToString(charnetId)+ ','+ pointx +','+ pointy +
','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_X())+','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_Y())+
','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_direction() )+','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_frame())+','+NumberToString(logonUnits.Get_Unit( charnetId )->Get_inarea())+"`~";
					textprintf_centre(screen, font, 40, 200, makecol(255, 255, 255), outboxbuffer.c_str());
				//sleep(200);

					}


			mousePointer=0;
					
				}
				
}	
			
		}
		else if(!(mouse_b &2)&&!(mouse_b &1))
		{
			clicked=false;
		}

	}


	inputConter=0;	
	}
	else
	{
		inputConter++;
	}

	if (inboxbuffer.length()  > 0)
	{
//textprintf(screen, font, 100, 10, makecol(255, 255, 255),outboxbuffer.c_str());
//Sleep(5000);
textout(views[0].get_buffer(),font,inboxbuffer.c_str(),50,30,makecol(5,255,5));
//	sleep(9);	
Packet * newpacket= new Packet ;

		newpacket->read();
		newpacket->exscute();
	}


if(startgameofnim == true)
{
	startgameofnim= false;
	//if(computerId != 0)
	//{
		equiped=true;
		views[0].set_screen_pos_x(12);
		views[0].set_screen_pos_y(2);
	//}


}

if (untstringflag== true)
	{
		untstringflag= false;

textout(screen,font,untstring.c_str(),100,20,makecol(255,6,255));

//sleep(1);
	logonUnits.insert(untstring);  /////player
		///// need some this to delet the data fome untstring and the boxs 
	//untstring.erase(0,untstring.length());
	}


if (untStatstringflag== true)
	{
		untStatstringflag= false;
//textout(screen,font,untStatstring.c_str(),100,20,makecol(255,6,255));

//sleep(1);
		logonUnits.upDateStats(untStatstring);  /////player
		///// need some this to delet the data fome untstring and the boxs 
	//untstring.erase(0,untstring.length());
	}


if (untItemliststringflag== true)
	{
		untItemliststringflag= false;
//textout(screen,font,untStatstring.c_str(),100,20,makecol(255,6,255));

//sleep(1);
		logonUnits.upDateUnitItems(untItemliststring);  /////player
		///// need some this to delet the data fome untstring and the boxs 
	//untstring.erase(0,untstring.length());
	}


if (sendlistflag== true)
	{
		logonUnits.listToString(sendliststring);
		sendlistflag =false;
		  
		///// need some this to delet the data fome untstring and the boxs 
	//untstring.erase(0,untstring.length());
	}		

	if (movestringflag== true)
	{
		movestringflag = false;
			
		logonUnits.setdest();  /////player
		///// need some this to delet the data fome untstring and the boxs 
	//untstring.erase(0,untstring.length());
	}
	
if (nimitems==1)
{
if(playpick== true && unitpickedleft==0)
{
//textprintf(screen, font, 250, 220, makecol(255, 0, 0),"You win press F12 to exit");

}
else if(playpick== true)
{
//textprintf(screen, font, 250, 220, makecol(255, 0, 0),"You lose press F12 to exit");

}
else
{
//textprintf(screen, font, 250, 220, makecol(255, 0, 0),"You win press F12 to exit");

}

}
if (deleteflag== true)
	{
//////////////////////////////////////////////////////////////bugg
		deleteflag = false;
			//deletetring = data;
		logonUnits.Delete(StringToNumber(deletetring)) ; /////playerdeletetring.erase(deletetring.length()
		///// need some this to delet the data fome untstring and the boxs 
	//untstring.erase(0,untstring.length());
	}
	

if (nimstringflag == true)
{
//textout(screen,font,usesitem.c_str(),100,400,makecol(255,255,255));
//sleep(644444);
		nimstringflag=false;

	int j= 0;
	int i = 0;
	string  nimstring2 = nimstring;
//maybey i acn make the conver for sring to char* right in here
	string temps[5]; //arry to hold data
	
	while (nimstring2[i]!= '`') //stay in untl you fing the ` at the end
	{
		if (nimstring2[i] != ',')//if found , dont add it to the data and move on to next char
		{
			temps[j] += nimstring2[i]; //add char to temp spot
			i++;
		}
		else
		{
			i++;
			j++;
		}

	}



if(StringToNumber(temps[1]) == 1)//start button
{
 unitpicked = 0;
 unitpickedleft = 3;
	tospawunit=StringToNumber(temps[2]); 
nimitems=tospawunit;
	spawunit=true;
}
else if(StringToNumber(temps[1]) == 2) //end turn
{
playpick=false;
unitpickedleft = 0;
if(nimitems!=1)
{
	if (computerId == 0)
			{

int nue[3] ;
int j=0;

for( int i = nimAI(nimitems); i>0; i--)
{

nue[j]=logonUnits.Get_Unit( "none" ,nue ,1)->Get_id();

inboxbuffer +="0|"+NumberToString(0)+"|002|"+NumberToString(logonUnits.Get_Unit(nue[j])->Get_id())+ ','+ NumberToString(554) +','+ NumberToString(115) +
						','+NumberToString(logonUnits.Get_Unit(nue[j])->Get_X())+','+NumberToString(logonUnits.Get_Unit(nue[j])->Get_Y())+
						','+NumberToString(logonUnits.Get_Unit(nue[j])->Get_direction() )+','+NumberToString(logonUnits.Get_Unit(nue[j])->Get_frame())+','
							+NumberToString(logonUnits.Get_Unit(nue[j])->Get_inarea())+"`~";
	//textout(screen,font,NumberToString(nue[j]).c_str(),100,400+nue[j]+30,makecol(255,255,255));
//sleep(2);			
//logonUnits.Get_Unit(nue)->Set_destx(x);
//logonUnits.Get_Unit(nue)->Set_desty(y);
j++;
}

}
playpick=true;
}
unitpickedleft = 3;
}
else if(StringToNumber(temps[1]) == 3) //end turn
{

	if (computerId == 0)
	{

		//int nue=0;
		//for( int i = tospawunit; i>0; i--)
		//{
	
			nimend=true;
		//	nue=logonUnits.Get_Unit( "none" ,nue )->Get_id();//glitch with the nue valu can only keep track of one preveus number
			//inboxbuffer += "0|0|005|"+NumberToString(nue)+"~";//delet char from screens

		//}
	}
	

}
 
			
		nimstring ="";  /////player
		}			



if(nimend==true)
{
	int dom =logonUnits.Get_Unit( "nim" ,0 )->Get_id() ;
	if(dom!=1)
	{
		//glitch with the nue valu can only keep track of one preveus number
		inboxbuffer += "0|0|005|"+NumberToString(dom)+"~";//delet char from screens
	}
	else
	{
		nimend=false;
	}
}

			
if(useitemflag== true)
{
	//textout(screen,font,usesitem.c_str(),100,400,makecol(255,255,255));
	//sleep(644444);
		useitemflag=false;

	int j= 0;
	int i = 0;
	string  usesitem2 = usesitem;
	//maybey i acn make the conver for sring to char* right in here
	string temps[2]; //arry to hold data
	
	while (usesitem2[i]!= '`') //stay in untl you fing the ` at the end
	{
		if (usesitem2[i] != ',')//if found , dont add it to the data and move on to next char
		{
			temps[j] += usesitem2[i]; //add char to temp spot
			i++;
		}
		else
		{
			i++;
			j++;
		}

	}
	gameitems.use(logonUnits.Get_Unit(StringToNumber(temps[0])),StringToNumber(temps[1]));
	//potion.Use(logonUnits.Get_Unit(StringToNumber(temps[0]))->attributess);//rig

	play_sound(SAMPLE_MAGIC);
 
			
	usesitem ="";  /////player
	///// need some this to delet the data fome untstring and the boxs 
	//untstring.erase(0,untstring.length());
}			







if(yesNOAnserstringflag== true)
{
	//textout(screen,font,usesitem.c_str(),100,400,makecol(255,255,255));
	//sleep(644444);
		yesNOAnserstringflag=false;

	int j= 0;
	int i = 0;
	string  usesitem2 = yesNOAnserstring;
	//maybey i acn make the conver for sring to char* right in here
	string temps[4]; //arry to hold data
	
	while (usesitem2[i]!= '`') //stay in untl you fing the ` at the end
	{
		if (usesitem2[i] != ',')//if found , dont add it to the data and move on to next char
		{
			temps[j] += usesitem2[i]; //add char to temp spot
			i++;
		}
		else
		{
			i++;
			j++;
		}

	}

	if(StringToNumber(temps[2])==1) //yes/no anser is about trade request
	{

		if(StringToNumber(temps[3])==1)//if reply == 1 (yes)
		{
			outboxbuffer += temps[0]+"|0|016|" +'~'; //2nd one mean yes
			//outboxbuffer += temps[0]+"|0|016|"+ newstring +",1,1"+'~'; //2nd one mean yes

		}
		else
		{


		}



	}



 
			
	yesNOAnserstring ="";  /////player
	///// need some this to delet the data fome untstring and the boxs 
	yesNOAnserstring.erase(0,i);
}		












							
if (talkstringflag== true)
{
	talkstringflag = false;
		
	logonUnits.setdieolog();  /////player
	///// need some this to delet the data fome untstring and the boxs 
	//untstring.erase(0,untstring.length());
}
if (computerId != 0)//if im the sevre send back online
{			
	if(unitpicked!=0)
	{
		//Set_destx(840);
						//Set_desty(115);
		outboxbuffer +="0|"+NumberToString(unitpicked)+"|002|"+NumberToString(unitpicked)+ ','+ NumberToString(840) +','+ NumberToString(115) +
		','+NumberToString(logonUnits.Get_Unit( unitpicked )->Get_X())+','+NumberToString(logonUnits.Get_Unit( unitpicked )->Get_Y())+
		','+NumberToString(logonUnits.Get_Unit( unitpicked )->Get_direction() )+','+NumberToString(logonUnits.Get_Unit( unitpicked )->Get_frame())+','+NumberToString(logonUnits.Get_Unit( unitpicked )->Get_inarea())+"`~";


		unitpicked=0;
	}
}















if(startTradestringflag== true)
{
	//textout(screen,font,usesitem.c_str(),100,400,makecol(255,255,255));
	//sleep(644444);
	startTradestringflag=false;

	logonUnits.startTrade(startTradestring);
	
	
	
	startTradestring="";


}
		
	





















	if ( battler.length()  > 0)
	{
	   logonUnits.battle(battler,music);
		battler="";
		
	}      
	if(serverdiolog.length()  > 0)
	{

		if (smsglife == 100)
		{
			serverdiolog="";
			smsglife=0;
		}
		else
		{
		smsglife++;
		}
	
}
                            
        ///////////////////////////////////////////////////////////////////////////////////
        // the game loop
logonUnits.sort();//we want mege sort instean for nlogn every time
logonUnits.setup_collision(music);//need better one sort then check side items bugg
//worlds.areas[0][0].players.setup_collision();




 if(text==true)
{              
 while(keypressed())
                {
                        int  newkey   = readkey();
                        char ASCII    = newkey & 0xff;
                        char scancode = newkey >> 8;
                        
                        // a character key was pressed; add it to the string
                        if(ASCII >= 32 && ASCII <= 126)
                        {
                                // add the new char, inserting or replacing as need be
                                if(insert || iter == edittext.end())
                                iter = edittext.insert(iter, ASCII);
                                else
                                edittext.replace(caret, 1, 1, ASCII);
                                
                                // increment both the caret and the iterator
                                caret++;
                                iter++;
                        }
                        // some other, "special" key was pressed; handle it here
                        else
                        switch(scancode)
                        {
                                case KEY_DEL:
                                if(iter != edittext.end()) iter = edittext.erase(iter);
                                break;
                                
                                case KEY_BACKSPACE:
                                if(iter != edittext.begin())
                                {
                                        caret--;
                                        iter--;
                                        iter = edittext.erase(iter);
                                }
                                break;
                                
                                case KEY_RIGHT:
                                if(iter != edittext.end())   caret++, iter++;
                                break;
                                
                                case KEY_LEFT:
                                if(iter != edittext.begin()) caret--, iter--;
                                break;
                                
                                case KEY_INSERT:
                                if(insert) insert = 0; else insert = 1;
                                break;
                                
								case KEY_ENTER:
                                if(iter != edittext.begin())
								{
									//this give runtime error
									if(computerId==severId)
									{
										//need to put in life contter
									serverdiolog = edittext;
									outboxbuffer +="9999|" + NumberToString(computerId) + "|003|" + NumberToString(computerId) + "," + edittext +"`~";
									
									}
									else
									{
									//need somthing for sending msg to serten clients
									outboxbuffer +="0|" + NumberToString(computerId) + "|003|" + NumberToString(computerId) + "," + edittext +"`~";
									}
									tra=edittext.length();
									caret-=(tra);
									iter-=(tra);
									edittext.erase(0,tra+1);
									
								}
                                break;
                                default:
                                
                                break;
                        }
                }
 }               
                
 if(computerId!=severId)	
{
	 /*
	if (swing==true) //battle rig for test
	{
		if (targget > -1)
		{
outboxbuffer +="0|"+NumberToString(computerId)+"|002|"+NumberToString(computerId)+ ','+ NumberToString(logonUnits.Get_Unit( computerId )->Get_X())+','+ NumberToString(logonUnits.Get_Unit( computerId )->Get_Y())+
','+NumberToString(logonUnits.Get_Unit( computerId )->Get_X())+','+NumberToString(logonUnits.Get_Unit( computerId )->Get_Y())+
','+NumberToString(logonUnits.Get_Unit( computerId )->Get_direction() )+','+NumberToString(logonUnits.Get_Unit( computerId )->Get_frame())+','+NumberToString(logonUnits.Get_Unit( computerId )->Get_inarea())+"`~";
		outboxbuffer += "0|"+NumberToString(computerId)+"|008|"+NumberToString(computerId)+","+NumberToString(targget)+"`~";
		targget =-1	;
		}
		swing= false;
	}
	*/

}


if(computerId==severId)	
{	
	if (key[KEY_F11])
	{
		
		views[0].set_GRID_WIDTH(15);
		
	
	
		
		worlds.areas.layers.edit(views[0], animations ,data);
		views[0].set_GRID_WIDTH(20);
	}




}

if (key[KEY_LEFT]) 
			{
			views[0].do_scroll(LEFT);	//if (sx>1) sx--;
			}
			if (key[KEY_RIGHT]) 
			{
			views[0].do_scroll(RIGHT);	//if (sx<(WORLD_X-GRID4_WIDTH-1)) sx++;
			}
			if (key[KEY_UP]) 
			{
			views[0].do_scroll(UP);	//if (sy>1) sy--;
			}
			if (key[KEY_DOWN]) 
			{
			views[0].do_scroll(DOWN);	//if (sy<(WORLD_Y-GRID4_HEIGHT-1)) sy++;
			}


/*
if (mouse_x<14) 
		{	
			views[0].do_scroll(LEFT);
		}
		if (mouse_x>(SCREEN_W-10))
		{
			views[0].do_scroll(RIGHT);
		}
		if (mouse_y<11)
		{
			views[0].do_scroll(UP);
		}
		if (mouse_y>(SCREEN_H-10))
		{
			views[0].do_scroll(DOWN);
		}
*/

/*		
textprintf_centre(screen, font, SCREEN_W/2, 176, makecol(0, 0, 0),"x=%d, y=%d, z=%d", x, y, z);
for (int c=1; c<=5; c++) {
      textprintf_centre(screen, font, SCREEN_W/2, 62+c*10, makecol(0, 0, 0),x=%d, x);
      rest(1000);
   }
*/





//unscare_mouse();
/*


worlds.redraw(views, animations);
LOCK_VARIABLE(xt);
	LOCK_FUNCTION(inc_xt);

 	install_int(inc_xt, 1000);

	textprintf_centre(views[0].get_buffer(), font, SCREEN_W/2, 176, makecol(255, 255, 255),"%d", xt);
	if (timer  ==xt )
	{
		new_fps=fps;
		fps = 1;
		timer =1+ xt;

	}
	else
	{

		timer =1+ xt;
		fps++;
	}
//////////////////////////////////////////////////need to be in logic	
	textprintf_centre(views[0].get_buffer(), font, 40, 20, makecol(255, 255, 255),"FPS:%3d", new_fps);

*/
	if(graphic != false)
	{

		if(minconter==10)
		{
			updateMiniMap(1);
			updateMiniMap(2);
			updateMiniMap(3);
			minconter=0;
		}
		else
		{
			minconter++;
		}
			//if(onesecpased==logicsec)
			//{
}
			worlds.redraw(views, animations,logonUnits ,data);
			//logicsec=(!logicsec);	
			 //}
//fps++;
rest(2)	; //take 100%cpu or runs slow			
}
//////////////////////////////////////////////////////////////////////////////////////////////////////


//void Game::do_game_networking()



void Game::do_game_gfx()
{
	fps++;	
	/////////////////////////////////////////////need to be in logic	
	//if(cont==600000)
	//{
	//cont=0;
	drawMiniMap();
	if(text==true)
	{
	// clear screen
                //clear(buffer);
                
                // output the string to the screen
                textout(get_views()->get_buffer(), font, edittext.c_str(), x, 10, WHITE);
                
                // output some stats using Allegro's printf functions
                textprintf(get_views()->get_buffer(), font,  x, 20, WHITE, "length:   %d", edittext.length());
                textprintf(get_views()->get_buffer(), font,  x, 30, WHITE, "capacity: %d", edittext.capacity());
                textprintf(get_views()->get_buffer(), font,  x, 40, WHITE, "empty`:   %d", edittext.empty());
                if(insert)
                textout(get_views()->get_buffer(), font, "Inserting", x, 50, WHITE);
                else
                textout(get_views()->get_buffer(), font, "Replacing", x, 50, WHITE);
                
                // draw the caret
                vline(get_views()->get_buffer(), caret * 8, 8, 18, WHITE);

	}

	if(serverdiolog.length()<=30)
	{
		textout(views[0].get_buffer(),font,serverdiolog.c_str(),get_views()[0].get_screen_pos_x()+150,get_views()[0].get_screen_pos_y()+30,makecol(255,255,255));
	}
	else if(serverdiolog.length()> 30)
	{
		textout(views[0].get_buffer(),font,serverdiolog.substr(0,30).c_str(),get_views()[0].get_screen_pos_x()+150,get_views()[0].get_screen_pos_y()+30,makecol(255,255,255));
		textout(views[0].get_buffer(),font,serverdiolog.substr(31,serverdiolog.length()).c_str(),get_views()[0].get_screen_pos_x()+150,get_views()[0].get_screen_pos_y()+40,makecol(255,255,255));
	}
	LOCK_VARIABLE(xt);
	LOCK_FUNCTION(inc_xt);

 	install_int(inc_xt, 1000);
	if(debugmode==true)
	{
		textprintf_centre(views[0].get_buffer(), font, SCREEN_W/2, 176, makecol(255, 255, 255),"%d", xt);
	}
	if (timer  ==xt )
	{
		new_fps=fps;
		fps = 1;
		timer =1+ xt;
		if(onesecpased==false)
		{
			onesecpased=true;
		}
		else
		{
			onesecpased=false;
		}
	}
	else
	{

		timer =1+ xt;
		
	}
//////////////////////////////////////////////////need to be in logic
	if(debugmode==true)
	{
		textprintf_centre(views[0].get_buffer(), font, 40, 20, makecol(255, 255, 255),"FPS:%3d", new_fps);
		textprintf_centre(views[0].get_buffer(), font, 40, 30, makecol(255, 255, 255),"srX:%3d", views[0].get_screen_pos_x());
		textprintf_centre(views[0].get_buffer(), font, 40, 40, makecol(255, 255, 255),"srY:%3d", views[0].get_screen_pos_y());
	}
	masked_blit(GUI,views[0].get_buffer(),4,4,4,4,views[0].get_GRID_WIDTH()*32-8,views[0].get_GRID_HEIGHT()*32-8);
if(mousePointer==0)
{

show_mouse( views[0].get_buffer() );
}
else if(mousePointer==1)
{
scare_mouse();

draw_sprite(views[0].get_buffer(),(BITMAP*)data[XMARK].dat,mouse_x,mouse_y);

}
	
	

	blitBuffer(views[0].get_buffer());
	clear(GUI);
	do_trans3(GUI);
//}
//cont++;	
}



void Game::play_song(int s)
{
//	if (snd==0)
		play_midi((MIDI*)music[s].dat, TRUE);
}

void Game::play_sound(int s)
{
//	if (snd==0)
	play_sample((SAMPLE*)music[s].dat, 255, 128, 1000,FALSE);
}

void Game::stop_song()
{
	play_midi(NULL,FALSE);
} 

#endif

