/*
 Libs:
 -lopengl32
 -lglu32 
 -lgdi32
 -lwinmm
 -mwindows
 -loleaut32
 -luuid
 -lgdiplus
*/

/**************************
 * Includes
 *
 **************************/

#include <windows.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glext.h>
#include "wglext.h"// https://khronos.org/registry/OpenGL/api/GL/wglext.h

#include <olectl.h>// Заголовочный файл для библиотеки
                   // управляющих элементов OLE (используется в BuildTexture)

#include <gdiplus/gdiplus.h>

#include "resource.h"

/**************************
 * Function Declarations
 *
 **************************/

float light_pos;
int light_d;
int gx=8,gy=8,lx=8,ly=8;
int state=0, stateCPU=0, sel_x=-1, sel_y=-1, sel_x0=-1, sel_y0=-1;
float move_sx, move_sy, move_sa=0.1f;
bool move1=false;

float leaps_stay=0.0f;
int leaps_c=-1, leaps_n=0;
int leaps_x [100];
int leaps_y [100];
int leaps_x1 [100];
int leaps_y1 [100];

int side=0;
int res=0;

int move_x1, move_y1, move_x2, move_y2;

int lang=0;// Ru, 1 - En
int sleepTime=50;
long stats_wins=0, stats_loses=0, stats_draws=0, stats_restart=0, stats_notfin=0, stats_moves=0;

bool square_white=false, square_black=false;


float bgAngle=0.0f;
float pLoad=150.0f, pLoad0=150.0f;
float loadAngleStep=1.0f;
float loadAngle=0.0f-pLoad*loadAngleStep;
float loadFarStep=0.1f;
float loadFar=-pLoad*loadFarStep;
  int pC=0;
  int sndVol=0, melVol=0;
  int qC=0, qCmx=4;
