/***********************************************************************
*Copyright (c)2012 , 天际边工作室wlo
*All rights reserved.
**
文件名称：	PublicFun.cpp
*摘要：		公用函数，全局函数
**
*修改历史：
*	版本    日期     作者     改动内容和原因
*   ----------------------------------------------------
*	1.0    2012-10-5  wstjb     基本的功能完成
***********************************************************************/

#include "PublicFun.h"
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <cstring>
#include <time.h>
#include "GameEng.h"

using namespace std;
extern Game game;
extern  PAINTSTRUCT ps;
extern 	HDC hdc;
extern 	HBITMAP hbmp; 
extern 	HBITMAP hbmp2; 
extern 	BITMAP bmp;
extern 	HDC hdcMem;
extern 	HDC hdcTmp;
extern 	RECT rect;
extern 	HWND hwnd;
extern  char texta[TEXTAMAX][20];
extern int color;
char strText[STRMAX][2][LINEMAX];
char t_str[48];
char t_heroName[HEROMAX][HERONAMEMAXLEN];
char t_skillName[SKILLMAX][SKILLNAMEMAXLEN];
char t_goodName[GOODMAX][GOODNAMEMAXLEN];
char t_cityName[CITYMAX][CITYNAMEMAXLEN];
int t_tile[MAPSUM][MAPMAX][MAPMAX];
int t_citymapnum[CITYMAX];
int t_tilestyle[TILEMAX];
//int t_movetilestyle[TILEMAX];
HFONT t_h;
HPEN t_hpen;
HBRUSH t_hbrush;

extern int KeyReturn;
extern int KeyEsc;
extern int KeyHome;
extern int KeySpace;
extern int KeyLeft0;
extern int KeyUp0;
extern int KeyRight0;
extern int KeyDown0;

extern char workpath[MAX_PATH];   
extern char absolutepath[MAX_PATH];

int periodinfo[PERIODMAX][PERIODLINEMAX];
int periodsum = 4;

/***********************************************************************
* 说明:    显示图片函数
* 输入参数: int delay——显示的时间长度,char *name——显示的图片文件名称,
int ux——显示的x坐标,int uy——显示的y坐标
* 返回值  : 无
* 功能	   : 显示图片
* 修改历史:
*               姓名            日期             说明
*             ------          ----------      -------------
*             wstjb          2012-10-5       完成基本功能
***********************************************************************/
void ShowCG(int delay,char *name,int ux,int uy)
{

	LoadPic(name,hbmp);	//封装完成

	//GetObject(hbmp, sizeof(BITMAP), &bmp);
	HBITMAP oldhbmp=(HBITMAP)SelectObject(hdcMem, hbmp);

	BitBlt(hdcTmp, ux, uy+50, 800, 480, hdcMem, 0, 0, SRCCOPY);
	SelectObject(hdcMem, oldhbmp);
	DeleteObject(hbmp);
	//BitBlt(hdc, 0, 0, 800, 600, hdcTmp, 0, 0, SRCCOPY);

	/*if (delay==-1)
	{
	Delay(2000);
	}
	else 
	{
	Delay(delay);
	}*/
	InvalidateRect(hwnd,&rect,false);
}

/***********************************************************************
* 说明:    直接显示图片函数
* 输入参数: int delay——显示的时间长度,char *name——显示的图片文件名称,
int ux——显示的x坐标,int uy——显示的y坐标
* 返回值  : 无
* 功能	   : 在HDC上直接显示图片
* 修改历史:
*               姓名            日期             说明
*             ------          ----------      -------------
*             wstjb          2012-10-13       完成基本功能
***********************************************************************/

void ShowCGDirect(int delay,char *name,int ux,int uy)
{
	LoadPic(name,hbmp2);	//封装完成

	//GetObject(hbmp, sizeof(BITMAP), &bmp);
	HBITMAP oldhbmp=(HBITMAP)SelectObject(hdcMem, hbmp2);

	BitBlt(hdcTmp, ux, uy+50, 800, 480, hdcMem, 0, 0, SRCCOPY);
	BitBlt(hdc, 0, 0, 800, 600, hdcTmp, 0, 0, SRCCOPY);
	SelectObject(hdcMem, oldhbmp);
	DeleteObject(hbmp2);
	if (delay==-1)
	{
		Delay(2000);
	}
	else 
	{
		Delay(delay);
	}

}

/***********************************************************************
* 说明:    开始游戏显示图片函数
* 输入参数: int delay——显示的时间长度,char *name——显示的图片文件名称,
int ux——显示的x坐标,int uy——显示的y坐标
* 返回值  : 无
* 功能	   : 开始游戏时直接显示图片
* 修改历史:
*               姓名            日期             说明
*             ------          ----------      -------------
*             wstjb          2012-10-13       完成基本功能
***********************************************************************/
void ShowCGStart(int delay,char *name,int ux,int uy)
{

	//HDC hdc2=GetDC(hwnd);
	LoadPic(name,hbmp2);	//封装完成

	//GetObject(hbmp, sizeof(BITMAP), &bmp);
	HBITMAP oldhbmp=(HBITMAP)SelectObject(hdcMem, hbmp2);

	BitBlt(hdc, ux, uy+50, 800, 480, hdcMem, 0, 0, SRCCOPY);
	//BitBlt(hdc, ux, uy+50, 800, 480, hdcMem, 0, 0, SRCCOPY);
	InvalidateRect(hwnd,NULL,TRUE);
	SelectObject(hdcMem, oldhbmp);
	DeleteObject(hbmp2);
	//ReleaseDC(hwnd,hdc2);
	if (delay==-1)
	{
		Delay(2000);
	}
	else 
	{
		Delay(delay);
	}

}