float rvSteps=255.0f/2.5f;
float rvAngle, moveAngle;

  int cx, cy;
  int posX=0, posY=0, posHL=1;
  int posXl=-1, posYl=-1;
  int mXar0 [10], mYar0 [10];
  int mXar1 [10]={0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, mYar1 [10]={0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  int mXar [10], mYar [10];
  int cCPU=0, cPlayer=0;
  int button=0;
float colorCoordHL [4]={0.0f, 0.0f, 0.0f}, colorCoordX [4]={0.0f, 0.0f, 1.0f}, colorCoordY [4]={0.5f, 0.25f, 0.0f},
      colorCellHL2 [4]={0.0f, 0.75f, 0.0f}, colorCellHL1 [4]={0.5f, 0.25f, 1.0f}, colorCellHL0 [4]={1.0f, 0.0f, 0.0f},
      colorCellOff [4]={1.0f, 0.8f, 0.1f},
      colorPlayer [4]={0.55f, 1.0f, 0.55f}, colorCPU [4]={0.65f, 0.35f, 0.05f},
      colorPlayerStat [4]={0.55f, 1.0f, 0.55f}, colorCPUStat [4]={0.65f, 0.35f, 0.05f},
      colorVol [4]={0.95f, 0.8f, 0.1f}, colorExitT [4]={0.85f, 0.0f, 0.0f},
      colorOff [4]={0.85f, 0.85f, 0.85f}, colorOn [4]={0.0f, 1.0f, 0.0f},
      colorExitB [4]={1.0, 0.0f, 0.0f}, colorRestB [4]={1.0f, 0.85f, 0.15f},
      colorTxt [4]={1.0f, 1.0f, 1.0f}, colorTxtB [4]={0.5f, 0.5f, 0.5f}, colorH [4]={1.0f, 0.5f, 0.0f},
      colorShadow [4]={0.1f, 0.1f, 0.1f};
  char txt [16];

float resultAngle;
 bool resultOff;

 float darkSkyTo=0.4f, darkSkyStep=0.005f, skyClGo=1.0f, skyCl=1.0f;

  int fpsOn=0;
 bool clockTweak=false;
 long clockL=0;
float clockD=0.0f;

 bool noRest=false, blur_on=false, loaded=false;
 bool moreFPS=true;
 bool bQuit=false;
 bool quitCPU=false;
  int infOn=0;

 bool ctrl_key=false, keyLockEsc=false, keyLockEnter=false;
 int fontS, fps=-1, paintC=0, timeS=0;

  int dmW [96], dmH [96], dmB [96], dmC=0,
      dmH0, dmW0, dmB0, dmN=0,
      dmHs, dmWs, dmBs, dmHt, dmWt, dmBt;
 bool dmBitsOff=true;

GLuint texture [256];
GLuint base; // База списка отображения для фонта
GLuint PixelFormat;

COLORREF bGround=RGB (55, 56, 84);
LRESULT CALLBACK WndProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

const unsigned int TIMER_MEL=5, TIMER_QUIT=10, TIMER_MELON=15;
COLORREF pixel=RGB (0, 0, 0);
TRACKMOUSEEVENT tme;
POINT mypoint;
HCURSOR curArrow, curWait, curNew, curOff;
static HANDLE gThreadCPU=NULL;
DWORD wThreadCPU;
DWORD WINAPI threadCPU (LPVOID);
WNDCLASS wc;
HWND hWnd;
HINSTANCE gThisInstance; int gFunsterStil;
HDC hDC;
HGLRC hRC;        
MSG msg;
PAINTSTRUCT PaintStruct;

ULONG_PTR gdiplusToken;
Gdiplus::Graphics * gDC;
Gdiplus::Image * imagesH;

char mb [64];

// Make the class name into a global variable
char szClassName []="OpenGL App";
char title []="CornersGL";

// board
char init_d [64];

char init_p [64]={
'a','a','a','0','0','0','0','0',
'a','a','a','0','0','0','0','0',
'a','a','a','0','0','0','0','0',
'0','0','0','0','0','0','0','0',
'0','0','0','0','0','0','0','0',
'0','0','0','0','0','1','1','1',
'0','0','0','0','0','1','1','1',
'0','0','0','0','0','1','1','1'
};


 void paint ();
 void mouseMove ();
 void mouseClick ();
  int getPos (int x, int y);
 void cellInfo ();
 void windowUp ();
 void moveCPU ();
 void playerMove ();
 void turnOver ();
 void Restart ();

 void statusBar ();
 void fpsC ();
float fpsTweak ();
 void saveConf ();
 void loadConf ();
 void EnableOpenGL (HWND hWnd, HDC *hDC, HGLRC *hRC, GLuint pf);
 void DisableOpenGL (HWND hWnd, HDC hDC, HGLRC hRC);
 void InitGL ();
  int InitMultisample ();
 void LoadGLTextures ();
 void BuildLists ();
 void getScr ();
 void screenSet ();
 void screenUp ();
 void keysOff ();
 void loading ();
 void flipBoard (char d [64]);


 char AppDir [_MAX_PATH];
  int soundVol=0, meloVol=0;
 bool soundOn=false, meloIs=false, audioOnce=false;
#include "sound.h"
#include "melody.h"



/**************************
 * WinMain
 *
 **************************/

int WINAPI WinMain (HINSTANCE hInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpCmdLine,
                    int iCmdShow)
{
 int i;

 gThisInstance=hInstance;
 gFunsterStil=iCmdShow;

 Gdiplus::GdiplusStartupInput gdiplusStartupInput; 
 GdiplusStartup (&gdiplusToken, &gdiplusStartupInput, NULL);

 char AppPath [_MAX_PATH];
 int ap_l=0;
 memset (AppPath, 0, _MAX_PATH);
 memset (AppDir, 0, _MAX_PATH);
 GetModuleFileName (NULL, AppPath, _MAX_PATH);
 for (i=_MAX_PATH-1; i>=0 && ap_l==0; i--)
 {
  if (AppPath [i]=='\\')
   ap_l=i+1;
 }

 memcpy (AppDir, AppPath, ap_l);

 memset (mb, 0, 64);

 // initialize random seed:
 srand (time (NULL));

 getScr ();
 loadConf ();
 screenSet ();

 // register window class
 wc.style=CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
 wc.lpfnWndProc=WndProc;
 wc.cbClsExtra=0;
 wc.cbWndExtra=0;
 wc.hInstance=hInstance;
 wc.hIcon=LoadIcon (hInstance, MAKEINTRESOURCE(ID_PIC));
 wc.hCursor=LoadCursor (hInstance, MAKEINTRESOURCE(ID_CUR));
 curArrow=LoadCursor (hInstance, MAKEINTRESOURCE(ID_CUR));
 curWait=LoadCursor (hInstance, MAKEINTRESOURCE(ID_CUW));
 curNew=LoadCursor (hInstance, MAKEINTRESOURCE(ID_NEW));
 curOff=LoadCursor (hInstance, MAKEINTRESOURCE(ID_OFF));
 wc.hbrBackground=(HBRUSH)CreateSolidBrush (bGround);
 wc.lpszMenuName=NULL;
 wc.lpszClassName=szClassName;
 RegisterClass (&wc);

 for (i=0; i<2; i++)
 {
  hWnd=CreateWindowEx (
   0,           // Extended possibilites for variation
   szClassName, // Classname
   title,       // Title Text
   WS_POPUP,    // No caption & borders
   0,           // Program decides the position
   0,           // where the window ends up on the screen
   cx+1,        // The programs width
   cy+1,        // and height in pixels
   HWND_DESKTOP,// The window is a child-window to desktop
   NULL,        // No menu
   hInstance,   // Program Instance handler
   NULL         // No Window Creation data
  );

  if (i==0)
  {
   EnableOpenGL (hWnd, &hDC, &hRC, 0);
   PixelFormat=InitMultisample ();
//   if (PixelFormat==0)
    break;
   DestroyWindow (hWnd);
  }
  else
   EnableOpenGL (hWnd, &hDC, &hRC, PixelFormat);
 }

 ShowWindow (hWnd, iCmdShow);
 SetForegroundWindow (hWnd);// Слегка повысим приоритет
 SetFocus (hWnd);// Установить фокус клавиатуры на наше окно
 InitGL ();

 playSound ("board", 0, 1);

 tme.cbSize=sizeof(tme);
 tme.dwFlags=TME_HOVER;
 tme.hwndTrack=hWnd;// hanlde of window you want the mouse over message for.
 tme.dwHoverTime=HOVER_DEFAULT;

 TrackMouseEvent(&tme);

 gThreadCPU=CreateThread (NULL, 0, threadCPU, (void *)"threadCPU", 0, &wThreadCPU);

 memcpy (init_d, init_p, 64);

 loaded=true;

 // program main loop
 while (!bQuit)
 {
  // check for messages
  if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
  {
   // handle or dispatch messages
   if (msg.message==WM_QUIT)
    bQuit=true;
   else
   {
    TranslateMessage (&msg);
    DispatchMessage (&msg);
   }
  }

  if (!bQuit)
  {
   if (!blur_on)
    paint ();
  }

  Sleep ((audioOnce ? 12 : 10)*(moreFPS ? 1 : 3));
 }

 saveConf ();
 meloClose ();

 Gdiplus::GdiplusShutdown (gdiplusToken);

 quitCPU=true;
 for (int i=0; i<10 && quitCPU; i++)
  Sleep (10);
 CloseHandle (gThreadCPU);

 // shutdown OpenGL
 DisableOpenGL (hWnd, hDC, hRC);

 ChangeDisplaySettings (NULL, 0);// Переключаемся обратно в оконный режим
 if (hRC)// Существует ли Контекст Рендеринга?
 {
  wglMakeCurrent (NULL, NULL);
  wglDeleteContext (hRC);
 }
 ReleaseDC (hWnd, hDC);// Возможно ли уничтожить DC?
 UnregisterClass (szClassName, gThisInstance);

 // destroy the window explicitly
 DestroyWindow (hWnd);

 return msg.wParam;
}

/********************
 * Window Procedure
 *
 ********************/

LRESULT CALLBACK WndProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
 switch (message)
 {
  case WM_CLOSE:
   PostQuitMessage (0);
   return 0;

  case WM_DESTROY:
   return 0;

  case WM_KILLFOCUS:
   keysOff ();

   meloBlurOn=true;
   blur_on=true;
   break;

  case WM_SETFOCUS:
   if (noRest==true || loaded==false)
    break;

   fpsOn=0;
   clockL=0;

   screenSet ();
   if (cx!=dmW0 || cy!=dmH0)
   {
    getScr ();
    dmN=0;
    dmWs=dmW0;
    dmHs=dmH0;
    dmBs=dmB0;
    screenUp ();
   }
   else
    windowUp ();

   meloBlurOff=true;
   blur_on=false;
   break;

  case WM_SIZE:
   switch (wParam)
   {
    case SIZE_RESTORED:
     if (blur_on)
      break;

     if (noRest==true || loaded==false)
      break;

     screenSet ();
     if (cx!=dmW0 || cy!=dmH0)
     {
      getScr ();
      dmN=0;
      dmWs=dmW0;
      dmHs=dmH0;
      dmBs=dmB0;
      screenUp ();
     }
     else
      windowUp ();

     break;
   }
   break;

  case WM_PAINT:
   BeginPaint(hWnd, &PaintStruct);
   if (blur_on && loaded)
   {
    hDC=GetDC (hWnd);
    paint ();
    ReleaseDC (hWnd, hDC);
   }
   EndPaint (hWnd, &PaintStruct);
   break;

  case WM_LBUTTONUP:
   mouseClick ();
   break;

  case WM_MOUSEMOVE:
   mouseMove ();
   break;


  case WM_TIMER:
   switch (wParam)
   {
    case TIMER_MELON:
     KillTimer (hWnd, TIMER_MELON);
     meloVol=melVol*250;
     break;
    case TIMER_MEL:
     KillTimer (hWnd, TIMER_MEL);
     meloInit ();
     break;
    case TIMER_QUIT:
     qC++;
     if (qC==qCmx)
     {
      KillTimer (hWnd, TIMER_QUIT);
      bQuit=true;
     }
     break;
   }
   break;

  case WM_KEYDOWN:
   switch (wParam)
   {
    case 81:
     if (ctrl_key)
      PostQuitMessage(0);
     break;

    case VK_ESCAPE:
     if (keyLockEsc)
      break;

     keyLockEsc=true;

     if (infOn)
     {
      infOn=0;
      playSound ("shake");
      mouseMove ();
     }
     break;

    case VK_RIGHT:
      infOn=0;
     if (posX<7)
     {
      posX++;
      cellInfo ();
     }
     break;

    case VK_LEFT:
      infOn=0;
     if (posX>0)
     {
      posX--;
      cellInfo ();
     }
     break;

    case VK_NEXT:
      infOn=0;
     if (posX<7 && posY<7)
     {
      posX++;
      posY++;
      cellInfo ();
     }
     break;

    case VK_PRIOR:
      infOn=0;
     if (posX<7 && posY>0)
     {
      posX++;
      posY--;
      cellInfo ();
     }
     break;

    case VK_UP:
      infOn=0;
     if (posY>0)
     {
      posY--;
      cellInfo ();
     }
     break;

    case VK_DOWN:
      infOn=0;
     if (posY<7)
     {
      posY++;
      cellInfo ();
     }
     break;

    case VK_HOME:
      infOn=0;
     if (posX>0 && posY>0)
     {
      posX--;
      posY--;
      cellInfo ();
     }
     break;

    case VK_END:
     infOn=0;
     if (posX>0 && posY<7)
     {
      posX--;
      posY++;
      cellInfo ();
     }
     break;

    case VK_CONTROL:
     ctrl_key=true;
     break;
   }

   if (wParam==VK_RETURN || wParam==VK_SPACE || wParam==VK_CLEAR)
   {
    if (keyLockEnter)
     break;

    infOn=0;
    playerMove ();
    keyLockEnter=true;
   }
   return 0;

  case WM_KEYUP:

   switch (wParam)
   {
    case VK_ESCAPE:
     keyLockEsc=false;
     break;

    case VK_CONTROL:
     ctrl_key=false;
     break;
   }

   if (wParam==VK_RETURN || wParam==VK_SPACE || wParam==VK_CLEAR)
    keyLockEnter=false;

   return 0;

  default:
   return DefWindowProc (hWnd, message, wParam, lParam);
 }
}

DWORD WINAPI threadCPU (LPVOID)
{
 // initialize random seed:
 srand (time (NULL));

 while (!quitCPU)
 {
  if (state==3)
  {
   state=4;
   moveCPU ();
  }

  Sleep (10);
 }

 quitCPU=false;
}

int conf_side=-1;
void turnOver ()
{
 resultAngle=90.0f;
 resultOff=false;
 state=10;

 if (square_white && square_black)
 {
  res=3;
  stats_draws++;
 }
 else if (square_white)
 {
  res=1;
  conf_side=0;
  stats_wins++;
 }
 else
 {
  res=2;
  conf_side=1;
  stats_loses++;
 }

 SetCursor (curWait);

 light_pos=0.0f;
 light_d=1;
}

void Restart ()
{
 if ((cPlayer+cCPU)>0)
 {
  move1=false;
  sel_x0=-1;
  sel_y0=-1;
  sel_x=-1;
  sel_y=-1;
  conf_side=-1;

  if (state>=10)
  {
   if (square_white && square_black)
   {
   }
   else if (square_white)
    side=0;
   else
    side=1;
  }

  square_white=false;
  square_black=false;

  if (state>2 && state<6)
   stateCPU=1;
  if (state<10)
   stats_restart++;
  state=0;
  memcpy (init_d, init_p, 64);
  cPlayer=0;
  cCPU=0;
  infOn=0;
  playSound ("board");
  if (side)
   state=3;
 }
 else
  playSound ("break");
}

void keysOff ()
{
 ctrl_key=false;
 keyLockEsc=false;
 keyLockEnter=false;
}

void getScr ()
{
 int i, i2, bitsN=0;
 bool dmRepeat;

 DEVMODE devMode;// Режим устройства
 memset (&devMode, 0, sizeof (devMode));// Очистка для хранения установок
 devMode.dmSize=sizeof (devMode);// Размер структуры Devmode

 for (i=0; EnumDisplaySettings (0, i, &devMode); i++)
 {
  dmRepeat=false;
  for (i2=0; i2<dmC; i2++)
  {
   if (dmW [i2]==devMode.dmPelsWidth && dmH [i2]==devMode.dmPelsHeight && dmB [i2]==devMode.dmBitsPerPel)
    dmRepeat=true;
  }
  if (!dmRepeat)
  {
   if (bitsN==0)
    bitsN=devMode.dmBitsPerPel;
   else if (bitsN!=devMode.dmBitsPerPel)
    dmBitsOff=false;

   dmW [dmC]=devMode.dmPelsWidth;
   dmH [dmC]=devMode.dmPelsHeight;
   dmB [dmC]=devMode.dmBitsPerPel;
   dmC++;
  }
 }

 int swpH, swpW, swpB;
 for (i=0; i<dmC; i++)
 {
  for (i2=i; i2<dmC; i2++)
  {
   if (dmW [i2]>dmW [i] || (dmW [i2]==dmW [i] && dmH [i2]>dmH [i])
   || (dmW [i2]==dmW [i] && dmH [i2]==dmH [i] && dmB [i2]>dmB [i]))
   {
    swpW=dmW [i];
    swpH=dmH [i];
    swpB=dmB [i];

    dmW [i]=dmW [i2];
    dmH [i]=dmH [i2];
    dmB [i]=dmB [i2];

    dmW [i2]=swpW;
    dmH [i2]=swpH;
    dmB [i2]=swpB;
   }
  }
 }

 memset (&devMode, 0, sizeof (devMode));// Очистка для хранения установок
 devMode.dmSize=sizeof (devMode);// Размер структуры Devmode
 EnumDisplaySettings (0, ENUM_CURRENT_SETTINGS, &devMode);
 dmW0=devMode.dmPelsWidth;
 dmH0=devMode.dmPelsHeight;
 dmB0=devMode.dmBitsPerPel;
}

void windowUp ()
{
 SetWindowPos (hWnd, HWND_TOP, 0, 0, cx+1, cy+1, SWP_NOMOVE);// ?
}

void screenSet ()
{
 cx=(LONG)::GetSystemMetrics (SM_CXSCREEN);
 cy=(LONG)::GetSystemMetrics (SM_CYSCREEN);
}

void screenUp ()
{
 noRest=true;

 windowUp ();

 // shutdown OpenGL
 DisableOpenGL (hWnd, hDC, hRC);
 EnableOpenGL (hWnd, &hDC, &hRC, PixelFormat);

 SetForegroundWindow (hWnd);// Слегка повысим приоритет
 SetFocus (hWnd);// Установить фокус клавиатуры на наше окно

 InitGL ();

 pC=0;

 noRest=false;
}

void InitGL ()
{
 SetCursor (curWait);

 glShadeModel (GL_SMOOTH);// Разрешить плавное затенение
 glViewport (0, 0, cx+2, cy+2);
 glMatrixMode (GL_PROJECTION);
 gluPerspective (45.0f, (GLfloat)cx/(GLfloat)cy, 0.1f, 100.0f);

 glClearDepth (1.0);       // Depth Buffer Setup
 glDisable (GL_DEPTH_TEST);// Disables Depth Testing
 glDepthFunc (GL_LEQUAL);  // The Type Of Depth Testing To Do

 glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
 glMatrixMode (GL_MODELVIEW);

// if (PixelFormat!=0)
//  glEnable (GL_MULTISAMPLE_ARB);

 loading ();
 LoadGLTextures ();
 glEnable (GL_TEXTURE_2D);

 int i;
 for (i=0; i<9; i++)
  mXar0 [i]=cx/2-(float)cy*4.5f/9.0f+cy*i/9;
 for (i=0; i<9; i++)
  mYar0 [i]=cy*(i+1)/9;

 // Функция смешивания для непрозрачности, базирующаяся на значении альфы
 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

 glPolygonMode (GL_BACK, GL_LINE); // нижняя (задняя) сторона прорисована линиями
 glPolygonMode (GL_FRONT, GL_FILL);// верхняя (передняя) сторона заполнена

 BuildLists ();// создаем список отображения

 delete imagesH;
}

/*******************
 * Enable OpenGL
 *
 *******************/

void EnableOpenGL (HWND hWnd, HDC *hDC, HGLRC *hRC, GLuint pf)
{
 PIXELFORMATDESCRIPTOR pfd;
 int iFormat;

 // get the device context (DC)
 *hDC=GetDC (hWnd);

 if (pf==0)
 {
  // set the pixel format for the DC
  ZeroMemory (&pfd, sizeof (pfd));
  pfd.nSize=sizeof (pfd);
  pfd.nVersion=1;
  pfd.dwFlags=PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  pfd.iPixelType=PFD_TYPE_RGBA;
  pfd.cColorBits=dmBs;
  pfd.cDepthBits=dmBs;//24;
  pfd.iLayerType=PFD_MAIN_PLANE;
  iFormat=ChoosePixelFormat (*hDC, &pfd);
  SetPixelFormat (*hDC, iFormat, &pfd);
 }
 else
  SetPixelFormat(*hDC, pf, &pfd);

 // create and enable the render context (RC)
 *hRC=wglCreateContext (*hDC);
 wglMakeCurrent (*hDC, *hRC);
}


/******************
 * Disable OpenGL
 *
 ******************/

void DisableOpenGL (HWND hWnd, HDC hDC, HGLRC hRC)
{
 wglMakeCurrent (NULL, NULL);
 wglDeleteContext (hRC);
 ReleaseDC (hWnd, hDC);
}

int shape [65536];

// читаем изображение и преобразуем его в текстуру
void LoadGLTextures ()
{
 HDC hdcTemp;                 // DC для растра
 HBITMAP hbmpTemp;            // иногда храним в ней растр
 IPicture *pPicture;          // интерфейс IPicture
 OLECHAR wszPath [MAX_PATH+1];// полный путь до картинки (WCHAR)
 long lWidth;                 // ширина в логических единицах
 long lHeight;                // высота в логических единицах
 long lWidthPixels;           // ширина в пикселях
 long lHeightPixels;          // высота в пикселях
 GLint glMaxTexDim ;          // максимальный размер текстуры

 memset (shape, 0, 256*256);
 char texs [25] [32]={"blank.gif", "shape.gif", "gray.gif",
                      "border.gif", "bordertop.gif", "bordercorner.gif", "bordlight.gif", "bordlighttop.gif",
                      "checker.jpg", "exit.gif", "snd.gif", "tune.gif", "info.gif", "bg.jpg", "stats.gif",
                      "tooltip.jpg", "restart.gif", "lang.gif", "sky.jpg"
                     };
 char texd [16]={"data\\textures"};
 char txt [_MAX_PATH];
 int i2, xi, yi, cl, ri;

 for (i2=0; i2<256; i2++)
 {
  if (!(i2>126 && i2<161) && !(i2>18 && i2<32))
  {
   if (i2<19)
    sprintf (txt, "%s%s\\%s", AppDir, texd, texs [i2]);
   else
    sprintf (txt, "%s%s\\litera\\%d.jpg", AppDir, texd, i2);

   MultiByteToWideChar (CP_ACP, 0, txt, -1, wszPath, MAX_PATH);// преобразуем к юникоду
   HRESULT hr=OleLoadPicturePath (wszPath, 0, 0, 0, IID_IPicture, (void**)&pPicture);

   if (!FAILED (hr)) // Если загрузка удачна
   {
    hdcTemp=CreateCompatibleDC (GetDC (0));// создать совместимый с устройством Windows контекст
    if (!hdcTemp)         // ну что, создали?
      pPicture->Release();// не-а… :( уменьшение счетчика ссылок на IPicture
    else
    {
     // получить максимально возможное разрешение изображения
     glGetIntegerv (GL_MAX_TEXTURE_SIZE, &glMaxTexDim);

     pPicture->get_Width (&lWidth);  // получить ширину изображения
     lWidthPixels=MulDiv (lWidth, GetDeviceCaps (hdcTemp, LOGPIXELSX), 2540);
     pPicture->get_Height (&lHeight);// получить высоту изображения
     lHeightPixels=MulDiv (lHeight, GetDeviceCaps (hdcTemp, LOGPIXELSY), 2540);

     // преобразовать изображение к ближайшей степени двойки
     if (lWidthPixels<=glMaxTexDim)
      // если ширина изображения меньше либо равна максимально-допустимому пределу карточки
      lWidthPixels=1<<(int)floor((log ((double)lWidthPixels)/log (2.0f))+0.5f);
     else
      // иначе установить размер равный максимальной степени двойки,
      // которую поддерживает карточка
      lWidthPixels=glMaxTexDim;
     // то же самое повторяется для высоты
     if (lHeightPixels<=glMaxTexDim)
      lHeightPixels=1<<(int)floor ((log ((double)lHeightPixels)/log (2.0f))+0.5f);
     else
      lHeightPixels=glMaxTexDim;

     // создать временный растр
     BITMAPINFO  bi={0}; // нужный нам тип растра
     DWORD   *pBits=0;   // указатель на биты растра

     bi.bmiHeader.biSize=sizeof (BITMAPINFOHEADER);// размер структуры
     bi.bmiHeader.biBitCount=32;                   // 32 бита
     bi.bmiHeader.biWidth=lWidthPixels;            // ширина кратная степени двойки
     // Сделаем изображение расположенным вверх (положительное направление оси Y)
     bi.bmiHeader.biHeight=lHeightPixels;
     bi.bmiHeader.biCompression=BI_RGB;            // RGB формат
     bi.bmiHeader.biPlanes=1;                      // 1 битовая плоскость 

     // создавая растр, таким образом, мы можем установить глубину цвета,
     // а также получить прямой доступ к битам.
     hbmpTemp=CreateDIBSection (hdcTemp, &bi, DIB_RGB_COLORS, (void**)&pBits, 0, 0);

     if (!hbmpTemp)        // создали?
     {                     // сам вижу что нет
      DeleteDC (hdcTemp);  // убить контекст устройства
      pPicture->Release ();// уменьшить счетчик количества интерфейсов IPicture
     }
     else
     {
      // есть растр!
      SelectObject (hdcTemp, hbmpTemp);// загрузить описатель временного растра
                                       // в описатель временного контекста устройства 
      // отрисовка IPicture в растр
      pPicture->Render (hdcTemp, 0, 0, lWidthPixels, lHeightPixels, 0, lHeight, lWidth, -lHeight, 0);

      long i, n=lWidthPixels*lHeightPixels;
      // преобразовать из BGR в RGB формат и устанавливаем значение Alpha

      if (i2>=32)// обработка символов
      {
       for (i=0; i<n; i++) // Цикл по всем пикселям
       {
        BYTE* pPixel=(BYTE*)(&pBits[i]);// берем текущий пиксель
        BYTE  temp=pPixel [0];          // сохраняем первый цвет в переменной
                                        // Temp (Синий)
        pPixel [0]=pPixel [2];          // ставим  Красный на место (в первую позицию)
        pPixel [2]=temp;                // ставим значение Temp в третий параметр (3rd)

        if (pPixel [0]<25 && pPixel [1]<25 && pPixel [2]>55)// убираем фон
        {
         pPixel [0]=0;
         pPixel [1]=0;
         pPixel [2]=0;
         pPixel [3]=0;
        }
        else
        {
         // Меняем цвет на серый, убирая случайные цветные пиксели
         pPixel [0]=(pPixel [0]+pPixel [1]+pPixel [2])/3;
         pPixel [1]=(pPixel [0]+pPixel [1]+pPixel [2])/3;
         pPixel [2]=(pPixel [0]+pPixel [1]+pPixel [2])/3;
         // Добавляем к градиенту прозрачность, на основе цвета
         pPixel [3]=(pPixel [0]+pPixel [1]+pPixel [2])/3;
        }
       }
      }
      else if (i2==1)
      {
       for (i=0; i<n; i++) // Цикл по всем пикселям
       {
        BYTE* pPixel=(BYTE*)(&pBits[i]);// берем текущий пиксель
        BYTE  temp=pPixel [0];          // сохраняем первый цвет в переменной
                                        // Temp (Синий)
        pPixel [0]=pPixel [2];          // ставим  Красный на место (в первую позицию)
        pPixel [2]=temp;                // ставим значение Temp в третий параметр (3rd)

        if (pPixel [0]<50 && pPixel [1]<50 && pPixel [2]>150)
         shape [i]=0;
        else
         shape [i]=(pPixel [0]+pPixel [1]+pPixel [2])/3;
       }
      }
      else if (i2==8)
      {
       for (i=0; i<n; i++) // Цикл по всем пикселям
       {
        BYTE* pPixel=(BYTE*)(&pBits[i]);// берем текущий пиксель
        BYTE  temp=pPixel [0];          // сохраняем первый цвет в переменной
                                        // Temp (Синий)
        pPixel [0]=pPixel [2];          // ставим  Красный на место (в первую позицию)
        pPixel [2]=temp;                // ставим значение Temp в третий параметр (3rd)
        pPixel [3]=shape [i];                // установить значение alpha
       }
      }
      else if (i2==9 || i2==10 || i2==11 || i2==12 || i2==14 || i2==16 || i2==17)//i2==8
      {
       for (i=0; i<n; i++) // Цикл по всем пикселям
       {
        BYTE* pPixel=(BYTE*)(&pBits[i]);// берем текущий пиксель
        BYTE  temp=pPixel [0];          // сохраняем первый цвет в переменной
                                        // Temp (Синий)
        pPixel [0]=pPixel [2];          // ставим  Красный на место (в первую позицию)
        pPixel [2]=temp;                // ставим значение Temp в третий параметр (3rd)

        if (pPixel [2]>150)
        {
         pPixel [0]=0;
         pPixel [1]=0;
         pPixel [2]=0;
         pPixel [3]=0;                  // установить значение alpha =0
        }
        else
        {
         yi=i/lWidthPixels;
         xi=i-yi*lWidthPixels;
         ri=sqrt (pow ((lWidthPixels/2-xi), 2)+pow ((lHeightPixels/2-yi), 2));

         cl=abs (lWidthPixels/2-ri);

         if (cl<12)
          cl=cl*cl;
         else
          cl=cl*16;
         if (cl>255)
          cl=255;
         pPixel [3]=cl;                // установить значение alpha
        }
       }
      }
      else
      {
       for (i=0; i<n; i++)// Цикл по всем пикселям
       {
        BYTE* pPixel=(BYTE*)(&pBits[i]);// берем текущий пиксель
        BYTE  temp=pPixel [0];          // сохраняем первый цвет в переменной
                                        // Temp (Синий)
        pPixel [0]=pPixel [2];          // ставим  Красный на место (в первую позицию)
        pPixel [2]=temp;                // ставим значение Temp в третий параметр (3rd)
        pPixel [3]=255;                 // установить значение alpha =255
       }
      }

      glGenTextures (1, &texture [i2]);//  создаем текстуру texid

      // типичная генерация текстуры, используя данные из растра
      glBindTexture (GL_TEXTURE_2D, texture [i2]);// делаем привязку к texid

      if (i2==0 || i2==2 || i2==3 || i2==4 || i2==5 || i2==15)
      {
       glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
       glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
      }

      // (измените для нужного вам типа фильтрации)
      glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);//GL_NEAREST
      // (измените, если хотите использовать мипмап-фильтрацию) 
      glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

      // (мипмап - множественное отображение (последовательность текстур одного
      //  и того же изображения с уменьшающимся разрешением по мере удаления отображаемого
      // объекта от наблюдателя))

      glTexImage2D (GL_TEXTURE_2D, 0, 4, lWidthPixels, lHeightPixels, 0, GL_RGBA, GL_UNSIGNED_BYTE, pBits);

      DeleteObject (hbmpTemp);// удаляем объект
      DeleteDC (hdcTemp);     // удаляем контекст устройства

      pPicture->Release();    //уменьшает счетчик IPicture
     }
    }
   }
  }
 }
}

int InitMultisample()
{
 // Get Our Pixel Format
 PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB;
 wglChoosePixelFormatARB=(PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress ("wglChoosePixelFormatARB");
 if (!wglChoosePixelFormatARB)
  return 0;

 HDC hDC=GetDC(hWnd);
 int pixelFormat;
 UINT numFormats;
 float fAttributes []={0, 0};

 // These Attributes Are The Bits We Want To Test For In Our Sample
 // Everything Is Pretty Standard, The Only One We Want To 
 // Really Focus On Is The SAMPLE BUFFERS ARB And WGL SAMPLES
 // These Two Are Going To Do The Main Testing For Whether Or Not
 // We Support Multisampling On This Hardware.
 int iAttributes[] = {
  WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
  WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
  WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
  WGL_COLOR_BITS_ARB, dmBs,
  WGL_ALPHA_BITS_ARB, 8,
  WGL_DEPTH_BITS_ARB, dmBs,//24,
  WGL_STENCIL_BITS_ARB, 0,
  WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
  WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
  WGL_SAMPLES_ARB, 6,
  0, 0};

 // First We Check To See If We Can Get A Pixel Format For 6 Samples
 int r=wglChoosePixelFormatARB(hDC, iAttributes, fAttributes, 1, &pixelFormat, &numFormats);

 // If We Returned False, Or Our Format Count Is Less Than 1
 if (!(r && numFormats>=1))
 {
  // Our Pixel Format With 6 Samples Failed, Test For 4 Samples
  iAttributes [19]=4;
  r=wglChoosePixelFormatARB (hDC, iAttributes, fAttributes, 1, &pixelFormat, &numFormats);
  if (!(r && numFormats>=1))
  {
   // Our Pixel Format With 4 Samples Failed, Test For 2 Samples
   iAttributes [19]=2;
   r=wglChoosePixelFormatARB (hDC, iAttributes, fAttributes, 1, &pixelFormat, &numFormats);
   if (!(r && numFormats>=1))
 	return 0;
  }
 }    

 return pixelFormat;
}

// Функция для печати текстурного шрифта;
// нет параметров, вместо - глобальные переменные
float literaScale=0.25f, literaX=0.0f, literaY=0.0f, literaZ=-2.4325f;
char literaText [256]="";
void glPrintLitera ()
{
 glEnable (GL_BLEND);

 for (int i=0; i<strlen (literaText); i++)
 {
  int t=literaText [i];
  if (t<0)
   t+=256;
  if (!((t>126 && t<161) || (t>-1 && t<=32)))
  {
   glBindTexture (GL_TEXTURE_2D, texture [t]);
   glBegin (GL_QUADS);
   glTexCoord2f (0.0f, 0.0f); glVertex3f (-literaScale/2.0f+literaX+i*literaScale/1.85f,
                                          -literaScale/2.0f+literaY, literaZ);// Низ лево
   glTexCoord2f (1.0f, 0.0f); glVertex3f ( literaScale/2.0f+literaX+i*literaScale/1.85f,
                                          -literaScale/2.0f+literaY, literaZ);// Низ право
   glTexCoord2f (1.0f, 1.0f); glVertex3f ( literaScale/2.0f+literaX+i*literaScale/1.85f,
                                           literaScale/2.0f+literaY, literaZ);// Верх право
   glTexCoord2f (0.0f, 1.0f); glVertex3f (-literaScale/2.0f+literaX+i*literaScale/1.85f,
                                           literaScale/2.0f+literaY, literaZ);// Верх лево
   glEnd ();
  }
 }

 glDisable (GL_BLEND);
}

GLuint bgList, brdList, infList;

float brdX=1.0f, brdY=1.0f, brdZ=-2.4325f;
float brdS=2.0f;
float brdL=-brdS*5.5f/9.0f, brdR=brdL+brdS;
float brdT=brdS/2.0f, brdB=-brdS/2.0f;

void BuildLists ()// создаем список отображения
{
 int i;

 bgList=glGenLists (5);// создаем списки

 float bgQ=sqrt (pow (cx, 2)+pow (cy, 2))/(float)cx;
 float bgX=1.825f*((float(cx)/float(cy))/(1600.0f/900.0f))*bgQ, bgY=bgX, bgZ=0.0f;

 glNewList (bgList, GL_COMPILE);// Новый откомпилированный список отображения
 glBindTexture (GL_TEXTURE_2D, texture [18]);
 glBegin (GL_QUADS);
 glTexCoord2f (0.0f, 0.0f); glVertex3f (-bgX, -bgY, bgZ);// Низ лево
 glTexCoord2f (1.0f, 0.0f); glVertex3f ( bgX, -bgY, bgZ);// Низ право
 glTexCoord2f (1.0f, 1.0f); glVertex3f ( bgX,  bgY, bgZ);// Верх право
 glTexCoord2f (0.0f, 1.0f); glVertex3f (-bgX,  bgY, bgZ);// Верх лево
 glEnd ();
 glEndList ();// Закончили создание списка

 brdList=bgList+1;
 glNewList (brdList, GL_COMPILE);
 glBindTexture (GL_TEXTURE_2D, texture [0]);
 glBegin (GL_QUADS);
 glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL, brdB, brdZ);// Низ лево
 glTexCoord2f (1.0f, 0.0f); glVertex3f (brdR, brdB, brdZ);// Низ право
 glTexCoord2f (1.0f, 1.0f); glVertex3f (brdR, brdT, brdZ);// Верх право
 glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL, brdT, brdZ);// Верх лево
 glEnd ();
 glEndList ();// Закончили создание списка

 infList=brdList+1;
 glNewList (infList, GL_COMPILE);
 glBindTexture (GL_TEXTURE_2D, texture [13]);
 glBegin (GL_QUADS);
 glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL, brdB, brdZ);// Низ лево
 glTexCoord2f (1.0f, 0.0f); glVertex3f (brdR, brdB, brdZ);// Низ право
 glTexCoord2f (1.0f, 1.0f); glVertex3f (brdR, brdT, brdZ);// Верх право +0.00135f
 glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL, brdT, brdZ);// Верх лево +0.001f
 glEnd ();
 glEndList ();// Закончили создание списка
}

COLORREF ig1=RGB (170, 170, 170), ig2=RGB (185, 185, 185), iw=RGB (240, 240, 240);
bool isGray (COLORREF px)
{
 if (px>ig1 && px<ig2)
  return true;
 return false;
}

bool isWhite (COLORREF px)
{
 if (px>iw)
  return true;
 return false;
}



char try_d [500] [64];
char try_d2 [10000] [64];
char try_d3 [150000] [64];

int try_p2 [50000];
int try_p3 [150000];

int try_b [500];
int try_b2 [10000];
int try_b3 [150000];

int try_b_s2 [500];
int try_b_s3 [10000];
int try_b_s4 [150000];

int try_i, try_i2, try_i3, try_ix, try_ix2, try_ix3;
int try_s, try_pt, try_n=0;

bool xy_check (int x, int y)
{
 if (x>-1 && x<8 && y>-1 && y<8)
  return true;
 else
  return false;
}

int n_ar [16]={1, -2, -1, -2, 1, 2, -1, 2, 2, -1, -2, -1, 2, 1, -2, 1};

bool fine=false;
int do_move (char d [64], int x1, int y1, int x2, int y2, int take)
{
 if (xy_check (x2, y2)==true)
 {
  int p1=getPos (x1, y1);
  int p2=getPos (x2, y2);
  char x=d [p1];
  char v=d [p2];
  int r=0;

  if (v=='0')
  {
   r=(x1-x2)*2+(y1-y2)*2+50;

   if ((x1-x2)+(y1-y2)>0 && !(x1<=2 && y1<=2))
    r+=(x1+y1);

   if (x2>4 || y2>4)
    r+=abs (y1-x1)-abs (y2-x2);

   if ((x1>4 && y1>4) && (x2<5 || y2<5))
    r+=5;
   else if ((x1<5 || y1<5) && (x2>4 && y2>4))
    r-=5;
   else if ((x1>2 || y1>2) && (x2<3 && y2<3))
   {
    r+=5;
    if (fine==true)
    {
     if (try_s==0)
      r+=15;
     else if (try_s==3)
      r+=10;
    }
   }
   else if ((x1<3 && y1<3) && (x2>2 || y2>2))
    r-=25;
  }

  if (r>0)
  {
   char d2 [64];
   memcpy (d2, d, 64);
   d2 [p2]=d2 [p1];
   d2 [p1]='0';

   if (try_s==0)
   {
    memcpy (try_d [try_i], d2, 64);
    try_b [try_i]=r;
    try_i++;

    if (try_i>try_ix)
     try_ix=try_i;
   }
   else if (try_s==2)
   {
    memcpy (try_d2 [try_i2], d2, 64);
    try_p2 [try_i2]=try_pt;
    try_b2 [try_i2]=r;
    try_i2++;

    if (try_i2>try_ix2)
     try_ix2=try_i2;
   }
   else if (try_s==3)
   {
    memcpy (try_d3 [try_i3], d2, 64);
    try_p3 [try_i3]=try_pt;
    try_b3 [try_i3]=r;
    try_i3++;

    if (try_i3>try_ix3)
     try_ix3=try_i3;
   }
   else if (try_s==4)
   {
    if (try_b_s4 [try_pt]<r)
     try_b_s4 [try_pt]=r;
   }

   return r;
  }
  else
   return 0;
 }
 else
  return 0;
}