/***********************************************************************
* 说明:    显示图片函数
* 输入参数: int delay——显示的时间长度,char *name——显示的图片文件名称,
char *name1——显示的图片文件的掩膜图片的名称,
int ux——显示的x坐标,int uy——显示的y坐标
* 返回值  : 无
* 功能	   : 显示图片（透明化显示）
* 修改历史:
*               姓名            日期             说明
*             ------          ----------      -------------
*             wstjb          2012-10-5       完成基本功能
***********************************************************************/
void ShowCGAdd(int delay,char *name,char *name1,int ux,int uy)
{
	LoadPic(name1,hbmp);	//封装完成
	uy=uy+50;
	//GetObject(hbmp, sizeof(BITMAP), &bmp);
	HBITMAP oldhbmp=(HBITMAP)SelectObject(hdcMem, hbmp);
	BitBlt(hdcTmp, ux, uy, 800, 480, hdcMem, 0, 0, SRCPAINT);
	SelectObject(hdcMem, oldhbmp);
	DeleteObject(hbmp);
	LoadPic(name,hbmp);
	GetObject(hbmp, sizeof(BITMAP), &bmp);
	oldhbmp=(HBITMAP)SelectObject(hdcMem, hbmp);
	BitBlt(hdcTmp, ux, uy, 800, 480, hdcMem, 0, 0, SRCAND);
	SelectObject(hdcMem, oldhbmp);
	InvalidateRect(hwnd,&rect,false);
	DeleteObject(hbmp);
	/*if (delay==-1)
	{
	Delay(2000);
	}
	else 
	{
	Delay(delay);
	}*/

}



/***********************************************************************
* 说明:    加载图片函数
* 输入参数: char *name——显示的图片文件名称,HBITMAP &hbmp——图片dc
* 返回值  : 无
* 功能	   : 加密并加载图片
* 修改历史:
*               姓名            日期             说明
*             ------          ----------      -------------
*             wstjb          2012-10-5       完成基本功能
***********************************************************************/
void LoadPic(char *name,HBITMAP &hbmp)
{
	//ChangeFile(name);
	if(color==1)
	{
		name = replace(name,".sbp","_c.sbp");
	}
	hbmp = (HBITMAP)LoadImage(NULL, name, IMAGE_BITMAP,0,0, LR_LOADFROMFILE);
	if(color ==2)
	{
		/*BITMAP bm;
		GetObject(hbmp, sizeof(bm),(LPSTR)&bm);
		HBITMAP hbmpOld = (HBITMAP)SelectObject(hdcMem,hbmp);
	
		for(int i = 0 ; i < bm.bmWidth ;i++)
		{
			for(int  j = 0 ; j < bm.bmHeight ; j++)
			{
				COLORREF cr = ::GetPixel(hdcMem , i , j);
				int nR = GetRValue(cr);
				int nG = GetGValue(cr);
				int nB = GetBValue(cr);
 
				int nPer = int (nR * 0.299 + nG * 0.587 + nB * 0.114);
 
				cr = RGB(nPer,nPer ,nPer);
 
				::SetPixel(hdcMem ,i,j,cr);
			}
		}

		hbmp = (HBITMAP) SelectObject(hdcMem, hbmpOld);*/
 
	}
	
	//ChangeFile(name);	
}

char *replace(char *src, char *sub, char *dst)
{
	int pos =0;
	int offset =0;
	int srcLen, subLen, dstLen;
	char*pRet = NULL;


	srcLen = strlen(src);
	subLen = strlen(sub);
	dstLen = strlen(dst);
	pRet = (char*)malloc(srcLen + dstLen - subLen +1);//(外部是否该空间)if (NULL != pRet)
	{
		pos = strstr(src, sub) - src;
		memcpy(pRet, src, pos);
		offset += pos;
		memcpy(pRet + offset, dst, dstLen);
		offset += dstLen;
		memcpy(pRet + offset, src + pos + subLen, srcLen - pos - subLen);
		offset += srcLen - pos - subLen;
		*(pRet + offset) ='\0';
	}
	return pRet;
}

/***********************************************************************
* 说明:    图片加密函数
* 输入参数: char filename[]——图片文件名称
* 返回值  : 无
* 功能	   : 加密解密文件
* 修改历史:
*               姓名            日期             说明
*             ------          ----------      -------------
*             wstjb          2012-10-5       完成基本功能
***********************************************************************/
int ChangeFile(char filename[])
{
	fstream file(filename, ios::in | ios::out | ios::binary);
	if(file.fail())
		return -1;								// 表示打开文件时出错
	unsigned char c;
	for(int i=0;i<10;i++)
	{
		file.read((char*)&c, sizeof(char));
		c = (c & 0xF)<<4 | (c>>4);				// 字符 c 的高、低 4 位互换
		file.seekp(-1, ios::cur);				// 文件内容指针后退 1 字节
		file.write((char*)&c, sizeof(char));
	}

	file.close();
	return 0;									// 表示正常返回
}

/***********************************************************************
* 说明:    数据文件加密函数
* 输入参数: char *filename——数据文件名称
* 返回值  : 无
* 功能	   : 加密解密文件
* 修改历史:
*               姓名            日期             说明
*             ------          ----------      -------------
*             wstjb          2012-10-5       完成基本功能
***********************************************************************/
int ChangeRes(char *filename)
{
	int i,count,len;
	char buff[1024];
	static char tmpfile[]="ws.tmp";
	FILE * in , * out ;
	char key[]="wstjb";
	len =strlen(key);
	in =fopen(filename,"rb");
	out =fopen(tmpfile,"wb"); 

	while( !feof(in) )
	{
		count=fread(buff,1,1024,in);
		for(i=0;i <count;i++)
			buff[i]^=key[i%len];
		fwrite(buff,1,count,out);
	}

	fclose(in);
	fclose(out);
	remove(filename);
	rename(tmpfile,filename);

	return 0;		
}