void try_move (char d [64], int x1, int y1)
{
 char d2 [64];
 memcpy (d2, d, 64);
 d2 [getPos (x1, y1)]='3';

 char f=d2 [getPos (x1, y1)];
 int x2, y2, i, i2, r;

 int tx1, ty1, tx2, ty2;

 bool start=true, loop=true, out;

 int yi, xi;

 while (loop==true)
 {
  out=false;
  for (yi=0; yi<8; yi++)
  {
   for (xi=0; xi<8; xi++)
   {
    if (d2 [getPos (xi, yi)]=='3')
    {
     d2 [getPos (xi, yi)]='a';
     tx1=xi;
     ty1=yi;
     out=true;
    }
    if (out==true)
     break;
   }
   if (out==true)
    break;
  }

  if (out==true)
  {
   if (ty1>1)
   {
    if (d2 [getPos (tx1, ty1-1)]=='1' || d2 [getPos (tx1, ty1-1)]=='a')
    {
     if (d2 [getPos (tx1, ty1-2)]=='0')
     {
      do_move (d, x1, y1, tx1, ty1-2, 0);
      d2 [getPos (tx1, ty1-2)]='3';
     }
    }
    else if (start==true)
     do_move (d, x1, y1, tx1, ty1-1, 0);
   }
   else if (ty1>0 && start==true)
    do_move (d, x1, y1, tx1, ty1-1, 0);

   if (ty1<6)
   {
    if (d2 [getPos (tx1, ty1+1)]=='1' || d2 [getPos (tx1, ty1+1)]=='a')
    {
     if (d2 [getPos (tx1, ty1+2)]=='0')
     {
      do_move (d, x1, y1, tx1, ty1+2, 0);
      d2 [getPos (tx1, ty1+2)]='3';
     }
    }
    else if (start==true)
     do_move (d, x1, y1, tx1, ty1+1, 0);
   }
   else if (ty1<7 && start==true)
    do_move (d, x1, y1, tx1, ty1+1, 0);


   if (tx1>1)
   {
    if (d2 [getPos (tx1-1, ty1)]=='1' || d2 [getPos (tx1-1, ty1)]=='a')
    {
     if (d2 [getPos (tx1-2, ty1)]=='0')
     {
      do_move (d, x1, y1, tx1-2, ty1, 0);
      d2 [getPos (tx1-2, ty1)]='3';
     }
    }
    else if (start==true)
     do_move (d, x1, y1, tx1-1, ty1, 0);
   }
   else if (tx1>0 && start==true)
    do_move (d, x1, y1, tx1-1, ty1, 0);

   if (tx1<6)
   {
    if (d2 [getPos (tx1+1, ty1)]=='1' || d2 [getPos (tx1+1, ty1)]=='a')
    {
     if (d2 [getPos (tx1+2, ty1)]=='0')
     {
      do_move (d, x1, y1, tx1+2, ty1, 0);
      d2 [getPos (tx1+2, ty1)]='3';
     }
    }
    else if (start==true)
     do_move (d, x1, y1, tx1+1, ty1, 0);
   }
   else if (tx1<7 && start==true)
    do_move (d, x1, y1, tx1+1, ty1, 0);


   start=false;
  }
  else
   loop=false;
 }
}

bool check_move (int t_x1, int t_y1, int t_x2, int t_y2)
{
 try_i=0;
 try_s=0;

 try_move (init_d, t_x1, t_y1);

 int i;
 char d2 [64];
 memcpy (d2, init_d, 64);
 d2 [getPos (t_x2, t_y2)]=d2 [getPos (t_x1, t_y1)];
 d2 [getPos (t_x1, t_y1)]='0';

 for (i=0; i<try_i; i++)
 {
  if (strncmp (try_d [i], d2, 64)==0)
   return true;
 }

 return false;
}



void flipBoard (char d [64])
{
 int i;
 char d2 [64];

 memcpy (d2, d, 64);

 for (i=0; i<64; i++)
 {
  if (d2 [i]=='0')
   d [63-i]='0';

  else if (d2 [i]=='1')
   d [63-i]='a';

  else if (d2 [i]=='a')
   d [63-i]='1';
 }
}

bool check_corner (char d2 [64])
{
 int yi, xi, c=0;
 bool white=false, black=false;

 for (yi=0; yi<3; yi++)
 {
  for (xi=0; xi<3; xi++)
  {
   if (d2 [getPos (xi, yi)]!='0')
   {
    if (d2 [getPos (xi, yi)]=='1')
     white=true;
    c++;
   }
  }
 }

 if (white==true && c==9)
  square_white=true;

 c=0;
 for (yi=5; yi<8; yi++)
 {
  for (xi=5; xi<8; xi++)
  {
   if (d2 [getPos (xi, yi)]!='0')
   {
    if (d2 [getPos (xi, yi)]=='a')
     black=true;
    c++;
   }
  }
 }

 if (black==true && c==9)
  square_black=true;

 if (square_white || square_black)
  return true;
 else
  return false;
}

void leaps (int x1, int y1, int x2, int y2)
{
 char d2 [64];
 int i, c, n=0, tx1, ty1;
 int ar_x [100], ar_y [100], ar_parent [100];

 memcpy (d2, init_d, 64);

 c=0;
 ar_x [c]=x1;
 ar_y [c]=y1;
 d2 [getPos (x1, y1)]='a';
 d2 [getPos (x2, y2)]='0';

 for (i=0; i<=c; i++)
 {
  tx1=ar_x [i];
  ty1=ar_y [i];

  if (tx1<6)
  {
   if ( (d2 [getPos (tx1+1, ty1)]=='1' || d2 [getPos (tx1+1, ty1)]=='a') && d2 [getPos (tx1+2, ty1)]=='0' )
   {
    c++;
    ar_x [c]=tx1+2;
    ar_y [c]=ty1;
    ar_parent [c]=i;
    d2 [getPos (tx1+2, ty1)]='a';
    if ( (tx1+2)==x2 && ty1==y2 )
    {
     n=c;
     break;
    }
   }
  }
  if (tx1>1)
  {
   if ( (d2 [getPos (tx1-1, ty1)]=='1' || d2 [getPos (tx1-1, ty1)]=='a') && d2 [getPos (tx1-2, ty1)]=='0' )
   {
    c++;
    ar_x [c]=tx1-2;
    ar_y [c]=ty1;
    ar_parent [c]=i;
    d2 [getPos (tx1-2, ty1)]='a';
    if ( (tx1-2)==x2 && ty1==y2 )
    {
     n=c;
     break;
    }
   }
  }
  if (ty1<6)
  {
   if ( (d2 [getPos (tx1, ty1+1)]=='1' || d2 [getPos (tx1, ty1+1)]=='a') && d2 [getPos (tx1, ty1+2)]=='0' )
   {
    c++;
    ar_x [c]=tx1;
    ar_y [c]=ty1+2;
    ar_parent [c]=i;
    d2 [getPos (tx1, ty1+2)]='a';
    if ( tx1==x2 && (ty1+2)==y2 )
    {
     n=c;
     break;
    }
   }
  }
  if (ty1>1)
  {
   if ( (d2 [getPos (tx1, ty1-1)]=='1' || d2 [getPos (tx1, ty1-1)]=='a') && d2 [getPos (tx1, ty1-2)]=='0' )
   {
    c++;
    ar_x [c]=tx1;
    ar_y [c]=ty1-2;
    ar_parent [c]=i;
    d2 [getPos (tx1, ty1-2)]='a';
    if ( tx1==x2 && (ty1-2)==y2 )
    {
     n=c;
     break;
    }
   }
  }
 }

 leaps_c=-1;
 if (n!=0)
 {
  for (i=c; i>=0; i--)
  {
   if (i==n)
   {
    leaps_c++;
    leaps_x [leaps_c]=ar_x [i];
    leaps_y [leaps_c]=ar_y [i];
    n=ar_parent [i];
   }
  }

  int i2=-1;
  for (i=leaps_c-1; i>=0; i--)
  {
   i2++;
   leaps_x1 [i2]=leaps_x [i];
   leaps_y1 [i2]=leaps_y [i];
  }
  leaps_c=i2;
 }
}

void moveCPU ()
{
 char d [64], d2 [64], d3 [64], d4 [64];
 int x, y, i, x2, y2, i2, try_c1, try_c0, x3, y3, i3;
 char t, f;
 int try_i2_t, try_i3_t;
 int break_x=0, break_y=0;

 memcpy (d, init_d, 64);

 bool own=false;
 int c=0;
 for (y=5; y<8; y++)
 {
  for (x=5; x<8; x++)
  {
   if (d [getPos (x, y)]!='0')
   {
    if (d [getPos (x, y)]=='a')
     own=true;
    c++;
   }
  }
 }
 if (own==true && c>7)
  fine=true;

 flipBoard (d);

 i=0;
 try_i=0;
 try_s=0;

 for (y=0; y<8; y++)
 {
  for (x=0; x<8; x++)
  {
   t=d [i];
   if (t=='1')
    try_move (d, x, y);

   i++;
  }
 }

 try_i2=0;
 try_s=2;

 for (i3=0; i3<try_i; i3++)
 {
  memcpy (d2, try_d [i3], 64);
  flipBoard (d2);

  i=0;
  try_pt=i3;
  try_i2_t=try_i2;
  for (y=0; y<8; y++)
  {
   for (x=0; x<8; x++)
   {
    t=d2 [i];
    if (t=='1')
     try_move (d2, x, y);
    i++;
   }
  }
 }

 try_i3=0;
 try_s=3;

 for (i3=0; i3<try_i2; i3++)
 {
  memcpy (d2, try_d2 [i3], 64);
  flipBoard (d2);

  i=0;
  try_pt=i3;
  try_i3_t=try_i3;
  for (y=0; y<8; y++)
  {
   for (x=0; x<8; x++)
   {
    t=d2 [i];
    if (t=='1')
     try_move (d2, x, y);
    i++;
   }
  }
 }

 try_s=4;

 int i3_1,i3_2,i3_3,i3_4;
 i3_1=(int)(try_i3/5);
 i3_2=(int)(try_i3/5*2);
 i3_3=(int)(try_i3/5*3);
 i3_4=(int)(try_i3/5*4);
 for (i=0; i<try_i3; i++)
 {
  if (cCPU<32)
  {
   try_b_s4 [i]=-1000;
   try_b_s3 [try_p3 [i]]=-1000;
  }
  else
  {
   try_b_s4 [i]=0;
   try_b_s3 [try_p3 [i]]=0;
  }
 }
 for (i3=0; i3<try_i3; i3++)
 {
  memcpy (d2, try_d3 [i3], 64);
  flipBoard (d2);

  i=0;
  try_pt=i3;
  for (y=0; y<8; y++)
  {
   for (x=0; x<8; x++)
   {
    t=d2 [i];
    if (t=='1')
     try_move (d2, x, y);
    i++;
   }
  }

  if (i3==i3_1)
   Sleep (sleepTime);
  else if (i3==i3_2)
   Sleep (sleepTime);
  else if (i3==i3_3)
   Sleep (sleepTime);
  else if (i3==i3_4)
   Sleep (sleepTime);
 }

 Sleep (sleepTime);

 int try_t=0;
 for (i=0; i<try_i3; i++)
 {
  try_t=try_b3 [i]-try_b_s4 [i];
  if (try_b_s3 [try_p3 [i]]<try_t)
   try_b_s3 [try_p3 [i]]=try_t;
 }

 for (i=0; i<try_i2; i++)
 {
  if (cCPU<32)
   try_b_s2 [try_p2 [i]]=-1000;
  else
   try_b_s2 [try_p2 [i]]=0;
 }

 for (i=0; i<try_i2; i++)
 {
  try_t=try_b2 [i]-try_b_s3 [i];
  if (try_b_s2 [try_p2 [i]]<try_t)
   try_b_s2 [try_p2 [i]]=try_t;
 }

 try_n=0;
 int try_max=-100000;
 for (i=0; i<try_i; i++)
 {
  try_t=try_b [i]-try_b_s2 [i];
  if (try_max<try_t)
  {
   try_max=try_t;
   try_n=i;
  }
  else if (try_max==try_t && rand()%2==1)
   try_n=i;
 }

 Sleep (sleepTime);

 flipBoard (try_d [try_n]);

 i=0;
 for (y2=0; y2<8; y2++)
 {
  for (x2=0; x2<8; x2++)
  {
   if (init_d [i]!=try_d [try_n] [i])
   {
    if (try_d [try_n] [i]=='0')
    {
     if (init_d [i]=='1')
     {
      break_x=x2;
      break_y=y2;
     }
     else
     {
      move_x1=x2;
      move_y1=y2;
     }
    }
    else
    {
     move_x2=x2;
     move_y2=y2;
    }
   }
   i++;
  }
 }

 Sleep (sleepTime);

 sel_x=0; sel_y=0; sel_x0=0; sel_y0=0;

 lx=move_x2;
 ly=move_y2;
 gx=move_x2;
 gy=move_y2;

 Sleep (sleepTime);

 sel_x0=move_x1;
 sel_y0=move_y1;
 sel_x=move_x2;
 sel_y=move_y2;
 move_sx=(float)sel_x0;
 move_sy=(float)sel_y0;
 leaps (sel_x0, sel_y0, sel_x, sel_y);
 leaps_n=0;
 moveAngle=0.0f;
 if (stateCPU)
 {
  stateCPU=0;
  state=0;
 }
 else
  state=5;
}



void paint ()
{
 if (pC<10 && !(pLoad>0.0f))
  pC++;

 // OpenGL animation code goes here
 glPushMatrix ();
 glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// glEnable (GL_MULTISAMPLE_ARB);


 // Фон
 glLoadIdentity ();  // Сброс просмотра
 glTranslatef (0.0f, 0.0f, -2.4f);
 glRotatef (-bgAngle, 0.0f, 0.0f, 1.0f);

 bgAngle+=0.05f*fpsTweak ();
 if (bgAngle>180.0f)
  bgAngle-=360.0f;

 if (state>=10 && res==2)
 {
  skyClGo-=darkSkyStep*fpsTweak ();
  if (skyClGo<darkSkyTo)
   skyClGo=darkSkyTo;
 }
 else if (skyClGo<skyCl)
 {
  skyClGo+=darkSkyStep*fpsTweak ();
  if (skyClGo>skyCl)
   skyClGo=skyCl;
 }
 glColor3f (1.0f*skyClGo, 1.0f*skyClGo, 1.0f*skyClGo);
 glCallList (bgList);


// glDisable (GL_MULTISAMPLE_ARB);


 // Доска
 glLoadIdentity ();  // Сброс просмотра


 // Intro
 if (pLoad>0.0f)
 {
  pLoad-=1.0f*fpsTweak ()*3;
  glTranslatef (0.0f, 0.0f, loadFar);
  glRotatef (-loadAngle, 0.0f, 0.0f, 1.0f);
  loadFar+=loadFarStep*fpsTweak ()*3;
  loadAngle+=loadAngleStep*fpsTweak ()*3;
  SetCursor (curWait);
  glEnable (GL_BLEND);
 }

 glColor3f (1.0f, 1.0f, 1.0f);
 glCallList (brdList);


 // Тёмные клетки
 glColor3f (1.0f, 1.0f, 1.0f);
 glBindTexture (GL_TEXTURE_2D, texture [2]);

 float brdCell=brdS/9.0f;
 float brdL2=brdL+brdS/9.0f, brdT2=brdT-brdS/9.0f;
 int xi, yi, c=0;
 for (yi=0; yi<8; yi++)
 {
  c++;

  for (xi=0; xi<8; xi++)
  {
   c++;
   if (c%2)
   {
    glBegin (GL_QUADS);
    glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL2+xi*brdCell, brdT2-(yi+1)*brdCell, brdZ);    // Низ лево
    glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL2+(xi+1)*brdCell, brdT2-(yi+1)*brdCell, brdZ);// Низ право
    glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL2+(xi+1)*brdCell, brdT2-yi*brdCell, brdZ);    // Верх право
    glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL2+xi*brdCell, brdT2-yi*brdCell, brdZ);        // Верх лево
    glEnd ();
   }
  }
 }


 // Угол доски
 glColor3f (1.0f, 1.0f, 1.0f);
 glBindTexture (GL_TEXTURE_2D, texture [5]);
 glBegin (GL_QUADS);
 glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL, brdT-brdCell, brdZ);        // Низ лево
 glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL+brdCell, brdT-brdCell, brdZ);// Низ право
 glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL+brdCell, brdT, brdZ);        // Верх право
 glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL, brdT, brdZ);                // Верх лево
 glEnd ();


 // Верхний край доски
 glColor3f (1.0f, 1.0f, 1.0f);
 glBindTexture (GL_TEXTURE_2D, texture [4]);
 for (xi=0; xi<8; xi++)
 {
  glBegin (GL_QUADS);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL2+xi*brdCell, brdT-brdCell, brdZ);    // Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL2+(xi+1)*brdCell, brdT-brdCell, brdZ);// Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL2+(xi+1)*brdCell, brdT, brdZ);        // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL2+xi*brdCell, brdT, brdZ);            // Верх лево
  glEnd ();
 }


 // Левый
 glColor3f (1.0f, 1.0f, 1.0f);
 glBindTexture (GL_TEXTURE_2D, texture [3]);
 for (yi=0; yi<8; yi++)
 {
  glBegin (GL_QUADS);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL, brdT2-(yi+1)*brdCell, brdZ);        // Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL+brdCell, brdT2-(yi+1)*brdCell, brdZ);// Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL+brdCell, brdT2-yi*brdCell, brdZ);    // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL, brdT2-yi*brdCell, brdZ);            // Верх лево
  glEnd ();
 }


 // Уточнение координат клеток
 if (pC==2)
 {
  int xs, ys=cy/2, xi2, yi2, c=0, i;
  bool chk;

  xs=mXar0 [0]-(mXar0 [1]-mXar0 [0])/2;

  for (xi=xs; xi<cx; xi++)
  {
   pixel=GetPixel (hDC, xi, ys);

   if ((isGray (pixel) && (c+1)%2) || (isWhite (pixel) && !((c+1)%2)))
   {
    chk=true;
    for (xi2=0; xi2<5; xi2++)
    {
     pixel=GetPixel (hDC, xi+xi2+1, ys);
     if ((!isGray (pixel) && (c+1)%2) || (!isWhite (pixel) && !((c+1)%2)))
      chk=false;
    }
    if (chk)
    {
     mXar1 [c]=xi;
     c++;
     if (c==8)
      break;      
    }
   }
  }

  if (c==8)
  {
   ys=cy/2+(mYar0 [1]-mYar0 [0]);
   for (i=xi+10; i<cx; i++)
   {
    pixel=GetPixel (hDC, i, ys);
    if (!isGray (pixel))
    {
     mXar1 [c]=i;
     break;
    }
   }
  }

  int mx=0, mxd;
  for (i=0; i<9; i++)
  {
   mxd=abs (mXar1 [i]-mXar0 [i]);
   if (mxd>mx)
    mx=mxd;
  }
  if (mx<25)
  {
   for (i=0; i<9; i++)
    mXar [i]=mXar1 [i];
  }
  else
  {
   for (i=0; i<9; i++)
    mXar [i]=mXar0 [i];
  }

  ys=mYar0 [0]-(mYar0 [1]-mYar0 [0])/2; xs=mXar [0]+(mXar [1]-mXar [0])/2; c=0;

  for (yi=ys; yi<cy; yi++)
  {
   pixel=GetPixel (hDC, xs, yi);

   if ((isGray (pixel) && !((c+1)%2)) || (isWhite (pixel) && (c+1)%2))
   {
    chk=true;
    for (yi2=0; yi2<5; yi2++)
    {
     pixel=GetPixel (hDC, xs, yi+yi2+1);
     if ((!isGray (pixel) && !((c+1)%2)) || (!isWhite (pixel) && (c+1)%2))
      chk=false;
    }
    if (chk)
    {
     mYar1 [c]=yi;
     c++;
     if (c==8)
      break;  
    }
   }
  }

  if (c==8)
  {
   mYar1 [c]=cy;

   for (i=yi+10; i<cy+10; i++)
   {
    pixel=GetPixel (hDC, xs, i);
    if (!isGray (pixel))
    {
     mYar1 [c]=i;
     break;
    }
   }
  }

  for (i=0; i<9; i++)
  {
   mxd=abs (mYar1 [i]-mYar0 [i]);
   if (mxd>mx)
    mx=mxd;
  }
  if (mx<25)
  {
   for (i=0; i<9; i++)
    mYar [i]=mYar1 [i];
  }
  else
  {
   for (i=0; i<9; i++)
    mYar [i]=mYar0 [i];
  }
  moreFPS=false;

  mouseMove ();
  SetTimer (hWnd, TIMER_MEL, 1000, NULL);
  playSound ("board");

  if (side)
  {
   state=3;
   SetCursor (curWait);
  }
  else
   SetCursor (curArrow);
 }


 if (pC>1)
 {
  // Выделение клетки
  if (state>1)
   glColor3f (colorCellOff [0], colorCellOff [1], colorCellOff [2]);
  else if (posHL==1)
   glColor3f (colorCellHL1 [0], colorCellHL1 [1], colorCellHL1 [2]);
  else if (posHL==2)
   glColor3f (colorCellHL2 [0], colorCellHL2 [1], colorCellHL2 [2]);
  else
   glColor3f (colorCellHL0 [0], colorCellHL0 [1], colorCellHL0 [2]);

  glBindTexture (GL_TEXTURE_2D, texture [0]);
  glBegin (GL_QUADS);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL2+posX*brdCell, brdT2-(posY+1)*brdCell, brdZ);    // Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL2+(posX+1)*brdCell, brdT2-(posY+1)*brdCell, brdZ);// Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL2+(posX+1)*brdCell, brdT2-posY*brdCell, brdZ);    // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL2+posX*brdCell, brdT2-posY*brdCell, brdZ);        // Верх лево
  glEnd ();


  // Выделение Y-координаты
  glColor3f (1.0f, 1.0f, 1.0f);
  glBindTexture (GL_TEXTURE_2D, texture [6]);
  glBegin (GL_QUADS);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL, brdT2-(posY+1)*brdCell, brdZ);        // Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL+brdCell, brdT2-(posY+1)*brdCell, brdZ);// Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL+brdCell, brdT2-posY*brdCell, brdZ);    // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL, brdT2-posY*brdCell, brdZ);            // Верх лево
  glEnd ();


  // X
  glColor3f (1.0f, 1.0f, 1.0f);
  glBindTexture (GL_TEXTURE_2D, texture [7]);
  glBegin (GL_QUADS);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL2+posX*brdCell, brdT-brdCell, brdZ);    // Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL2+(posX+1)*brdCell, brdT-brdCell, brdZ);// Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL2+(posX+1)*brdCell, brdT, brdZ);        // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL2+posX*brdCell, brdT, brdZ);            // Верх лево
  glEnd ();


  // Наименование координат
  char literaL [10]={'8', '7', '6', '5', '4', '3', '2', '1'};
  char literaT [10]={'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};
  glBindTexture (GL_TEXTURE_2D, texture [0]);

  literaY=brdT-brdCell/2.0f; literaZ=brdZ;
  literaScale=0.07f;
  for (xi=0; xi<8; xi++)
  {
   if (xi==posX)
    glColor3f (colorCoordHL [0], colorCoordHL [1], colorCoordHL [2]);
   else
    glColor3f (colorCoordX [0], colorCoordX [1], colorCoordX [2]);

   literaX=brdL2+brdCell/2.0f+brdCell*xi; 
   sprintf (literaText, "%c", literaT [xi]);
   glPrintLitera ();// Печать текста GL на экран
  }

  literaX=brdL+brdCell/2.0f;
  for (yi=0; yi<8; yi++)
  {
   if (yi==posY)
    glColor3f (colorCoordHL [0], colorCoordHL [1], colorCoordHL [2]);
   else
    glColor3f (colorCoordY [0], colorCoordY [1], colorCoordY [2]);

   literaY=brdT2-brdCell/2.0f-brdCell*yi; 
   sprintf (literaText, "%c", literaL [yi]);
   glPrintLitera ();// Печать текста GL на экран
  }


  // Фишки
  if (state==1)
  {
   rvAngle-=360.0f/rvSteps*fpsTweak ();
   if (rvAngle<-360.0f)
    rvAngle+=360.0f;
  }

  glLoadIdentity ();// Сброс просмотра

  glEnable (GL_BLEND);
  glBindTexture (GL_TEXTURE_2D, texture [8]);
  glBegin (GL_QUADS);

  int xi, yi, c=0;
  for (yi=0; yi<8; yi++)
  {
   for (xi=0; xi<8; xi++)
   {
    if (init_d [c]!='0' && !(state==1 && sel_x0==xi && sel_y0==yi) && !((state==2 || state==5) && sel_x0==xi && sel_y0==yi))
    {
     if ((init_d [c]=='1' && !side) || (init_d [c]=='a' && side))
      glColor3f (colorPlayer [0], colorPlayer [1], colorPlayer [2]);
     else if ((init_d [c]=='a' && !side) || (init_d [c]=='1' && side))
      glColor3f (colorCPU [0], colorCPU [1], colorCPU [2]);

     glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL2+xi*brdCell, brdT2-(yi+1)*brdCell, brdZ);    // Низ лево
     glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL2+(xi+1)*brdCell, brdT2-(yi+1)*brdCell, brdZ);// Низ право
     glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL2+(xi+1)*brdCell, brdT2-yi*brdCell, brdZ);    // Верх право
     glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL2+xi*brdCell, brdT2-yi*brdCell, brdZ);        // Верх лево
    }
    c++;
   }
  }

  glEnd ();

  // Статистика
  if (state==2 || state==5)
  {
   moveAngle-=360.0f/rvSteps*fpsTweak ();
   if (moveAngle<-360.0f)
    moveAngle+=360.0f;
  }

  float xr=8.1f, yr=-1.0f;
  glLoadIdentity ();// Сброс просмотра
  glTranslatef (brdL2+(xr+1)*brdCell-brdCell/2.0f, brdT2-(yr+1)*brdCell+brdCell/2.0f, brdZ);
  if (state==2)
   glRotatef (moveAngle, 0.0f, 0.0f, 1.0f);
  glBindTexture (GL_TEXTURE_2D, texture [8]);
  glBegin (GL_QUADS);
  if (!side)
   glColor3f (colorPlayer [0], colorPlayer [1], colorPlayer [2]);
  else
   glColor3f (colorCPU [0], colorCPU [1], colorCPU [2]);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (-brdCell/(2.0f), -brdCell/2.0f, 0.0f);// Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdCell/(2.0f), -brdCell/2.0f, 0.0f); // Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdCell/(2.0f), brdCell/2.0f, 0.0f);  // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (-brdCell/(2.0f), brdCell/2.0f, 0.0f); // Верх лево
  glEnd ();

  yr=0.0f;
  glLoadIdentity ();// Сброс просмотра
  glTranslatef (brdL2+(xr+1)*brdCell-brdCell/2.0f, brdT2-(yr+1)*brdCell+brdCell/2.0f, brdZ);
  if (state==5)
   glRotatef (moveAngle, 0.0f, 0.0f, 1.0f);
  glBindTexture (GL_TEXTURE_2D, texture [8]);
  glBegin (GL_QUADS);
  if (!side)
   glColor3f (colorCPU [0], colorCPU [1], colorCPU [2]);
  else
   glColor3f (colorPlayer [0], colorPlayer [1], colorPlayer [2]);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (-brdCell/(2.0f), -brdCell/2.0f, 0.0f);// Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdCell/(2.0f), -brdCell/2.0f, 0.0f); // Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdCell/(2.0f), brdCell/2.0f, 0.0f);  // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (-brdCell/(2.0f), brdCell/2.0f, 0.0f); // Верх лево

  glEnd ();


  // Кнопки
  glLoadIdentity ();// Сброс просмотра

  xr=8.1f, yr=1.0f;
  glBindTexture (GL_TEXTURE_2D, texture [16]);
  glBegin (GL_QUADS);
  if (button!=1)
  {
   if ((cPlayer+cCPU)>0)
   {
    if (state==12)
     glColor3f (colorOn [0], colorOn [1], colorOn [2]);
    else
     glColor3f (colorRestB [0], colorRestB [1], colorRestB [2]);
   }
   else
    glColor3f (colorOff [0], colorOff [1], colorOff [2]);
  }
  else
   glColor3f (colorCellHL1 [0], colorCellHL1 [1], colorCellHL1 [2]);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL2+xr*brdCell, brdT2-(yr+1)*brdCell, brdZ);    // Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-(yr+1)*brdCell, brdZ);// Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-yr*brdCell, brdZ);    // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL2+xr*brdCell, brdT2-yr*brdCell, brdZ);        // Верх лево
  glEnd ();

  xr=8.1f, yr=2.0f;
  glBindTexture (GL_TEXTURE_2D, texture [17]);
  glBegin (GL_QUADS);
  if (button!=2)
   glColor3f (colorRestB [0], colorRestB [1], colorRestB [2]);
  else
   glColor3f (colorCellHL1 [0], colorCellHL1 [1], colorCellHL1 [2]);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL2+xr*brdCell, brdT2-(yr+1)*brdCell, brdZ);    // Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-(yr+1)*brdCell, brdZ);// Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-yr*brdCell, brdZ);    // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL2+xr*brdCell, brdT2-yr*brdCell, brdZ);        // Верх лево
  glEnd ();

  xr=8.1f, yr=3.0f;
  glBindTexture (GL_TEXTURE_2D, texture [10]);
  glBegin (GL_QUADS);
  if (button!=3)
   glColor3f (colorRestB [0], colorRestB [1], colorRestB [2]);
  else
   glColor3f (colorCellHL1 [0], colorCellHL1 [1], colorCellHL1 [2]);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL2+xr*brdCell, brdT2-(yr+1)*brdCell, brdZ);    // Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-(yr+1)*brdCell, brdZ);// Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-yr*brdCell, brdZ);    // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL2+xr*brdCell, brdT2-yr*brdCell, brdZ);        // Верх лево
  glEnd ();

  xr=8.1f, yr=4.0f;
  glBindTexture (GL_TEXTURE_2D, texture [11]);
  glBegin (GL_QUADS);
  if (button!=4)
   glColor3f (colorRestB [0], colorRestB [1], colorRestB [2]);
  else
   glColor3f (colorCellHL1 [0], colorCellHL1 [1], colorCellHL1 [2]);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL2+xr*brdCell, brdT2-(yr+1)*brdCell, brdZ);    // Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-(yr+1)*brdCell, brdZ);// Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-yr*brdCell, brdZ);    // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL2+xr*brdCell, brdT2-yr*brdCell, brdZ);        // Верх лево
  glEnd ();

  xr=8.1f, yr=5.0f;
  glBindTexture (GL_TEXTURE_2D, texture [14]);
  glBegin (GL_QUADS);
  if (button!=5)
   glColor3f (colorRestB [0], colorRestB [1], colorRestB [2]);
  else
   glColor3f (colorCellHL1 [0], colorCellHL1 [1], colorCellHL1 [2]);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL2+xr*brdCell, brdT2-(yr+1)*brdCell, brdZ);    // Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-(yr+1)*brdCell, brdZ);// Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-yr*brdCell, brdZ);    // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL2+xr*brdCell, brdT2-yr*brdCell, brdZ);        // Верх лево
  glEnd ();

  xr=8.1f, yr=6.0f;
  glBindTexture (GL_TEXTURE_2D, texture [12]);
  glBegin (GL_QUADS);
  if (button!=6)
   glColor3f (colorRestB [0], colorRestB [1], colorRestB [2]);
  else
   glColor3f (colorCellHL1 [0], colorCellHL1 [1], colorCellHL1 [2]);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL2+xr*brdCell, brdT2-(yr+1)*brdCell, brdZ);    // Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-(yr+1)*brdCell, brdZ);// Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-yr*brdCell, brdZ);    // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL2+xr*brdCell, brdT2-yr*brdCell, brdZ);        // Верх лево
  glEnd ();

  xr=8.1f, yr=7.0f;
  glBindTexture (GL_TEXTURE_2D, texture [9]);
  glBegin (GL_QUADS);
  if (button!=7)
   glColor3f (colorExitB [0], colorExitB [1], colorExitB [2]);
  else
   glColor3f (colorCellHL1 [0], colorCellHL1 [1], colorCellHL1 [2]);
  glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL2+xr*brdCell, brdT2-(yr+1)*brdCell, brdZ);    // Низ лево
  glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-(yr+1)*brdCell, brdZ);// Низ право
  glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL2+(xr+1)*brdCell, brdT2-yr*brdCell, brdZ);    // Верх право
  glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL2+xr*brdCell, brdT2-yr*brdCell, brdZ);        // Верх лево
  glEnd ();

  glDisable (GL_BLEND);


  // Количество ходов
  glBindTexture (GL_TEXTURE_2D, texture [0]);
  xr=8.8f; yr=-1.0f;

  literaY=brdT2-brdCell/2.0f-brdCell*yr; 
  literaX=brdL2+brdCell/2.0f+brdCell*xr;
  literaScale=0.12f;
  sprintf (literaText, "%d", cPlayer);
  if (!side)
   glColor3f (colorPlayerStat [0], colorPlayerStat [1], colorPlayerStat [2]);
  else
   glColor3f (colorCPUStat [0], colorCPUStat [1], colorCPUStat [2]);
  glPrintLitera ();// Печать текста GL на экран
  
  yr=0.0f;

  literaY=brdT2-brdCell/2.0f-brdCell*yr; 
  literaX=brdL2+brdCell/2.0f+brdCell*xr;
  sprintf (literaText, "%d", cCPU);
  if (!side)
   glColor3f (colorCPUStat [0], colorCPUStat [1], colorCPUStat [2]);
  else
   glColor3f (colorPlayerStat [0], colorPlayerStat [1], colorPlayerStat [2]);
  glPrintLitera ();// Печать текста GL на экран

  // Язык
  yr=2.0f;

  literaY=brdT2-brdCell/2.0f-brdCell*yr; 
  literaX=brdL2+brdCell/2.0f+brdCell*xr;
  if (lang==0)
   sprintf (literaText, "Ru");
  else if (lang==1)
   sprintf (literaText, "En");
  if (button!=2)
   glColor3f (colorVol [0], colorVol [1], colorVol [2]);
  else
   glColor3f (colorCellHL1 [0], colorCellHL1 [1], colorCellHL1 [2]);
  glPrintLitera ();// Печать текста GL на экран

  // Громкость
  yr=3.0f;

  literaY=brdT2-brdCell/2.0f-brdCell*yr;
  literaX=brdL2+brdCell/2.0f+brdCell*xr;
  sprintf (literaText, "%d", sndVol*25);
  if (button!=3)
   glColor3f (colorVol [0], colorVol [1], colorVol [2]);
  else
   glColor3f (colorCellHL1 [0], colorCellHL1 [1], colorCellHL1 [2]);
  glPrintLitera ();// Печать текста GL на экран

  yr=4.0f;

  literaY=brdT2-brdCell/2.0f-brdCell*yr;
  literaX=brdL2+brdCell/2.0f+brdCell*xr;
  sprintf (literaText, "%d", melVol*25);
  if (button!=4)
   glColor3f (colorVol [0], colorVol [1], colorVol [2]);
  else
   glColor3f (colorCellHL1 [0], colorCellHL1 [1], colorCellHL1 [2]);
  glPrintLitera ();// Печать текста GL на экран


  // Таймер выхода
  if (qC!=0)
  {
   yr=7.0f;

   literaY=brdT2-brdCell/2.0f-brdCell*yr;
   literaX=brdL2+brdCell/2.0f+brdCell*xr;
   sprintf (literaText, "%d", qCmx-qC);
   if (button!=7)
    glColor3f (colorExitT [0], colorExitT [1], colorExitT [2]);
   else
    glColor3f (colorCellHL1 [0], colorCellHL1 [1], colorCellHL1 [2]);
   glPrintLitera ();// Печать текста GL на экран
  }


  // Реверсная фишка
  if (state==1)
  {
   xr=sel_x0;
   yr=sel_y0;
   glLoadIdentity ();// Сброс просмотра
   glEnable (GL_BLEND);
   glTranslatef (brdL2+(xr+1)*brdCell-brdCell/2.0f, brdT2-(yr+1)*brdCell+brdCell/2.0f, brdZ);
   glRotatef (rvAngle, 0.0f, 0.0f, 1.0f);
   glBindTexture (GL_TEXTURE_2D, texture [8]);
   glBegin (GL_QUADS);

   if ((init_d [getPos (sel_x0, sel_y0)]=='1' && !side) || (init_d [getPos (sel_x0, sel_y0)]=='a' && side))
    glColor3f (colorPlayer [0], colorPlayer [1], colorPlayer [2]);
   else if ((init_d [getPos (sel_x0, sel_y0)]=='a' && !side) || (init_d [getPos (sel_x0, sel_y0)]=='1' && side))
    glColor3f (colorCPU [0], colorCPU [1], colorCPU [2]);

   glTexCoord2f (0.0f, 0.0f); glVertex3f (-brdCell/(2.0f), -brdCell/2.0f, 0.0f);// Низ лево
   glTexCoord2f (1.0f, 0.0f); glVertex3f (brdCell/(2.0f), -brdCell/2.0f, 0.0f); // Низ право
   glTexCoord2f (1.0f, 1.0f); glVertex3f (brdCell/(2.0f), brdCell/2.0f, 0.0f);  // Верх право
   glTexCoord2f (0.0f, 1.0f); glVertex3f (-brdCell/(2.0f), brdCell/2.0f, 0.0f); // Верх лево
   glEnd ();
   glDisable (GL_BLEND);
  }
  else if (state==2 || state==5)
  {
   int sel_x1, sel_y1, sel_x10, sel_y10;
   if (leaps_stay>0.0f)
    leaps_stay-=1.0f*fpsTweak ();
   else
   {
   if (leaps_c>-1)
   {
    sel_x1=(float)leaps_x1 [leaps_n];
    sel_y1=(float)leaps_y1 [leaps_n];
    if (leaps_c>0 && leaps_n>0)
    {
     sel_x10=(float)leaps_x1 [leaps_n-1];
     sel_y10=(float)leaps_y1 [leaps_n-1];
    }
    else
    {
     sel_x10=(float)sel_x0;
     sel_y10=(float)sel_y0;
    }
   }
   else
   {
    sel_x1=(float)sel_x;
    sel_y1=(float)sel_y;
    sel_x10=(float)sel_x0;
    sel_y10=(float)sel_y0;
   }

   if (sel_x1>sel_x10)
   {
    move_sx+=move_sa*fpsTweak ();
    if (move_sx>=(float)sel_x1)
     move_sx=(float)sel_x1;
   }
   else
   {
    move_sx-=move_sa*fpsTweak ();
    if (move_sx<=(float)sel_x1)
     move_sx=(float)sel_x1;
   }
   if (sel_y1>sel_y10)
   {
    move_sy+=move_sa*fpsTweak ();
    if (move_sy>=(float)sel_y1)
     move_sy=(float)sel_y1;
   }
   else
   {
    move_sy-=move_sa*fpsTweak ();
    if (move_sy<=(float)sel_y1)
     move_sy=(float)sel_y1;
   }
   if (move_sx==(float)sel_x1 && move_sy==(float)sel_y1)
   {
    char t [16];
    if (abs(sel_x-sel_x0)<2 && abs(sel_y-sel_y0)<2)
     sprintf (t, "dash");
    else
     sprintf (t, "move%d", (rand ()%5+1));
    playSound (t);
    leaps_stay=6.0f+float(rand ()%7);

    if (leaps_n<leaps_c)
     leaps_n++;
    else
    {
     init_d [getPos (sel_x, sel_y)]=init_d [getPos (sel_x0, sel_y0)];
     init_d [getPos (sel_x0, sel_y0)]='0';
     if (state==2)
     {
      cPlayer++;
      if (side)
      {
       check_corner (init_d);
       if (square_white || square_black)
        turnOver ();
       else
        state=3;
      }
      else
       state=3;
     }
     else if (state==5)
     {
      cCPU++;
      stats_moves++;
      SetCursor (curArrow);

      if (!side)
      {
       check_corner (init_d);
       if (square_white || square_black)
        turnOver ();
       else
        state=0;
      }
      else
       state=0;

      cellInfo ();
     }
    }
   }
  }

  xr=move_sx;
  yr=move_sy;
  glLoadIdentity ();// Сброс просмотра
  glEnable (GL_BLEND);
  glTranslatef (brdL2+(xr+1)*brdCell-brdCell/2.0f, brdT2-(yr+1)*brdCell+brdCell/2.0f, brdZ);

  glBindTexture (GL_TEXTURE_2D, texture [8]);
  glBegin (GL_QUADS);
  if (state==2 || state==3)
  {
   if (!side)
    glColor3f (colorPlayer [0], colorPlayer [1], colorPlayer [2]);
   else
    glColor3f (colorCPU [0], colorCPU [1], colorCPU [2]);
   }
   else if (state==5 || state==0)
   {
    if (!side)
     glColor3f (colorCPU [0], colorCPU [1], colorCPU [2]);
    else
     glColor3f (colorPlayer [0], colorPlayer [1], colorPlayer [2]);
   }
   glTexCoord2f (0.0f, 0.0f); glVertex3f (-brdCell/(2.0f), -brdCell/2.0f, 0.0f);// Низ лево
   glTexCoord2f (1.0f, 0.0f); glVertex3f (brdCell/(2.0f), -brdCell/2.0f, 0.0f); // Низ право
   glTexCoord2f (1.0f, 1.0f); glVertex3f (brdCell/(2.0f), brdCell/2.0f, 0.0f);  // Верх право
   glTexCoord2f (0.0f, 1.0f); glVertex3f (-brdCell/(2.0f), brdCell/2.0f, 0.0f); // Верх лево
   glEnd ();
   glDisable (GL_BLEND);
  }

  if (state==10 || state==12)
  {
   glLoadIdentity ();// Сброс просмотра
   glEnable (GL_BLEND);
   glColor4f(1.0f, 1.0f, 1.0f, 0.0f+(90.0f-resultAngle)*0.65f/90.0f);// 0.65f
   glCallList (infList);
   glDisable (GL_BLEND);

   if (res==3)
   {
    if (lang==0)
    {
     literaX=-0.57f;
     sprintf (txt, "Ничья");
    }
    else
    {
     literaX=-0.486f;
     sprintf (txt, "Draw");
    }
   }
   else if (res==1)
   {
    if (lang==0)
    {
     literaX=-0.734f;
     sprintf (txt, "Выигрыш");
    }
    else
    {
     literaX=-0.384f;
     sprintf (txt, "Win");
    }
   }
   else
   {
    if (lang==0)
    {
     literaX=-0.834f;
     sprintf (txt, "Проигрыш");
    }
    else
    {
     literaX=-0.477f;
     sprintf (txt, "Lose");
    }
   }

   if (resultAngle>0.0f)
    resultAngle-=fpsTweak ();
   else if (!resultOff)
   {
    resultAngle=0.0f;
    resultOff=true;

    char speech1 [8], speech2 [8], speech [16];

    if (lang==0)
     sprintf (speech1, "ru_");
    else
     sprintf (speech1, "en_");

    if (res==1)
     sprintf (speech2, "win");
    else if (res==2)
     sprintf (speech2, "lose");
    else
     sprintf (speech2, "draw");

    sprintf (speech, "%s%s", speech1, speech2);
    playSound (speech);

    SetCursor (curNew);
    state=12;
   }

   GLfloat LightDiffuse []={colorH [0]*1.5f, colorH [1]*1.5f, colorH [2]*0.5f, light_pos*1.5f};// Значения диффузного света
   GLfloat LightPosition []={light_pos, light_pos, -light_pos, 1.0f};      // Позиция света
   light_pos+=light_d*0.01f*fpsTweak ();
   if (light_pos>1.0f)
   {
    light_d=-1;
    light_pos=1.0f;
   }
   else if (light_pos<0.0f)
   {
    light_d=1;
    light_pos=0.0f;
   }
   glLightfv (GL_LIGHT1, GL_DIFFUSE, LightDiffuse);  // Установка Диффузного Света
   glLightfv (GL_LIGHT1, GL_POSITION, LightPosition);// Позиция света
   glEnable (GL_LIGHT1); // Разрешение источника света номер один
   glEnable (GL_LIGHTING);// Разрешить освещение

   literaY=-0.082f;
   literaScale=0.32f;
   sprintf (literaText, "%s", txt);
   glColor4f (colorH [0], colorH [1], colorH [2], 0.0f+(90.0f-resultAngle)*1.0f/90.0f);
   glPrintLitera ();// Печать текста GL на экран

   glDisable (GL_LIGHTING);// Запрет освещения
  }


  if (button)
  {
   if (button==1)
   {
    yr=1.0f;
    if (lang==0)
     sprintf (txt, "     сначала");
    else
     sprintf (txt, "     restart");
   }
   else if (button==2)
   {
    yr=2.0f;
    if (lang==0)
     sprintf (txt, "        язык");
    else
     sprintf (txt, "    language");
   }
   else if (button==3)
   {
    yr=3.0f;
    if (lang==0)
     sprintf (txt, "        звук");
    else
     sprintf (txt, "       sound");
   }
   else if (button==4)
   {
    yr=4.0f;
    if (lang==0)
     sprintf (txt, "     мелодия");
    else
     sprintf (txt, "      melody");
   }
   else if (button==5)
   {
    yr=5.0f;
    if (lang==0)
     sprintf (txt, "  достижения");
    else
     sprintf (txt, "achievements");
   }
   else if (button==6)
   {
    yr=6.0f;
    if (lang==0)
     sprintf (txt, " о программе");
    else
     sprintf (txt, "       about");
   }
   else if (button==7)
   {
    yr=7.0f;
    if (lang==0)
     sprintf (txt, "       выход");
    else
     sprintf (txt, "       quit");
   }

   xr=4.0f;
   glLoadIdentity ();// Сброс просмотра
   glEnable (GL_BLEND);
   glColor4f(1.0, 1.0, 1.0, 0.85f);
   glBindTexture (GL_TEXTURE_2D, texture [15]);
   glBegin (GL_QUADS);
   glTexCoord2f (0.0f, 0.0f); glVertex3f (brdL2+xr*brdCell, brdT2-(yr+1)*brdCell, brdZ);    // Низ лево
   glTexCoord2f (1.0f, 0.0f); glVertex3f (brdL2+(xr+4)*brdCell, brdT2-(yr+1)*brdCell, brdZ);// Низ право
   glTexCoord2f (1.0f, 1.0f); glVertex3f (brdL2+(xr+4)*brdCell, brdT2-yr*brdCell, brdZ);    // Верх право
   glTexCoord2f (0.0f, 1.0f); glVertex3f (brdL2+xr*brdCell, brdT2-yr*brdCell, brdZ);        // Верх лево
   glEnd ();
   glDisable (GL_BLEND);

   literaY=brdT2-brdCell/2.0f+0.0095f-brdCell*yr;
   literaX=brdL2+brdCell/2.0f+brdCell*xr;
   literaScale=0.12f;
   sprintf (literaText, "%s", txt);
   glColor3f (colorCellHL1 [0]/1.5f, colorCellHL1 [1]/1.5f, colorCellHL1 [2]/1.5f);
   glPrintLitera ();// Печать текста GL на экран
  }


  if (infOn)
  {
   glLoadIdentity ();// Сброс просмотра
   glEnable (GL_BLEND);
   glColor4f(1.0f, 1.0f, 1.0f, 0.9f);
   glCallList (infList);
   glDisable (GL_BLEND);

   literaScale=0.32f;
   literaY=0.55f;
   if (infOn==1)
   {
    if (lang==0)
    {
     literaX=-0.654f;//-0.734f;
     sprintf (literaText, "Уголки");
    }
    else
    {
     literaX=-0.734f;
     sprintf (literaText, "Corners");
    }
   }
   else
   {
    if (lang==0)
    {
     literaX=-0.554f;
     sprintf (literaText, "Итоги");
    }
    else
    {
     literaX=-0.734f;
     sprintf (literaText, "Summary");
    }
   }

   glColor3f (colorH [0], colorH [1], colorH [2]);
   glPrintLitera ();// Печать текста GL на экран

   yr=1.75f;

   char infTxt [10] [100];
   if (infOn==1)
   {
    xr=-0.25f;

    if (lang==0)
    {
     char infTxt1 [10] [100]={" Надо провести шашки в противоположный",
                              "уголок. Можно ходить на одну клетку или",
                              "прыжками через шашки - по горизонтали и",
                              "вертикали. Чтобы сделать ход, нужно",
                              "кликнуть на шашку, а затем на конечную",
                              "точку в цепочке перемещений.",
                              "",
                              ""
                             };
     memcpy (infTxt, infTxt1, 1000);
    }
    else
    {
     char infTxt1 [10] [100]={" The goal of the game is to draw checkers",
                              "into the opposite corner. You can move on",
                              "one cell or by jumping through checkers -",
                              "horizontally and vertically. To make a",
                              "move, you need to click on the checker,",
                              "and then on the end point in the movement",
                              "chain.",
                              ""
                             };
     memcpy (infTxt, infTxt1, 1000);
    }
   }
   else
   {
    xr=-0.15f;

    if (lang==0)
    {
     char infTxt1 [10] [100]={"            Партий:",
                              "          Выиграно:",                 
                              "         Проиграно:",
                              "            Вничью:",
                              "    Начато сначала:",
                              "        Недоиграно:",
                              "          Доиграно:",
                              "             Ходов:"
                             };
     memcpy (infTxt, infTxt1, 1000);
    }
    else
    {
     char infTxt1 [10] [100]={"             Total:",
                              "              Wins:",                 
                              "             Loses:",
                              "             Draws:",
                              "         Restarted:",
                              "      Not finished:",
                              "          Finished:",
                              "             Moves:"
                             };
     memcpy (infTxt, infTxt1, 1000);
    }
   }

   glColor3f (colorTxt [0], colorTxt [1], colorTxt [2]);

   for (yi=0; yi<8; yi++)
   {
    literaY=brdT2-brdCell/2.0f-brdCell*(yr+yi*0.5f)-0.0225f;
    literaX=brdL2+brdCell/2.0f+brdCell*xr-0.0025f;
    literaScale=0.07f;
    sprintf (literaText, "%s", infTxt [yi]);
    glPrintLitera ();// Печать текста GL на экран
   }

   if (infOn==2)
   {
    xr=3.25f; yr=1.76f;
    long stats_total=stats_wins+stats_loses+stats_draws+stats_restart+stats_notfin;
    long stats_fin=stats_wins+stats_loses+stats_draws;
    long stats [10]={stats_total, stats_wins, stats_loses, stats_draws, stats_restart, stats_notfin, stats_fin, stats_moves};

    glColor3f (colorVol [0], colorVol [1], colorVol [2]);

    for (yi=0; yi<8; yi++)
    {
     literaY=brdT2-brdCell/2.0f-brdCell*(yr+yi*0.5f)-0.0225f;
     literaX=brdL2+brdCell/2.0f+brdCell*xr-0.0025f;
     literaScale=0.07f;
     sprintf (literaText, "%d", stats [yi]);
     glPrintLitera ();// Печать текста GL на экран
    }
    glColor3f (colorTxt [0], colorTxt [1], colorTxt [2]);
   }

   xr=-0.25f; yr=1.75f;

   if (infOn==1)
   {
    literaY=brdT2-brdCell/2.0f-brdCell*(yr+9*0.5f)-0.0025f;
    literaX=brdL2+brdCell/2.0f+brdCell*xr-0.0025f;
    if (lang==0)
     sprintf (literaText, "                         Маркичев Д. 2019");
    else
     sprintf (literaText, "                       D. Markichev, 2019");
    glColor3f (colorTxtB [0], colorTxtB [1], colorTxtB [2]);
    glPrintLitera ();// Печать текста GL на экран
   }
  }
 }

 fpsC ();