/***********************************************************************
* 说明:    延时函数
* 输入参数: long time——延时等待的时间（毫秒）
* 返回值  : 无
* 功能	   : 延时等待
* 修改历史:
*               姓名            日期             说明
*             ------          ----------      -------------
*             wstjb          2012-10-5       完成基本功能
***********************************************************************/
void Delay(long time)
{
	static long old_clock, new_clock; //延时变量
	new_clock=old_clock=GetTickCount();
	while( new_clock < old_clock + time )
	{
		new_clock=GetTickCount();
		CheckSysMsg();
		Sleep(1);
	}
}

void CheckSysMsg()
{

	MSG msg;
	if(PeekMessage(&msg,NULL,0,0,PM_NOREMOVE))
	{
		if(GetMessage(&msg,NULL,0,0)) return;
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

}

/***********************************************************************
* 说明:    文本显示函数
* 输入参数: char *text——显示的内容,int x——显示的x坐标,
int y——显示的y坐标,int size——文字大小
* 返回值  : 无
* 功能	   : 显示文本
* 修改历史:
*               姓名            日期             说明
*             ------          ----------      -------------
*             wstjb          2012-10-5       完成基本功能
***********************************************************************/
void ShowText(char *text,int x,int y,int size)
{
	MyCreateFont((double)(((double)size)/50.0));
	HFONT	h = t_h;
	HFONT oldh=(HFONT)SelectObject(hdcTmp,h);
	MySetTextColor(FONTA,USEHDCTMP);

	if(color == 0)
	{

		TextOut(hdcTmp,x,y,text,strlen(text));
		InvalidateRect(hwnd,NULL,FALSE);
		SelectObject(hdcTmp,oldh); 
		DeleteObject(h);

	}
	else
	{

		TextOut(hdcTmp,x,y,text,strlen(text));
		InvalidateRect(hwnd,NULL,FALSE);
		SelectObject(hdcTmp,oldh); 
		DeleteObject(h);
	}
	SetTextColor(hdcTmp,RGB(0, 0, 0));
}

void ShowTextDirect(char *text,int x,int y,int size)
{
	MyCreateFont((double)(((double)size)/50.0));
	HFONT	h = t_h;
	HFONT oldh=(HFONT)SelectObject(hdc,h);
	MySetTextColor(FONTA,USEHDC);

	if(color == 0)
	{

		TextOut(hdc,x,y,text,strlen(text));
		InvalidateRect(hwnd,NULL,FALSE);
		SelectObject(hdc,oldh); 
		DeleteObject(h);
	}
	else
	{

		TextOut(hdc,x,y,text,strlen(text));
		InvalidateRect(hwnd,NULL,FALSE);
		SelectObject(hdc,oldh); 
		DeleteObject(h);
	}
	SetTextColor(hdc,RGB(0, 0, 0));
}

void ShowTextDirectWithColor(char *text,int x,int y,int size)
{
	MyCreateFont((double)(((double)size)/50.0));
	HFONT	h = t_h;
	HFONT oldh=(HFONT)SelectObject(hdc,h);
	MySetTextColor(FONTB,USEHDC);
	if(color == 0)
	{

		TextOut(hdc,x,y,text,strlen(text));
		InvalidateRect(hwnd,NULL,FALSE);
		SelectObject(hdc,oldh); 
		DeleteObject(h);
	}
	else
	{

		TextOut(hdc,x,y,text,strlen(text));
		InvalidateRect(hwnd,NULL,FALSE);
		SelectObject(hdc,oldh); 
		DeleteObject(h);
	}
	SetTextColor(hdc,RGB(0, 0, 0));
}

/***********************************************************************
* 说明:    获取文本函数
* 输入参数: char *filename——文件名称
* 返回值  : 无
* 功能	   : 获取文本内容
* 修改历史:
*               姓名            日期             说明
*             ------          ----------      -------------
*             wstjb          2012-10-5       完成基本功能
***********************************************************************/
int GetFileText(char *filename)
{
	ifstream infile(filename,ios::in);
	char *c=new char[20];
	int i=0;
	while(infile.getline(c,20,'\n'))
	{	
		for(int j=0;j<20;j++)
		{
			texta[i][j]=c[j];
		}
		i++;
	}
	infile.close();

	return i;
}

/***********************************************************************
* 说明:    消息显示函数
* 输入参数: char *text——显示的消息,int posx——左上角x坐标,
int posy——左上角y坐标,int ux——宽度,int uy——高度
* 返回值  : 无
* 功能	   : 获取文本内容
* 修改历史:
*               姓名            日期             说明
*             ------          ----------      -------------
*             wstjb          2012-10-5       完成基本功能
***********************************************************************/
void Message(char *text,int posx,int posy,int ux,int uy)
{
	MyCreateFont(0.9);
	HFONT	h = t_h;
	HFONT oldh=(HFONT)SelectObject(hdcTmp,h);
	MySetTextColor(FONTA,USEHDCTMP);


	if(color==0)
	{
		MySetShowStyle();
		HPEN hpen=t_hpen;
		HPEN oldhpen=(HPEN)SelectObject(hdcTmp,hpen);

		HBRUSH hbrush = t_hbrush;
		HBRUSH hbrold = (HBRUSH)SelectObject(hdcTmp, hbrush); 


		Rectangle(hdcTmp,posx,posy,posx+ux*60,posy+uy*60); 	
		SelectObject(hdcTmp,oldhpen);
		DeleteObject(hpen);		

		TextOut(hdcTmp,posx+5,posy+5,text,strlen(text));
		SelectObject(hdcTmp,oldh);	
		DeleteObject(h);		
		InvalidateRect(hwnd,NULL,false);	
	}
	else
	{
		ShowCG(0,"Res\\messageback.sbp",posx,posy-50);


		TextOut(hdcTmp,posx+5,posy+5,text,strlen(text));
		SelectObject(hdcTmp,oldh);	
		DeleteObject(h);		
		InvalidateRect(hwnd,NULL,false);	

	}
	SetTextColor(hdcTmp,RGB(0, 0, 0));

}

void TimerMessage(char *name,char *text,int posx,int posy,int ux,int uy,int delay)
{
	MyCreateFont(1.0);
	HFONT	h = t_h;
	HFONT oldh=(HFONT)SelectObject(hdc,h);
	MySetTextColor(FONTA,USEHDC);

	if(color==0)
	{
		MySetShowStyle();
		HPEN hpen=t_hpen;
		HPEN oldhpen=(HPEN)SelectObject(hdc,hpen);


		Rectangle(hdc,posx,posy,posx+ux*60,posy+uy*60);
		SelectObject(hdc,oldhpen);
		DeleteObject(hpen);




		TextOut(hdc,posx+5,posy+5,name,strlen(name));
		TextOut(hdc,posx+40+strlen(name)*25,posy+5,text,strlen(text));
		InvalidateRect(hwnd,NULL,TRUE);

		SelectObject(hdc,oldh);

		DeleteObject(h);		
	}
	else
	{
		ShowCGDirect(0,"Res\\messageback.sbp",posx-20,posy-50);


		SetTextColor(hdc,RGB(255, 255, 255));
		TextOut(hdc,posx+5,posy+5,name,strlen(name));
		TextOut(hdc,posx+40+strlen(name)*25,posy+5,text,strlen(text));
		InvalidateRect(hwnd,NULL,TRUE);

		SelectObject(hdc,oldh);

		DeleteObject(h);		
	}
	SetTextColor(hdc,RGB(0, 0, 0));
	Delay(delay);

}

void TimerMessagePlus(char *text1,char *text2,char *text3,int posx,int posy,int ux,int uy,int delay)
{
	MyCreateFont(1.0);
	HFONT	h = t_h;
	HFONT oldh=(HFONT)SelectObject(hdc,h);
	MySetTextColor(FONTA,USEHDC);

	if(color==0)
	{
		MySetShowStyle();
		HPEN hpen=t_hpen;
		HPEN oldhpen=(HPEN)SelectObject(hdc,hpen);

		Rectangle(hdc,posx,posy,posx+ux*60,posy+uy*60);
		SelectObject(hdc,oldhpen);
		DeleteObject(hpen);


		TextOut(hdc,posx+5,posy+5,text1,strlen(text1));
		TextOut(hdc,posx+40+strlen(text1)*25,posy+5,text2,strlen(text2));
		TextOut(hdc,posx+75+strlen(text1)*25+strlen(text2)*25,posy+5,text3,strlen(text3));
		InvalidateRect(hwnd,NULL,TRUE);

		SelectObject(hdc,oldh);

		DeleteObject(h);	
	}
	else
	{
		ShowCGDirect(0,"Res\\messageback.sbp",posx-20,posy-50);

		TextOut(hdc,posx+5,posy+5,text1,strlen(text1));
		TextOut(hdc,posx+40+strlen(text1)*25,posy+5,text2,strlen(text2));
		TextOut(hdc,posx+75+strlen(text1)*25+strlen(text2)*25,posy+5,text3,strlen(text3));
		InvalidateRect(hwnd,NULL,TRUE);

		SelectObject(hdc,oldh);

		DeleteObject(h);	

	}
	SetTextColor(hdc,RGB(0, 0, 0));
	Delay(delay);

}

void TimerMessageCF(char *name,char *text,int posx,int posy,int ux,int uy,int delay)
{
	MyCreateFont(1.0);
	HFONT	h = t_h;
	HFONT oldh=(HFONT)SelectObject(hdc,h);
	MySetTextColor(FONTA,USEHDC);

	if(color==0)
	{
		MySetShowStyle();
		HPEN hpen=t_hpen;
		HPEN oldhpen=(HPEN)SelectObject(hdc,hpen);

		Rectangle(hdc,posx,posy,posx+ux*60,posy+uy*60);
		SelectObject(hdc,oldhpen);
		DeleteObject(hpen);
	}
	else
	{
		ShowCGDirect(0,"Res\\messageback.sbp",posx-20,posy-50);
	}

	TextOut(hdc,posx+5,posy+5,name,strlen(name));
	TextOut(hdc,posx+125,posy+5,text,strlen(text));
	InvalidateRect(hwnd,NULL,TRUE);
	SelectObject(hdc,oldh);
	DeleteObject(h);		
	Delay(delay);

}

void TimerMessageGS(char *name,char *text,char *text1,int posx,int posy,int ux,int uy,int delay)
{
	MyCreateFont(1.0);
	HFONT	h = t_h;
	HFONT oldh=(HFONT)SelectObject(hdc,h);
	MySetTextColor(FONTA,USEHDC);

	if(color==0)
	{
		MySetShowStyle();
		HPEN hpen=t_hpen;
		HPEN oldhpen=(HPEN)SelectObject(hdc,hpen);

		Rectangle(hdc,posx,posy,posx+ux*60,posy+uy*60);
		SelectObject(hdc,oldhpen);
		DeleteObject(hpen);
	}
	else
	{
		ShowCGDirect(0,"Res\\messageback.sbp",posx-20,posy-50);
	}

	TextOut(hdc,posx+5,posy+5,text,strlen(text));
	TextOut(hdc,posx+135,posy+5,name,strlen(name));
	TextOut(hdc,posx+375,posy+5,text1,strlen(text1));
	InvalidateRect(hwnd,NULL,TRUE);
	SelectObject(hdcTmp,oldh);
	DeleteObject(h);		
	Delay(delay);

}

int PlcExtract(int num)//求平方根
{
	int	gen,step;
	int	tcnt;

	gen = 0;
	step = 10;
	while(1)
	{
		if(!step) break;
		tcnt = gen + step;
		if((int)tcnt * tcnt < num)
			gen = tcnt;
		else
			step -= 1;		
	}
	return gen;
}

void wlogfile(int type,char *infun,char *inmsg,int result)
{
	char filename[100];
	char filename1[200];
	char now[30];
	memset(filename,0,sizeof(filename));
	memset(filename1,0,sizeof(filename1));
	memset(now,0,sizeof(now));
	time_t tt = time(NULL);
	tm* t= localtime(&tt);
	sprintf_s(now,"%d-%02d-%02d %02d:%02d:%02d", 
		t->tm_year + 1900,
		t->tm_mon + 1,
		t->tm_mday,
		t->tm_hour,
		t->tm_min,
		t->tm_sec);
	sprintf_s(filename,"Res\\Log\\%d%02d%02d.log",t->tm_year + 1900,t->tm_mon + 1, t->tm_mday);


	if(type == 5)//清理现有日志
	{
		sprintf_s(filename1,"Res\\Log\\Err\\%d%02d%02d%02d%02d%02d.log",t->tm_year + 1900,t->tm_mon + 1, t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
		MoveFile(filename,filename1);
		type = 1;
	}
	ofstream outfile(filename,ios::app|ios::out);
	if(result != 0)
	{
		if(type == 1)
		{
			outfile<<now<<":"<<":常规:"<<infun<<inmsg<<":"<<result<<endl;
		}
		else if(type == 2)
		{
			outfile<<now<<":"<<":错误:"<<infun<<inmsg<<":"<<result<<endl;
		}
		else if(type == 3)
		{
			outfile<<now<<":"<<":测试:"<<infun<<inmsg<<":"<<result<<endl;
		}
	}
	else
	{
		if(type == 1)
		{
			outfile<<now<<":"<<":常规:"<<infun<<inmsg<<endl;
		}
		else if(type == 2)
		{
			outfile<<now<<":"<<":错误:"<<infun<<inmsg<<endl;
		}
		else if(type == 3)
		{
			outfile<<now<<":"<<":测试:"<<infun<<inmsg<<endl;
		}
	}
	outfile.close();
}

void DeleteLog()
{
	char filename[100];
	char filename1[200];
	char now[30];
	memset(filename,0,sizeof(filename));
	memset(filename1,0,sizeof(filename1));
	memset(now,0,sizeof(now));
	time_t tt = time(NULL);
	tm* t= localtime(&tt);
	sprintf_s(now,"%d-%02d-%02d %02d:%02d:%02d", 
		t->tm_year + 1900,
		t->tm_mon + 1,
		t->tm_mday,
		t->tm_hour,
		t->tm_min,
		t->tm_sec);
	sprintf_s(filename,"Res\\Log\\%d%02d%02d.log",t->tm_year + 1900,t->tm_mon + 1, t->tm_mday);
	DeleteFile(filename);
}

LONG WINAPI TopLevelExceptionFilter(struct _EXCEPTION_POINTERS *pExceptionInfo)  
{
	//存崩溃存档
	game.newgame.who.gamemap.ChangeDataToSave();	
	game.newgame.who.gamemap.save.Write(9);

	//printStack() ;
	char filename1[500];
	char now[30];
	time_t tt = time(NULL);
	tm* t= localtime(&tt);
	sprintf_s(now,"%d-%02d-%02d %02d:%02d:%02d", 
		t->tm_year + 1900,
		t->tm_mon + 1,
		t->tm_mday,
		t->tm_hour,
		t->tm_min,
		t->tm_sec);
	wlogfile(1, "TopLevelExceptionFilter" ,"Enter TopLevelExceptionFilter Function",0); 

	TCHAR szPath[MAX_PATH];
	if( !GetModuleFileName( NULL, szPath, MAX_PATH ) )
	{
		wlogfile(2, "TopLevelExceptionFilter" ,"GetModuleFileName failed (%d)",GetLastError()); 
	}
	char *p = strrchr(szPath, '\\');  
	*p=0x00;  

	memset(filename1,0,sizeof(filename1));
	sprintf_s(filename1,"%s\\Res\\Log\\%d%02d%02d%02d%02d%02d.dmp",szPath,t->tm_year + 1900,t->tm_mon + 1, t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);

	HANDLE hFile = CreateFile(filename1,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);  
	MINIDUMP_EXCEPTION_INFORMATION stExceptionParam;  
	stExceptionParam.ThreadId    = GetCurrentThreadId();  
	stExceptionParam.ExceptionPointers = pExceptionInfo;  
	stExceptionParam.ClientPointers    = FALSE;  
	MiniDumpWriteDump(GetCurrentProcess(),GetCurrentProcessId(),hFile,MiniDumpNormal,&stExceptionParam,NULL,NULL);  
	CloseHandle(hFile);  

	//调用崩溃程序 包括以下信息 dmp save log 
	char execcmd[500];
	memset(execcmd,0,sizeof(execcmd));

	sprintf_s(execcmd,"CrashReport.exe 天际边三国霸业 %s 天际边三国霸业错误报告 %s",filename1,"save");
	//程序名 dmp文件名 标题

	STARTUPINFO si; //一些必备参数设置  
	memset(&si, 0, sizeof(STARTUPINFO));  
	si.cb = sizeof(STARTUPINFO);  
	si.dwFlags = STARTF_USESHOWWINDOW;  
	si.wShowWindow = SW_SHOW;  
	PROCESS_INFORMATION pi; //必备参数设置结束  
	CreateProcess(NULL,execcmd,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi);


	return EXCEPTION_EXECUTE_HANDLER;
}

void printStack()  
{  
	char filename[200];
	char word[300];
	char now[30];
	memset(filename,0,sizeof(filename));

	memset(now,0,sizeof(now));
	time_t tt = time(NULL);
	tm* t= localtime(&tt);
	sprintf_s(now,"%d-%02d-%02d %02d:%02d:%02d", 
		t->tm_year + 1900,
		t->tm_mon + 1,
		t->tm_mday,
		t->tm_hour,
		t->tm_min,
		t->tm_sec);
	sprintf_s(filename,"Res\\Log\\%d%02d%02d.log",t->tm_year + 1900,t->tm_mon + 1, t->tm_mday);

	unsigned int   i;  
	void         * stack[ 100 ];  
	unsigned short frames;  
	SYMBOL_INFO  * symbol;  
	HANDLE         process;  

	process = GetCurrentProcess();  

	SymInitialize( process, NULL, TRUE );  

	frames               = CaptureStackBackTrace( 0, 100, stack, NULL );  
	symbol               = ( SYMBOL_INFO * )calloc( sizeof( SYMBOL_INFO ) + 256 * sizeof( char ), 1 );  
	symbol->MaxNameLen   = 255;  
	symbol->SizeOfStruct = sizeof( SYMBOL_INFO );  

	ofstream outfile(filename,ios::app|ios::out);

	for( i = 0; i < frames; i++ )  
	{  
		SymFromAddr( process, ( DWORD64 )( stack[ i ] ), 0, symbol );  

		sprintf(word, "%i: %s - 0x%0X\n", frames - i - 1, symbol->Name, symbol->Address );  
		outfile<<word<<endl;
	}  

	free( symbol );  
	outfile.close();
}  

int InitStrText()
{
	char name[NORMALSTRLEN];
	memset(strText,0,sizeof(strText));
	sprintf_s(name,"%s","Res\\const.sss");

	ifstream infile(name,ios::in);
	char *c=new char[LINEMAX+1];
	int i = 0;
	while(infile.getline(c,100,'\n'))
	{	
		char *tokenPtr=strtok(c,"=");
		sprintf_s(strText[i][0],"%s",tokenPtr);
		tokenPtr=strtok(NULL,"");
		sprintf_s(strText[i][1],"%s",tokenPtr);
		i++;
	}
	infile.close();


	return 0;
}

char *GetStrText(char *strid)
{
	for(int i = 0 ; i < STRMAX ; i++)
	{
		if(strcmp(strText[i][0], strid)==0)
		{
			return strText[i][1];
		}
	}
	return "";

}

char *GetStrTextSpilted(char *strid,int pos,int len)
{

	memset(t_str,0,sizeof(t_str));
	for(int i = 0 ; i < STRMAX ; i++)
	{
		if(strcmp(strText[i][0], strid)==0)
		{
			strncpy_s(t_str,strText[i][1]+pos*len*2,len*2);
			t_str[len*2]='\0';
			return t_str;
		}
	}
	return "";

}

int InitSSS(int choice)
{
	wlogfile(1,__FUNCTION__,"开始",0);
	char name[NORMALSTRLEN];
	memset(name,0,sizeof(name));
	sprintf_s(name,"%s%d%s","Res\\Hero\\heroname",choice+1,".sss");

	ifstream infile(name,ios::in);
	char *c=new char[HERONAMEMAXLEN];
	int i=0;
	while(infile.getline(c,HERONAMEMAXLEN,'\n'))
	{	
		for(int j=0;j<HERONAMEMAXLEN;j++)
		{
			t_heroName[i][j]=c[j];
		}
		i++;
	}
	infile.close();

	memset(name,0,sizeof(name));
	sprintf_s(name,"%s","Res\\goods.sss");

	ifstream infile1(name,ios::in);
	char *c1=new char[GOODNAMEMAXLEN];
	i=0;
	while(infile1.getline(c1,GOODNAMEMAXLEN,'\n'))
	{	
		for(int j=0;j<GOODNAMEMAXLEN;j++)
		{
			t_goodName[i][j]=c1[j];
		}
		i++;
	}
	infile1.close();

	memset(name,0,sizeof(name));
	sprintf_s(name,"%s","Res\\skill.sss");

	ifstream infile2(name,ios::in);
	char *c2=new char[SKILLNAMEMAXLEN];
	i=0;
	while(infile2.getline(c2,SKILLNAMEMAXLEN,'\n'))
	{	
		for(int j=0;j<SKILLNAMEMAXLEN;j++)
		{
			t_skillName[i][j]=c2[j];
		}
		i++;
	}
	infile2.close();

	memset(name,0,sizeof(name));
	sprintf_s(name,"%s","Res\\citynamebylist.sss");

	ifstream infile3(name,ios::in);
	char *c3=new char[CITYNAMEMAXLEN];
	i=0;
	while(infile3.getline(c3,CITYNAMEMAXLEN,'\n'))
	{	
		for(int j=0;j<CITYNAMEMAXLEN;j++)
		{
			t_cityName[i][j]=c3[j];
		}
		i++;
	}
	infile3.close();

	return 0;
}

int InitTileInfo()
{
	wlogfile(1,__FUNCTION__,"开始",0);
	char name[NORMALSTRLEN];
	//int citymapnum[CITYMAX];
	for(int i = 0 ; i < CITYMAX ; i ++)
	{
		t_citymapnum[i] = 0;
	}
	sprintf_s(name,"%s","Res\\Fight\\fightmapid.sdt");
	ifstream infile1(name,ios::in);
	int i_t = 0;
	int i_tmp;
	while(infile1>>t_citymapnum[i_t])
	{
		i_t ++;
	}
	infile1.close();

	sprintf_s(name,"%s","Res\\Fight\\fightmapstyle.sdt");
	ifstream infile2(name,ios::in);
	i_t = 0;
	while(infile2>>i_tmp)
	{
		infile2>>t_tilestyle[i_t];
		i_t ++;
	}
	infile2.close();

	//={6,0,1,6,3,4,2,5,6,3,1,0,2,3,4,0,2,1,4,6,1,1,3,5,6,6,3,3,4,2,6,6,1,2,3,4,5,1};
	int retch=0;
	for(int retch = 0 ; retch < MAPSUM ; retch ++)
	{

		sprintf_s(name,"%s%02d%s","Res\\Fight\\fightmap",retch,".sdt");

		ifstream infile(name,ios::in);

		for(int g=0;g<MAPMAX;g++)
		{
			for(int h=0;h<MAPMAX;h++)
			{			
				infile>>t_tile[retch][g][h];
			}
		}
		infile.close();
	}
	return 0;
}

/*int InitMoveCal()
{

char name[NORMALSTRLEN];

int i_tmp = 0;

sprintf_s(name,"%s","Res\\Fight\\fightland.sdt");
ifstream infile2(name,ios::in);
int i_t = 0;
while(infile2>>i_tmp)
{
infile2>>t_movetilestyle[i_t];
i_t ++;
}
infile2.close();


return 0;
}*/

void MyCreateFont(double times)
{

	if(color==COLORVERSION)
	{		
		int fontSize=GetPrivateProfileInt("Font", "CFontSize", 50, absolutepath );
		fontSize = (int)((double)fontSize * times);
		char font[10];
		GetPrivateProfileString("Font", "CFont", "隶书", font, sizeof(font),  absolutepath);  
		t_h = CreateFont(fontSize,0,0,0,FW_BLACK,0,FALSE,FALSE, 
			GB2312_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,
			DEFAULT_QUALITY,FIXED_PITCH|FF_MODERN,font); 
		//SetTextColor(hdcTmp,RGB(255, 255, 255));

	}
	else
	{
		int fontSize=GetPrivateProfileInt("Font", "BFontSize", 50, absolutepath );
		fontSize = (int)((double)fontSize * times);
		char font[10];
		GetPrivateProfileString("Font", "BFont", "黑体", font, sizeof(font),  absolutepath);  
		t_h = CreateFont(fontSize,0,0,0,FW_BLACK,0,FALSE,FALSE, 
			GB2312_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,
			DEFAULT_QUALITY,FIXED_PITCH|FF_MODERN,font); 
	}
}

void MySetTextColor(int id,int type)
{
	int fontR=0;
	int fontG=0;
	int fontB=0;
	if(color==COLORVERSION)
	{		
		if(id==FONTA)
		{
			fontR=GetPrivateProfileInt("Font", "CFontR0", 50, absolutepath );
			fontG=GetPrivateProfileInt("Font", "CFontG0", 50, absolutepath );
			fontB=GetPrivateProfileInt("Font", "CFontB0", 50, absolutepath );

		}
		else
		{
			fontR=GetPrivateProfileInt("Font", "CFontR1", 50, absolutepath );
			fontG=GetPrivateProfileInt("Font", "CFontG1", 50, absolutepath );
			fontB=GetPrivateProfileInt("Font", "CFontB1", 50, absolutepath );

		}
	}
	else
	{
		if(id==FONTA)
		{
			fontR=GetPrivateProfileInt("Font", "BFontR0", 50, absolutepath );
			fontG=GetPrivateProfileInt("Font", "BFontG0", 50, absolutepath );
			fontB=GetPrivateProfileInt("Font", "BFontB0", 50, absolutepath );

		}
		else
		{
			fontR=GetPrivateProfileInt("Font", "BFontR1", 50, absolutepath );
			fontG=GetPrivateProfileInt("Font", "BFontG1", 50, absolutepath );
			fontB=GetPrivateProfileInt("Font", "BFontB1", 50, absolutepath );

		}
	}

	if(type== USEHDC)
	{
		SetTextColor(hdc,RGB(fontR,fontG,fontB));
	}
	else
	{
		SetTextColor(hdcTmp,RGB(fontR,fontG,fontB));
	}
}

void MySetShowStyle()
{

	if(color==COLORVERSION)
	{		

		int lineSize=GetPrivateProfileInt("ShowStyle", "CLineSize", 5, absolutepath );
		int lineR=GetPrivateProfileInt("ShowStyle", "CLineR", 180, absolutepath );
		int lineG=GetPrivateProfileInt("ShowStyle", "CLineG", 106, absolutepath );
		int lineB=GetPrivateProfileInt("ShowStyle", "CLineB", 41, absolutepath );
		int backR=GetPrivateProfileInt("ShowStyle", "CBackR", 198, absolutepath );
		int backG=GetPrivateProfileInt("ShowStyle", "CBackG", 151, absolutepath );
		int backB=GetPrivateProfileInt("ShowStyle", "CBackB", 81, absolutepath );
		t_hpen=CreatePen(PS_SOLID,lineSize, RGB(lineR,lineG,lineB));
		t_hbrush = CreateSolidBrush(RGB(backR,backG,backB)); 

	}
	else
	{

		int lineSize=GetPrivateProfileInt("ShowStyle", "BLineSize", 5, absolutepath );
		int lineR=GetPrivateProfileInt("ShowStyle", "BLineR", 0, absolutepath );
		int lineG=GetPrivateProfileInt("ShowStyle", "BLineG", 0, absolutepath );
		int lineB=GetPrivateProfileInt("ShowStyle", "BLineB", 0, absolutepath );
		int backR=GetPrivateProfileInt("ShowStyle", "BBackR", 255, absolutepath );
		int backG=GetPrivateProfileInt("ShowStyle", "BBackG", 255, absolutepath );
		int backB=GetPrivateProfileInt("ShowStyle", "BBackB", 255, absolutepath );
		t_hpen=CreatePen(PS_SOLID,lineSize, RGB(lineR,lineG,lineB));
		t_hbrush = CreateSolidBrush(RGB(backR,backG,backB)); 

	}

}

void OverflowCheck(char *file,int line,int max,int cur)
{
	if(cur <0 || cur >=max)
	{
		wlogfile(3,"OverflowCheck ",file,line);
		wlogfile(3,"OverflowCheck ","",max);
		wlogfile(3,"OverflowCheck ","",cur);
	}
	return;
}

void SetEnableDebug()
{
	HMENU hMenu = GetMenu(hwnd);
	HMENU hSubMenu = GetSubMenu(hMenu,2);

	EnableMenuItem ( hSubMenu,IDM_DEBUG,MF_ENABLED  );

	DeleteObject(&hSubMenu);
	DeleteObject(&hMenu);
}

/***********************************************************************
 * 说明:    Who类获取数据函数
 * 输入参数: 无
 * 返回值  : 无
 * 功能	   : 用于对君主选择时获取城市所属数据
 * 修改历史:
 *               姓名            日期             说明
 *             ------          ----------      -------------
 *             wstjb          2012-10-5       完成基本功能
***********************************************************************/
void GetLine(char *name,int num,int datab[],int datac[])
{
	wlogfile(1,__FUNCTION__,"开始",0);
				int j=0;
				//ChangeRes(name);
				ifstream infile(name,ios::in);
				while(infile>>datab[0])
				{
					int i=0;
					while(i<datab[0])
					{
						infile>>datac[i];
						i++;
					}
					j++;
					if((j-1)==num)break;

				}
				infile.close();
				//ChangeRes(name);
	
}


/***********************************************************************
 * 说明:    Who类获取数据函数
 * 输入参数: 无
 * 返回值  : 无
 * 功能	   : 用于对君主选择时获取城市所属数据
 * 修改历史:
 *               姓名            日期             说明
 *             ------          ----------      -------------
 *             wstjb          2012-10-5       完成基本功能
***********************************************************************/
void GetStore(char *name,int dataa[])
{
	wlogfile(1,__FUNCTION__,"开始",0);
				//ChangeRes(name);
				ifstream infile(name,ios::in);
				for(int i=0;i<TEXTAMAX;i++)
				{
						infile>>dataa[i];

				}
				infile.close();
				//ChangeRes(name);
	
}

void GetPeriodInfo()//获取时期信息
{
	wlogfile(1,__FUNCTION__,"开始",0);
	char name[NORMALSTRLEN];
	//int citymapnum[CITYMAX];
	for(int i = 0 ; i < PERIODMAX ; i ++)
	{
		for(int j = 0 ; j < PERIODLINEMAX ; j ++)
		{
			periodinfo[i][j] = 0;
		}
	}
	sprintf_s(name,"%s","Res\\period.sdt");
	ifstream infile1(name,ios::in);
	int i_t = 0;
	int i_tmp;
	infile1>>periodsum;
	for(int i = 0 ; i < periodsum ; i ++)
	{
		for(int j = 0 ; j < PERIODLINEMAX ; j ++)
		{
			infile1>>periodinfo[i][j];
		}
	}
	infile1.close();
}
char *GetVersionInfo()
{
	
	OSVERSIONINFO osvi;
	ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
	if (!GetVersionEx(&osvi)) {
		return NULL;
	}

	//判断版本
	if (osvi.dwMajorVersion == 5) 
	{

		switch (osvi.dwMinorVersion) 
		{
		case 0:
			return "Windows 2000";
		case 1:
			return "Windows XP";
		case 2:
			return "Windows Server 2003";
		default:
			return "Unknown System";
		}

	}
	else if (osvi.dwMajorVersion == 6) 
	{
		
		switch (osvi.dwMinorVersion) 
		{
		case 0:
			return "Windows Vista";
		case 1:
			return "Windows 7";
		case 2:
			return "Windows 8 or higher";
		case 3:
			return "Windows 8.1";
		default:
			return "Unknown System";
		}

	}
	else if (osvi.dwMajorVersion == 10) 
	{
		
		switch (osvi.dwMinorVersion) 
		{
		case 0:
			return "Windows 10";
		default:
			return "Unknown System";
		}

	}
	else {
		return "Unknown System";
	}
}