// sprintf (mb, "ok");
// statusBar ();

 glPopMatrix ();
 SwapBuffers (hDC);
}

void mouseMove ()
{
 int xi, yi;

 if (blur_on)
  return;

 GetCursorPos (&mypoint);

 if (infOn && mypoint.x>=mXar [0]-(mXar [1]-mXar [0]) && mypoint.x<mXar [8] && mypoint.y>=mYar [0]-(mYar [1]-mYar [0]) && mypoint.y<mYar [8])
 {
  button=0;
  SetCursor (curOff);
  return;
 }

 int field=0, fldX=posX, fldY=posY;
 for (xi=0; xi<9; xi++)
 {
  if (mypoint.x>=mXar [xi] && mypoint.x<mXar [xi+1])
  {
   posX=xi;
   field++;

   break;
  }
 }

 for (yi=0; yi<9; yi++)
 {
  if (mypoint.y>=mYar [yi] && mypoint.y<mYar [yi+1])
  {
   posY=yi;
   field++;
   break;
  }
 }

 if (field<2)
 {
  posX=fldX;
  posY=fldY;
 }

 cellInfo ();

 int bL=button;
 button=0;
 float ri, qi=float(mXar [8]-mXar [7])/25.0f;

 if ((mypoint.x>(mXar [8]+(mXar [8]-mXar [7])/10) && mypoint.x<(mXar [8]+(mXar [8]-mXar [7])*11/10)))
 {
  if (mypoint.y>=mYar [7] && mypoint.y<mYar [8])
  {
   xi=abs ((float)mypoint.x-((float)mXar [8]+float(mXar [8]-mXar [7])*6.0f/10.0f));
   yi=abs ((float)mypoint.y-((float)mYar [7]+float(mYar [8]-mYar [7])*39.0f/40.0f/2.0f));
   ri=sqrt (pow (xi, 2)+pow (yi, 2));
   if (ri<float(mXar [8]-mXar [7])/2.0f-qi)
    button=7;
  }
  if (mypoint.y>=mYar [6] && mypoint.y<mYar [7])
  {
   xi=abs ((float)mypoint.x-((float)mXar [8]+float(mXar [8]-mXar [7])*6.0f/10.0f));
   yi=abs ((float)mypoint.y-((float)mYar [6]+float(mYar [8]-mYar [7])*39.0f/40.0f/2.0f));
   ri=sqrt (pow (xi, 2)+pow (yi, 2));
   if (ri<float(mXar [8]-mXar [7])/2.0f-qi)
    button=6;
  }
  if (mypoint.y>=mYar [5] && mypoint.y<mYar [6])
  {
   xi=abs ((float)mypoint.x-((float)mXar [8]+float(mXar [8]-mXar [7])*6.0f/10.0f));
   yi=abs ((float)mypoint.y-((float)mYar [5]+float(mYar [8]-mYar [7])*39.0f/40.0f/2.0f));
   ri=sqrt (pow (xi, 2)+pow (yi, 2));
   if (ri<float(mXar [8]-mXar [7])/2.0f-qi)
    button=5;
  }
  if (mypoint.y>=mYar [4] && mypoint.y<mYar [5])
  {
   xi=abs ((float)mypoint.x-((float)mXar [8]+float(mXar [8]-mXar [7])*6.0f/10.0f));
   yi=abs ((float)mypoint.y-((float)mYar [4]+float(mYar [8]-mYar [7])*39.0f/40.0f/2.0f));
   ri=sqrt (pow (xi, 2)+pow (yi, 2));
   if (ri<float(mXar [8]-mXar [7])/2.0f-qi)
    button=4;
  }
  if (mypoint.y>=mYar [3] && mypoint.y<mYar [4])
  {
   xi=abs ((float)mypoint.x-((float)mXar [8]+float(mXar [8]-mXar [7])*6.0f/10.0f));
   yi=abs ((float)mypoint.y-((float)mYar [3]+float(mYar [8]-mYar [7])*39.0f/40.0f/2.0f));
   ri=sqrt (pow (xi, 2)+pow (yi, 2));
   if (ri<float(mXar [8]-mXar [7])/2.0f-qi)
    button=3;
  }
  if (mypoint.y>=mYar [2] && mypoint.y<mYar [3])
  {
   xi=abs ((float)mypoint.x-((float)mXar [8]+float(mXar [8]-mXar [7])*6.0f/10.0f));
   yi=abs ((float)mypoint.y-((float)mYar [2]+float(mYar [8]-mYar [7])*39.0f/40.0f/2.0f));
   ri=sqrt (pow (xi, 2)+pow (yi, 2));
   if (ri<float(mXar [8]-mXar [7])/2.0f-qi)
    button=2;
  }
  if (mypoint.y>=mYar [1] && mypoint.y<mYar [2])
  {
   xi=abs ((float)mypoint.x-((float)mXar [8]+float(mXar [8]-mXar [7])*6.0f/10.0f));
   yi=abs ((float)mypoint.y-((float)mYar [1]+float(mYar [8]-mYar [7])*39.0f/40.0f/2.0f));
   ri=sqrt (pow (xi, 2)+pow (yi, 2));
   if (ri<float(mXar [8]-mXar [7])/2.0f-qi)
    button=1;
  }
 }

 if (bL!=button && button!=0)
  playSound ("select");

 if (button!=0)
  SetCursor (curArrow);
 else if (state==10)
  SetCursor (curWait);
 else if (state==12)
  SetCursor (curNew);
 else if (state!=0 && state!=1 && !button)
  SetCursor (curWait);
}

void mouseClick ()
{
 GetCursorPos (&mypoint);

 if (infOn && mypoint.x>=mXar [0]-(mXar [1]-mXar [0]) && mypoint.x<mXar [8] && mypoint.y>=mYar [0]-(mYar [1]-mYar [0]) && mypoint.y<mYar [8])
 {
  infOn=0;
  playSound ("shake");
  mouseMove ();
  return;
 }

 if (!button)
  playerMove ();
 else if (button==1)
  Restart ();
 else if (button==2)
 {
  if (lang==0)
   lang=1;
  else
   lang=0;

  playSound ("turn_on");
 }
 else if (button==3)
 {
  sndVol++;
  if (sndVol>4)
   sndVol=0;

  soundVol=sndVol*250;
  if (sndVol!=0)
  {
   if (sndVol==1)
    soundOn=true;
   playSound ("turn_on");
  }
  else
  {
   soundOn=false;
   playSound ("turn_off", 100, 25);
  }
 }
 else if (button==4)
 {
  melVol++;
  if (melVol>4)
   melVol=0;

  if (melVol==0)
  {
   meloTurnOff=true;
   playSound ("turn_off");
  }
  else if (melVol==1)
   meloTurnOn=true;

  if (melVol>0)
   playSound ("turn_on");

  meloVol=0;
  SetTimer (hWnd, TIMER_MELON, 1000, NULL);
 }
 else if (button==5)
 {
  if (infOn!=2)
  {
   infOn=2;
   playSound ("shake");
  }
  else
  {
   infOn=0;
   playSound ("shake");
  }
 }
 else if (button==6)
 {
  if (infOn!=1)
  {
   infOn=1;
   playSound ("shake");
  }
  else
  {
   infOn=0;
   playSound ("shake");
  }
 }
 else if (button==7)
 {
  if (qC==0)
  {
   qC=1;
   playSound ("turn_on");
   SetTimer (hWnd, TIMER_QUIT, 1000, NULL);
  }
  else
  {
   KillTimer (hWnd, TIMER_QUIT);
   qC=0;
   playSound ("turn_off");
  }
 }
}

int getPos (int x, int y)
{
 int p;

 if (x>-1 && x<8 && y>-1 && y<8)
  p=y*8+x;
 else
  p=0;

 return p;
}

void playerMove ()
{
 if (state>=10)
  Restart ();
 else
 {
  if (state!=0 && state!=1)
  {
   SetCursor (curWait);
   return;
  }

  if (state==0)
  {
   if (init_d [getPos (posXl, posYl)]=='1')
   {
    sel_x0=posXl;
    sel_y0=posYl;
    state=1;
    playSound ("ready");
   }
  }
  else if (state==1)
  {
   if (init_d [getPos (posXl, posYl)]=='1')
   {
    if (sel_x0==posXl && sel_y0==posYl)
    {
     state=0;
     playSound ("drop");
    }
    else
    {
     sel_x0=posXl;
     sel_y0=posYl;
     playSound ("ready");
    }
   }
   else if (init_d [getPos (posXl, posYl)]=='0')
   {
    if (check_move (sel_x0, sel_y0, posXl, posYl)==true)
    {
     move1=true;
     sel_x=posXl;
     sel_y=posYl;
     move_sx=(float)sel_x0;
     move_sy=(float)sel_y0;
     leaps (sel_x0, sel_y0, posXl, posYl);
     leaps_n=0;
     moveAngle=0.0f;
     stateCPU=0;
     state=2;
     SetCursor (curWait);
    }
    else
     playSound ("break");
   }
  }
 }
}



void cellInfo ()
{
 int r;

 posXl=posX;
 posYl=posY;
 posHL=0;

 if (state==0)
 {
  if (init_d [getPos (posXl, posYl)]=='1')
   posHL=1;
 }
 else if (state==1)
 {
  if (init_d [getPos (posXl, posYl)]=='1')
   posHL=1;
  else if (init_d [getPos (posXl, posYl)]=='0' && check_move (sel_x0, sel_y0, posXl, posYl)==true)
   posHL=2;
 }
}


float fpsTweak ()
{
 if (!clockTweak)
  return 1.0f;
 else
  return clockD/15.0f;// 1 frame ms tweak
}

void fpsC ()
{
 // FPS
 paintC++;
 if (clock ()-timeS>=1000)
 {
  fps=paintC;
  paintC=0;
  timeS=clock ();
  if (fpsOn<10)
   fpsOn++;
 }

 clockTweak=false;
 if (clockL!=0)
  clockTweak=true;

 clockD=(float)clock ()-(float)clockL;
 clockL=clock ();
}

void statusBar ()
{
 if (fps>-1)
 {
  glLoadIdentity ();// Сброс просмотра

  literaY=0.75f;
  literaX=-0.75f;
  literaScale=0.17f;
  glColor3f (1.0f, 0.5f, 0.0f);

  if (strlen (mb)!=0)
  {
   sprintf (literaText, "%s", mb);
   glPrintLitera ();// Печать текста GL на экран

   return;
  }

  sprintf (literaText, "FPS:%d X:%d Y:%d", fps, posX, posY);
  glPrintLitera ();// Печать текста GL на экран
 }
}

void loading ()
{
 bool fileIs=true;
 char url [_MAX_PATH];
 int px, py, dx, dy, bx, by, off=55;

 sprintf (url, "%s\\data\\textures\\sky.jpg", AppDir);

 FILE * file;
 file=fopen (url, "r");
 if (file==NULL)
  fileIs=false;
 fclose (file);

 if (fileIs==true)
 {
  WCHAR ts [256];
  MultiByteToWideChar (CP_ACP, 0, url, -1, ts, 256);
  imagesH=new Gdiplus::Image (ts, true);
  px=imagesH->GetWidth ();
  if (px>0)
  {
   py=px;
   if (cx>cy)
   {
    off=(sqrt (pow (cx, 2)+pow (cy, 2))-cx)*120/100;
    dx=px*cx/(cx+off);
    dy=py*dx/px*cy/cx;
    bx=(px-dx)/2;
    by=(py-dy)/2;
   }
   else
   {
    off=(sqrt (pow (cx, 2)+pow (cy, 2))-cy)*120/100;
    dy=py*cy/(cy+off);
    dx=px*dy/py*cx/cy;
    by=(py-dy)/2;
    bx=(px-dx)/2;
   }
   hDC=GetDC (hWnd);
   gDC=new Gdiplus::Graphics (hDC);
   gDC->SetPageUnit(Gdiplus::UnitPixel);
   gDC->SetCompositingMode(Gdiplus::CompositingModeSourceCopy);
   gDC->SetCompositingQuality(Gdiplus::CompositingQualityAssumeLinear);
   gDC->SetPixelOffsetMode(Gdiplus::PixelOffsetModeHighQuality);
   gDC->SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
   gDC->SetInterpolationMode(Gdiplus::InterpolationModeHighQualityBicubic);

   Gdiplus::RectF bounds(0, 0, cx, cy);
   Gdiplus::ImageAttributes attr;
   attr.SetWrapMode(Gdiplus::WrapModeTile);

   gDC->DrawImage (imagesH, bounds, bx, by, dx, dy, Gdiplus::UnitPixel, &attr);

   DeleteObject (&attr);
   DeleteObject (&bounds);

   ReleaseDC (hWnd, hDC);
  }
 }
}

void saveConf()
{
 FILE *file;
 int i;
 char conf [1024], conf1 [1024], conf2 [1024];

 if (move1 && state<10)
  stats_notfin++;

 if (conf_side!=-1)
  side=conf_side;

 sprintf (conf1, "Sound:%d\r\nMelody:%d\r\nLanguage:%d\r\nSide:%d\r\n",
                  sndVol, melVol, lang, side);
 sprintf (conf2, "Wins:%d\r\nLoses:%d\r\nDraws:%d\r\nRestarted:%d\r\nNotFinished:%d\r\nMoves:%d\r\n",
                  stats_wins, stats_loses, stats_draws, stats_restart, stats_notfin, stats_moves);
 sprintf (conf, "%s\r\n%s", conf1, conf2);
 char path [_MAX_PATH];
 sprintf (path, "%s%s", AppDir, "data\\save.txt");

 file=fopen (path, "wb");
 if (file!=NULL)
 {
  fwrite (conf, 1, strlen (conf), file);
  fclose (file);
 }
}

void loadConf ()
{
 FILE *file;
 int i, i2, n=0, n2, fS, confMx=1024, parMx=32, parL;
 char conf [1024], par [32], par0 [32], par1 [32];
 memset (conf, 0, confMx);

 char path [_MAX_PATH];
 sprintf (path, "%s%s", AppDir, "data\\save.txt");

 file=fopen (path, "rb");
 if (file!=NULL)
 {
  fseek (file, 0, SEEK_END);// seek to end of file
  fS=ftell (file);// get current file pointer
  fseek (file, 0, SEEK_SET);// seek to begin of file
  if (fS<confMx-2)
   fread (conf, 1, fS, file);
  else
   fread (conf, 1, confMx-2, file);
  fclose (file);
 }
 strcat (conf, "\n");

 for (i2=0; i2<strlen (conf); i2++)
 {
  if (conf [i2]!='\n' && conf [i2]!='\r')
   break;
 }
 n=i2;

 for (i=n; i<strlen (conf); i++)
 {
  if (conf [i]=='\n' || conf [i]=='\r')
  {
   memset (par, 0, parMx);
   for (i2=n; i2<i; i2++)
    par [i2-n]=conf [i2];

   for (i2=i+1; i2<strlen (conf); i2++)
   {
    if (conf [i2]!='\n' && conf [i2]!='\r')
     break;
   }
   n=i2;
   i=i2;

   parL=strlen (par);
   if (parL>parMx)
    parL=parMx;

   memset (par0, 0, parMx);
   memset (par1, 0, parMx);
   n2=0;
   for (i2=0; i2<parL; i2++)
   {
    if (par [i2]==':')
    {
     n2=i2;
     break;
    }
   }
   if (n2)
   {
    memcpy (par0, par, i2);
    for (i2=n2+1; i2<parL; i2++)
     par1 [i2-n2-1]=par [i2];
   }
   if (!strcmp (par0, "Sound"))
   {
    sndVol=atoi (par1);
    soundVol=sndVol*250;
    if (soundVol>1000)
     soundVol=1000;
    if (soundVol<0)
     soundVol=0;
    if (soundVol)
     soundOn=true;
    else
     soundOn=false;
   }
   else if (!strcmp (par0, "Melody"))
   {
    melVol=atoi (par1);
    meloVol=melVol*250;
    if (meloVol>1000)
     meloVol=1000;
    if (meloVol<0)
     meloVol=0;
    if (meloVol)
     meloIs=true;
    else
     meloIs=false;
   }
   else if (!strcmp (par0, "Language"))
   {
    lang=atoi (par1);
    if (lang!=0 && lang!=1)
     lang=0;
   }
   else if (!strcmp (par0, "Side"))
   {
    side=atoi (par1);
    if (side!=0 && side!=1)
     side=0;
   }
   else if (!strcmp (par0, "Wins"))
   {
    stats_wins=atoi (par1);
    if (stats_wins<0)
     stats_wins=0;
   }
   else if (!strcmp (par0, "Loses"))
   {
    stats_loses=atoi (par1);
    if (stats_loses<0)
     stats_loses=0;
   }
   else if (!strcmp (par0, "Draws"))
   {
    stats_draws=atoi (par1);
    if (stats_draws<0)
     stats_draws=0;
   }
   else if (!strcmp (par0, "Restarted"))
   {
    stats_restart=atoi (par1);
    if (stats_restart<0)
     stats_restart=0;
   }
   else if (!strcmp (par0, "NotFinished"))
   {
    stats_notfin=atoi (par1);
    if (stats_notfin<0)
     stats_notfin=0;
   }
   else if (!strcmp (par0, "Moves"))
   {
    stats_moves=atoi (par1);
    if (stats_moves<0)
     stats_moves=0;
   }
  }
 }
}