#Include "window9.bi"

'Константы для меню и горячих клавиш
Enum ChessGui
	M_LEVEL_1=1 '1 уровень
	M_LEVEL_2 '2 уровень
	M_LEVEL_3 '3 уровень
	M_LEVEL_4 '4 уровень
	M_LEVEL_5 '5 уровень
	M_LEVEL_6 '6 уровень
	M_LEVEL_7 '7 уровень
	M_LEVEL_8 '8 уровень
	M_LEVEL_9 '9 уровень
	M_PLAYWHITE 'играть белыми
	M_PLAYBLACK 'играть черными
	M_OPTION 'настройки
	M_EXIT 'выход
	M_SCALE_100 ' масштаб 100%
	M_SCALE_150 ' масштаб 150%
	M_SCALE_200 ' масштаб 200%
	M_ROTATE ' поворот доски
	M_COMPMOVE 'ход компьютера
	M_AUTOPLAY 'автоигра компьютера с компьютером
	M_ABOUT 'о программе
	HOTKEY_BACK ' ход назад
	HOTKEY_FORWARD ' ход вперед
	MY_RATING ' личный рейтинг
	RND_PLAYER ' случайный игрок
End Enum
' константы для гаджетов окна настроек
Enum OPTIONS
	OPT_BLACK=100 'выбор цвета для черной клетки
	OPT_WHITE 'выбор цвета для белой клетки
	OPT_ABC 'выбор цвета для цифр
	OPT_BG ' выбор цвета фона
	OPT_FONT ' выбор шрифта
	OPT_LANG ' выбор языка
	OPT_FIGURE ' выбор фигуры
	OPT_But ' Отмена действий
	OPT_ButS 'сохранение действий
	OPT_P1 'пояснение для OPT_BLACK
	OPT_P2 'пояснение для OPT_WHITE
	OPT_P3 'пояснение для OPT_ABC
	OPT_P4 'пояснение для OPT_BG
	OPT_P5 'пояснение для OPT_FONT
	OPT_P6 'пояснение для OPT_LANG
	OPT_FIGURE_TEXT=300 ' пояснение для кнопки выбора набора фигур
End Enum
' константы для гаджетов окна превращения пешки в ферзя
Enum P_QRBN
	Image_PQ=OPT_P6+1 'ферзь
	Image_PR 'ладья
	Image_PB 'слон
	Image_PN 'конь
End Enum
' константы для тулбаров и контейнеров
Enum tool
	TOOLBAR_UNDO = Image_PN+100 'назад
	TOOLBAR_REDO 'вперед
	TOOLBAR_MOVE ' ход компьютера
	TOOLBAR_AUTOGAME ' автоигра
	TOOLBAR_SETUP 'установка фигур
	TOOLBAR_OPTION ' настройки
	TOOLBAR_LOAD 'загрузить
	TOOLBAR_SAVE 'сохранить
	TOOLBAR_OK 'Принять установленную позицию
	TOOLBAR_CLEAR 'очистить позицию
	TOOLBAR_P ' пешка
	TOOLBAR_N ' конь
	TOOLBAR_B ' слон
	TOOLBAR_R ' ладья
	TOOLBAR_K ' король
	TOOLBAR_Q ' ферзь
	TOOLBAR_P_B ' черная пешка
	TOOLBAR_N_B ' черный конь
	TOOLBAR_B_B ' черный слон
	TOOLBAR_R_B ' черная ладья
	TOOLBAR_K_B ' черный король
	TOOLBAR_Q_B ' черный ферзь
	CONTEINER ' контейнер для функциональных кнопок тулбара
	CONTEINER_F ' контейнер для кнопок - фигур
End Enum

Type A_B_C
	STRMASSS(1 To 65) As String*2 ' массив с координатами
	mass(1 To 65) As Integer={_
	1,0,1,0,1,0,1,0,_
	0,1,0,1,0,1,0,1,_
	1,0,1,0,1,0,1,0,_
	0,1,0,1,0,1,0,1,_
	1,0,1,0,1,0,1,0,_
	0,1,0,1,0,1,0,1,_
	1,0,1,0,1,0,1,0,_
	0,1,0,1,0,1,0,1} 'для определения черных и белых клеток
	a As Integer 'хранилище индекса FIGURE
	b As Integer 'хранилище индекса FIGURE
	c As Integer 'хранилище индекса FIGURE
End Type
Type Opti_
	As Colorref black=&h276b97 'цвет темных клеток
	As Colorref white=&h2fa3df 'цвет светлых клеток
	As Colorref ColorABCD=&hFFFFFF 'цвет шахматных координат
	As Colorref Colorbg=&h5bafcf 'цвет фона окна
	As Integer fontsize=12 ' размер шрифта шахматных координат(ABCDEFGH и 12345678)
	As String fontname="Courirer New" ' имя шрифта
	As HFONT hfont ' хедл шрифта
	As String*2 language="ru" 'язык интерфейса
	As ZString*8 FigureEndsName="_1.png" 'постфикс для имен изображений фигур
End Type
Type GuiChess
	As HWND hwnd 'хендл главного окна
	As HWND hwnd_option 'хендл окна настроек
	As HWND hwnd_option_figure 'хендл окна настроек фигур
	As HWND HWpQ 'хендл окна превращения пешки в ферзя
	As Integer EVENT ' событие
	As HMENU hMessages 'Хендл главного меню
	As HMENU MenName0 'Хендл подменю
	As HMENU MenName1 'Хендл подменю
	As HMENU MenName2 'Хендл подменю
	As HMENU MenName3 'Хендл подменю
	As HMENU MenName4 'Хендл подменю
	As HMENU MenName5	'Хендл подподменю
	As HMENU MenName6	'Хендл подподменю
	As Opti_ Opti ' указатель на структуру выше
	As Opti_ CopyOpti 'копия Opti
	As bool flag=1 ' флаг для определения установки светлых или темных клеток
	As bool flagtimer ' очередность включения , выключения автоигры
	As bool flagtimer2 ' сигнал о завершении потока автоигры
	As Integer whbox=60 ' размер клетки
	As Integer indent=30 ' отступ рисования поля от начала окна
	As Integer w_b_g_f,w_b_g_f_2 'флаги для определения( если 1 играть белыми, иначе черными)
	As Integer level=4 ' уровень игры
	As Integer ScaleMenu=M_SCALE_150 'масштаб окна
	As Integer toolbar,toolbar2 ' хендлы тулбаров
	As Integer iSetupFlag ' флаг определяющий установку позиции фигур
	As Integer iflipBoard ' флаг определяющий поворот доски
	As Integer Selectfigure ' номер выбранной фигуры
	As Integer iMyRating = 700 ' рейтинг игрока
	As Integer iflagMyRating ' флаг установки рейтинга
	As Integer iFlagEndOfGame ' флаг-сигнализатор окончания игры
	As ZString*15 szNameGame = " " ' имя сохраняемой, загружаемой игры
	As Integer Rating(1 To 9) = {700,900,1100,1300,1600,1900,2000,2100,2150} ' рейтинг уровней
	As Integer iGadget(1 To 64) = {_
	57,58,59,60,61,62,63,64,_
	49,50,51,52,53,54,55,56,_
	41,42,43,44,45,46,47,48,_
	33,34,35,36,37,38,39,40,_
	25,26,27,28,29,30,31,32,_
	17,18,19,20,21,22,23,24,_
	9, 10,11,12,13,14,15,16,_
	1, 2, 3, 4, 5, 6, 7, 8} ' расположение гаджетов относительно таблицы движка
	As String*128 Dimlanguage(66)={_
	"Вам поставили мат!",_
	"Поздравляем! Вы выиграли.",_
	"Ну вот, вроде как зря играли, ничья!",_
	"Автор оболочки для движка MINIMAX: Станислав Будинов. Сам движок написан: D.Steinwender, Ch.Donninger",_
	"Настройки",_
	"Цвет темных клеток",_
	"Цвет светлых клеток",_
	"Цвет шахматных координат",_
	"Цвет фона окна",_
	"Размер шрифта",_
	"Язык интерфейса",_
	"Отмена",_
	"Сохранить",_
	"Шахматы",_
	"Файл",_
	"Вид",_
	"Уровень",_
	"Действие",_
	"Информация",_
	"Новая игра",_
	"Играть белыми",_
	"Играть черными",_
	"Настройки",_
	"Выход",_
	"Масштаб",_
	"Пусть компьютер за меня сходит",_
	"Автоигра",_
	"О программе",_
	"При изменении настроек , шахматная позиция будет сброшена! Продолжить?" ,_
	"Остановить автоигру",_
	"Да",_
	"Нет",_
	"Набор фигур",_
	"Ход назад",_
	"Ход вперед",_
	"Пусть компьютер за меня сходит",_
	"Автоигра",_
	"Расставить позицию",_
	"Настройки",_
	"Загрузить позицию",_
	"Сохранить позицию",_
	"Внимание!",_
	"При установке позиции, ваша текущая позиция будет потеряна!",_
	"Если после установки позиции, будете играть за белых, нажмите -ДА-",_
	"Если будете играть за черных, нажмите -НЕТ-",_
	"Если не хотите устанавливать позицию, нажмите -ОТМЕНА-",_
	"На доске должны быть оба короля!",_
	"На доске слишком много королей!",_
	"Повернуть доску",_
	"Патовое состояние",_
	"Три повторных хода",_
	"Недостаток фигур для выигрыша",_
	"Рейтинг:",_
	"Ваш рейтинг составляет:",_
	"Вы играете в силу",_
	"новичка",_
	"4 разряда",_
	"3 разряда",_
	"2 разряда",_
	"1 разряда",_
	"Автоигра завершена",_
	"Партия не закончена.",_
	"Если вы сейчас закроете игру без сохранения, вам будет засчитано поражение",_
	"Прервать партию?",_
	"Случайный соперник",_
	"Невозможно использовать другие опции, пока не выключена автоигра!",_
	"Идет отключение автоигры...."}'массив для строк языкового файла
	As ZString*2 pawnto__ ' буфер хранения новой фигуры из пешки
	As HBITMAP background ' хендл фона
	As HBITMAP tempbitmap 'хендл изымаемого рисунка
	As HBITMAP blacknull ' пустая незанятая черная клетка
	As HBITMAP whitenull ' пустая незанятая белая клетка
	As HBITMAP Selectblackwhitenull ' временный битмап для незанятой клетки
	As HBITMAP optionfiguretemp ' битмап для окна настроек фигур
	As HBITMAP FIGURE(1,2,11) 'хенлы фигур (фон,размер,фигура)
	As HBITMAP CopyFIGURE(1,2,11) 'копия массива FIGURE
	As HBITMAP option_figure(100) 'массив-выбор фигур
	As HBITMAP ImageTBar(21) ' хендлы изображений для тулбара
	As A_B_C  A_B_C ' сохраняет координаты массива выбранного рисунка
	Declare Function CurentSize() As Integer
	Declare Sub drawBackGround()'метод рисования фона
	Declare Sub Begin()'Вход в игру (Создание GUI)
	Declare Sub EVENT_CHESS()'Обработчик событий
	Declare Sub Option()'процедура настроек
	Declare Function CheckPawnValid(sel As Integer, n As Integer,CHECKBIT As HBITMAP) As bool
	Declare Sub SelectPawnToQueen(sel As Integer,n As Integer)' процедура создания окна для выбора превращения пешки в фигуру
	Declare Sub ReplacePawnToQueen(As String, As bool=0)'перезапись пешки в фигуру
	Declare Sub PawnTo(sel As Integer, n As Integer,CHECKBIT As HBITMAP)
	Declare Sub NewGame(wbg As bool)'запуск новой игры
	Declare Sub Click(n As Integer,fl As bool=0)'клик по фигуре
	Declare Sub OptionsClick(gadget As Integer) ' процедура обработки сообщений от гаджетов окна настроек
	Declare Sub LoadImage(fl As Integer=0)' загрузка изображений
	Declare Sub freeImage()'освобождение хендлов изображений
	Declare Function checkmove(n As Integer, selectfigure As Integer,flcheck As Integer=0,replpawn As String="")As String 'проверка хода на возможность
	Declare Sub LoadImageGadgets(NR As bool=0) ' загрузка или изменение размеров гаджетов
	Declare Sub NewGamePosition() 'установка исходной позиции для начала игры
	Declare Sub UpdatePosition() 'изменение рисунков при изменении масштаба
	Declare Sub SCALE(i As Integer,id As Integer)'Изменение масштаба окна игры
	Declare Sub SaveAndLoadOptions(As bool)'сохранение или загрузка настроек
	Declare Sub LoadMenu(fl As Integer=0) ' загрузка меню
	Declare Sub ClearCheckMenu(beg As Integer, en As Integer,cur As Integer) 'установка галки у меню
	Declare Sub MoveFigure(n As Integer, selectfigure As Integer)'Ход фигурой
	Declare Sub LoadLang() 'Загрузка языкового файла
	Declare Sub LoadOptionFigure() 'Загрузка фото для настроек фигур
	Declare Sub SetPositionFromTable() ' Вывод графики для фигур из таблицы
	Declare Function SetPositionInTable(iCurrent_Move As Integer) As Integer ' Вывод натации фигур в таблицу
	Declare Sub BackMove() ' ход назад
	Declare Sub ForwardMove() ' ход вперед
	Declare Function SaveInFile(flag As Integer = 0) As BOOL ' сохранение партии в файл
	Declare Function LoadFromFile(flag As Integer = 0) As BOOL ' загрузка партии из файла
	Declare Sub Setup_Position(g As Integer) ' установка позиции
	Declare Sub Clear_Position() ' очистка поля
	Declare Function Check_king() As Integer ' проверка королей
	Declare Sub SetCoordinates() ' установка координат для поворота доски
	Declare Sub CalcRating(n As Single) ' Подсчет рейтинга
	Declare Sub MessageRating() ' Вывод сообщения о рейтинге
	Declare Sub PlayGame(i As Integer) ' Вывод сообщения о прерывании игры и\или подготовка к началу
End Type

#Include "MINIMAX.bas"

Randomize Timer
Dim Shared As GuiChess Obj
Obj.Begin()'<-вход

Sub GuiChess.MessageRating()
	Dim As String sMess
	Select Case iMyRating
		Case Is <1000
			sMess = Dimlanguage(55)
		Case Is < 1400
			sMess = Dimlanguage(56)
		Case Is <1600
			sMess = Dimlanguage(57)
		Case Is < 1800
			sMess = Dimlanguage(58)
		Case Else
			sMess = Dimlanguage(59)
	End Select
	MessBox("",Dimlanguage(53) & "  " & iMyRating & _
	Chr(13) & Chr(13) & Dimlanguage(54) & " " & sMess)
End Sub

Sub GuiChess.CalcRating(n As Single)
	If iflagMyRating = FALSE Then
		Dim As Single Rcomp = Rating(level), Ea, K
		Select Case iMyRating
			Case Is <1000
				K = 30
			Case Is< 1900
				K = 15
			Case Else
				K = 10
		End Select
		Ea = 1/(1+10*((Rcomp - iMyRating)/400))
		iMyRating = iMyRating+ K*(n-Ea)
		iflagMyRating = TRUE
	EndIf
End Sub

Function GuiChess.Check_king() As Integer
	Dim As Integer b,w
	For i As Integer = 0 To 119
		If board(i) = 6 Then
			b+=1
		ElseIf board(i) = -6 Then
			w+=1
		EndIf
	Next
	If b = 0 Or w = 0 Then
		MessBox(Dimlanguage(41),Dimlanguage(46))
	ElseIf b+w>2 Then
		MessBox(Dimlanguage(41),Dimlanguage(47))
	Else
		Return 1
	EndIf
End Function

Sub GuiChess.Clear_Position()
	For i As Integer = 0 To 119
		If Board(i)<>100 Then
			Board(i) = 0
		EndIf
	Next
	SetPositionFromTable()
End Sub

Sub GuiChess.Setup_Position(g As Integer)
	Static mF(TOOLBAR_P To TOOLBAR_Q_B) As Short = {_
	1,4,3,2,6,5,-1,-4,-3,-2,-6,-5}

	Dim As Integer iC,iC2, iBt

	For i As Integer = TOOLBAR_P To TOOLBAR_Q_B
		If GetButtonToolBarState(toolbar2,i,1) Then
			iBt = i
			Exit For
		EndIf
	Next

	If WHITEORBLACKGAME=1 Then
		If iflipBoard = 0 Then
			For i As Integer = 1 To 64
				iC+=1
				If iGadget(i) = g Then
					Exit For
				EndIf
			Next
		Else
			For i As Integer = 64 To 1 Step -1
				iC+=1
				If iGadget(i) = g Then
					Exit For
				EndIf
			Next
		EndIf
	Else
		If iflipBoard = 0 Then
			For i As Integer = 64 To 1 Step -1
				iC+=1
				If iGadget(i) = g Then
					Exit For
				EndIf
			Next
		Else
			For i As Integer = 1 To 64
				iC+=1
				If iGadget(i) = g Then
					Exit For
				EndIf
			Next
		EndIf
	EndIf

	For i As Integer = 0 To 119
		If Board(i)<>100 Then
			iC2+=1
			If iC2 = iC Then
				If Board(i) = 0 Then
					Board(i) = mF(iBt)
				Else
					Board(i) = 0
				EndIf
				Exit For
			EndIf
		EndIf
	Next

	SetPositionFromTable()
	Mcopy2()
End Sub

Function GuiChess.SaveInFile(flag As Integer = 0) As BOOL
	Dim h As HANDLE
	Dim sPath As String
	If flag = 0 Then
		sPath = SaveFileRequester("",ExePath & "\Saves")
	Else
		If szNameGame=" " Then
			szNameGame = "temp"
		EndIf
		sPath = ExePath & "\Saves\" & szNameGame
	EndIf

	If sPath<>"" Then
		h = Create_File(sPath)
		If h <> -1 Then
			Write_Data(h,CInt(@shArrayAllPosition(0,0)),130*601*2)
			Write_Integer(h,Colour)
			Write_Integer(h,WHITEORBLACKGAME)
			Write_Integer(h,iAll_Moves)
			Close_File(h)
			Return TRUE
		EndIf
	EndIf
End Function

Function GuiChess.LoadFromFile(flag As Integer = 0) As BOOL
	Dim h As HANDLE
	Dim sPath As String
	FlagStalemate = 0
	Dim As Integer wob = WHITEORBLACKGAME
	If flag = 0 Then
		sPath = OpenFileRequester("",ExePath & "\Saves")
	Else
		sPath = ExePath & "\Saves\" & szNameGame
	EndIf

	If sPath<>"" Then
		h = Read_File(sPath)
		If h <> -1 Then
			Set_File_Pointer(h,-12,FILE_END)
			Var iTempC = Read_Integer(h)
			WHITEORBLACKGAME = Read_Integer(h)
			Var iTemp = Read_Integer(h)
			If WHITEORBLACKGAME = 1 Then
				If wob<>WHITEORBLACKGAME Then
					flag_setup_ = 1
					interrupt(1)
				EndIf
				'Colour = 1
			Else
				If wob<>WHITEORBLACKGAME Then
					flag_setup_ = 1
					Var L = level
					level = 1
					Var e=CommandLoop("SD1")
					interrupt(0)
					level = L
					e=CommandLoop("SD" & L)
				EndIf
				'Colour = -1
			EndIf
			Set_File_Pointer(h,0,FILE_BEGIN)
			Read_Data(h,Cast(Any Ptr,@shArrayAllPosition(0,0)),130*601*2)
			iAll_Moves = iTemp
			iCurrent_Moves = iAll_Moves
			If SetPositionInTable(iCurrent_Moves) Then
				SetPositionFromTable
			EndIf
			InputPosition
			Colour = iTempC
			flag_setup_ = 0
			Close_File(h)
			Return TRUE
		EndIf
	EndIf
End Function

Sub GuiChess.BackMove()
	If SetPositionInTable(iCurrent_Moves-1) Then
		SetPositionFromTable
		iFlagBackForwardMove = 1
		InputPosition
		iCurrent_Moves-=1
		Selectfigure = 0
		FlagStalemate = 0
		iflagMyRating = TRUE
		Colour=-Colour
	EndIf
End Sub

Sub GuiChess.ForwardMove()
	If SetPositionInTable(iCurrent_Moves+1) Then
		SetPositionFromTable
		iFlagBackForwardMove = 1
		InputPosition
		iCurrent_Moves+=1
		Selectfigure = 0
		FlagStalemate = 0
		iflagMyRating = TRUE
		Colour=-Colour
	EndIf
End Sub

Function GuiChess.SetPositionInTable(iCurrent_Move As Integer) As Integer
	If iCurrent_Move>iAll_Moves Or iCurrent_Move<0 Then Return FALSE
	Function = TRUE

	For i As Integer = 0 To 119
		Board(i) = shArrayAllPosition(i,iCurrent_Move)
	Next
	Castling(0) = shArrayAllPosition(120,iCurrent_Move)
	Castling(2) = shArrayAllPosition(121,iCurrent_Move)
	wKing = shArrayAllPosition(122,iCurrent_Move)
	bKing = shArrayAllPosition(123,iCurrent_Move)
	MoveControl(A1) = shArrayAllPosition(124,iCurrent_Move)
	MoveControl(A8) = shArrayAllPosition(125,iCurrent_Move)
	MoveControl(H1) = shArrayAllPosition(126,iCurrent_Move)
	MoveControl(H8) = shArrayAllPosition(127,iCurrent_Move)
	MoveControl(E1) = shArrayAllPosition(128,iCurrent_Move)
	MoveControl(E8) = shArrayAllPosition(129,iCurrent_Move)
End Function

Sub GuiChess.SetPositionFromTable()

	#Macro mGadget(param)
		If iflipBoard = 0 Then
			If WHITEORBLACKGAME=1 Then
				param = iGadget(j)
			Else
				param = iGadget(65-j)
			EndIf
		Else
			If WHITEORBLACKGAME=1 Then
				param = iGadget(65-j)
			Else
				param = iGadget(j)
			EndIf
		EndIf

	#EndMacro
	#Macro mSetImageGadget(param)
		If bc = 0 Then
			If j Mod 2 Then
				SetImageGadget(iTempGadget,FIGURE(0,c,param))
			Else
				SetImageGadget(iTempGadget,FIGURE(1,c,param))
			EndIf
		Else
			If j Mod 2 Then
				SetImageGadget(iTempGadget,FIGURE(1,c,param))
			Else
				SetImageGadget(iTempGadget,FIGURE(0,c,param))
			EndIf
		EndIf
	#EndMacro

	Dim As Integer  j= 1,ic = 1, bc=0,iTempGadget,c=CurentSize()

	For i As Integer = 0 To BoardDim
		mGadget(iTempGadget)
		Select Case Board(i)
			Case 0
				If bc = 0 Then
					If j Mod 2 Then
						SetImageGadget(iTempGadget,whitenull)
					Else
						SetImageGadget(iTempGadget,blacknull)
					EndIf
				Else
					If j Mod 2 Then
						SetImageGadget(iTempGadget,blacknull)
					Else
						SetImageGadget(iTempGadget,whitenull)
					EndIf
				EndIf
			Case -1
				mSetImageGadget(6)
			Case 1
				mSetImageGadget(0)
			Case -2
				mSetImageGadget(9)
			Case 2
				mSetImageGadget(3)
			Case -3
				mSetImageGadget(8)
			Case 3
				mSetImageGadget(2)
			Case -4
				mSetImageGadget(7)
			Case 4
				mSetImageGadget(1)
			Case -5
				mSetImageGadget(11)
			Case 5
				mSetImageGadget(5)
			Case -6
				mSetImageGadget(10)
			Case 6
				mSetImageGadget(4)
		End Select

		If Board(i)<>100 Then
			j+=1
			ic+=1
		EndIf
		If ic>8 Then
			bc= bc Xor 1
			ic=1
		EndIf
	Next

End Sub

Sub GuiChess.LoadLang()
	Dim As handle h=Read_File(ExePath & "\Lang\" & Opti.language)
	If h<>-1 Then
		Dim i As Integer
		While E_O_F(h)=0
			Dimlanguage(i)=Read_String(h)
			i+=1
		Wend
	EndIf
	Close_File(h)
End Sub
Sub GuiChess.LoadOptionFigure()
	hwnd_option_figure=OpenWindow("",0,0,384,40,WS_POPUP Or WS_VISIBLE)
	CenterWindow(hwnd_option_figure)
	ChDir(ExePath &"\Data\Cdata\")
	Dim d As String=Dir("*.png",32)
	Dim n As Integer=1
	Do

		Dim As ZString*6 Nv = Right(d,6)
		If Left(Nv,1)="_" Then
			Nv=Mid(Nv,2,1)
		Else
			Nv=Mid(Nv,1,2)
		EndIf
		Option_figure(Val(Nv))=Load_image(ExePath &"\Data\Cdata\" & d,&hf0f0f0)
		ImageGadget(Image_PN+Val(Nv),0,32*(n-1)+1,384,32,Option_figure(Val(Nv)))
		d= Dir()
		n+=1
	Loop Until d=""
	ResizeWindow(hwnd_option_figure,,,,(n-1)*33)

	Do
		EVENT=WaitEvent
		If event=eventgadget Then
			Select Case EventNumber
				Case Image_PN+1 To Image_PN+n-1
					Close_Window(hwnd_option_figure)
					Exit Do
			End Select
		EndIf
	Loop
	Opti.FigureEndsName="_" & EventNumber-Image_PN & ".png"
	For i As Integer = Image_PN+1 To Image_PN+n-1
		Free_Image(Option_figure(i))
	Next
End Sub
Sub GuiChess.SaveAndLoadOptions(ls As bool)
	If ls=1 Then
		Var h=Create_File(ExePath & "\ChessMinimax.txt")
		If h<>-1 Then
			Write_StringN(h,Str(Opti.black))
			Write_StringN(h,Str(Opti.white))
			Write_StringN(h,Str(Opti.ColorABCD))
			Write_StringN(h,Str(Opti.Colorbg))
			Write_StringN(h,Str(whbox))
			Write_StringN(h,Str(Opti.fontsize))
			Write_StringN(h,Str(Opti.fontname))
			Write_StringN(h,Str(level))
			Write_StringN(h,Str(ScaleMenu))
			Write_StringN(h,Opti.language)
			Write_StringN(h,Opti.FigureEndsName)
			Write_StringN(h,Str(iMyRating))
			Write_StringN(h,szNameGame)
			Close_File(h)
		EndIf
	Else
		Var h=Read_File(ExePath & "\ChessMinimax.txt")
		If h<>-1 Then
			Opti.black=Val(Read_String(h))
			CopyOpti.black=Opti.black
			Opti.white=Val(Read_String(h))
			CopyOpti.white=Opti.white
			Opti.ColorABCD=Val(Read_String(h))
			CopyOpti.ColorABCD=Opti.ColorABCD
			Opti.Colorbg=Val(Read_String(h))
			CopyOpti.Colorbg=Opti.Colorbg
			whbox=Val(Read_String(h))
			Opti.fontsize=Val(Read_String(h))
			CopyOpti.fontsize=Opti.fontsize
			Opti.fontname=Read_String(h)
			CopyOpti.fontname=Opti.fontname
			level=Val(Read_String(h))
			ScaleMenu=Val(Read_String(h))
			Opti.language=Read_String(h)
			CopyOpti.language=Opti.language
			Opti.FigureEndsName=Read_String(h)
			CopyOpti.FigureEndsName=Opti.FigureEndsName
			iMyRating = Val(Read_String(h))
			szNameGame = Read_String(h)
			If szNameGame = "" Then szNameGame = " "
			LoadLang()
			Close_File(h)
		EndIf
	EndIf
End Sub

Sub GuiChess.SetCoordinates()
	Dim As String TS="ABCDEFGH"
	Dim As Integer I=1

	If WHITEORBLACKGAME = 1 Then
		If iflipBoard = 0 Then
			For a As Integer=8 To 1 Step -1
				For b As Integer=0 To 7
					A_B_C.STRMASSS(I)=Chr(TS[b]) & a
					I+=1
				Next
			Next
		Else
			For a As Integer=1 To 8
				For b As Integer=0 To 7
					A_B_C.STRMASSS(I)=Chr(TS[7-b]) & a
					I+=1
				Next
			Next
		EndIf
	Else
		If iflipBoard = 1 Then
			For a As Integer=8 To 1 Step -1
				For b As Integer=0 To 7
					A_B_C.STRMASSS(I)=Chr(TS[b]) & a
					I+=1
				Next
			Next
		Else
			For a As Integer=1 To 8
				For b As Integer=0 To 7
					A_B_C.STRMASSS(I)=Chr(TS[7-b]) & a
					I+=1
				Next
			Next
		EndIf
	EndIf
End Sub

Sub GuiChess.newgame(wbg As bool)
	FLAGDEADPLAYER = 0
	If flagtimer=1 Then
		StopAutoPlay()
	EndIf
	If wbg = 2 Then
		wbg  = Int(Rnd*2)
		level = Int(Rnd*7)+1
		ClearCheckMenu(M_LEVEL_1,M_LEVEL_9,level)
	EndIf
	WHITEORBLACKGAME=wbg
	Var e=CommandLoop("NG")
	e=CommandLoop("SD" & level)
	SetCoordinates()
	Click(0,1)
	drawBackGround()
	If flag_setup_ = 0 And iSetupFlag = 0 Then
		NewGamePosition()
	EndIf
	For a As Integer = 17 To 48 Step 2
		Select Case a
			Case 17 To 24,33 To 40
				SetImageGadget(a,blacknull)
				SetImageGadget(a+1,whitenull)
			Case Else
				SetImageGadget(a,whitenull)
				SetImageGadget(a+1,blacknull)
		End Select
	Next
	If wbg=0 Then
		Click(0,2)
	EndIf
End Sub

Sub GuiChess.UpdatePosition()
	SetPositionFromTable()
End Sub

Sub GuiChess.MoveFigure(n As Integer, selectfigure As Integer)
	If flag_setup_ = 0 And iSetupFlag = 0 Then
		SetPositionFromTable()
		If FLAFSOUNDCRUNCH = 1 Then
			sndPlaySound("Data\Sdata\Crunch.wav",SND_SYNC)
			If (AttackingField(wKing, Black) = True Or _
				AttackingField(bKing, White) = True) Then
				sndPlaySound("Data\Sdata\Check.wav",SND_SYNC)
			EndIf
		ElseIf (AttackingField(wKing, Black) = True Or _
			AttackingField(bKing, White) = True) Then
			sndPlaySound("Data\Sdata\Stroke.wav",SND_SYNC)
			sndPlaySound("Data\Sdata\Check.wav",SND_SYNC)
		Else
			sndPlaySound("Data\Sdata\Stroke.wav",SND_SYNC)
		EndIf

		If FLAGDEADPLAYER = 1 Then
			Dim As String sMess
			If FLAGAUTOPLAY = 0 And FLAGAUTOPLAYTEMP = 0 Then
				sndPlaySound("Data\Sdata\Defeat.wav",SND_ASYNC)
				CalcRating(0)
				iFlagEndOfGame = TRUE
				sMess = Dimlanguage(0)
			Else
				FLAGAUTOPLAYTEMP = 0
				sMess = Dimlanguage(60)
			EndIf
			DisableWindow(hwnd,1)
			MessBox("",sMess)
			DisableWindow(hwnd,0)
			SetFocus(hwnd)
			FLAGDEADPLAYER = 0
		EndIf
		FLAGDEADPLAYER = 0
	EndIf
End Sub

Function GuiChess.checkmove(n As Integer, selectfigure As Integer,flcheck As Integer=0,replpawn As String="")As String
	Dim As String move= A_B_C.STRMASSS(selectfigure) & A_B_C.STRMASSS(n) & replpawn,RetMove
	If flcheck=1 Then
		If FlagStalemate = 1 Or FlagStalemate = 2 Then
			RetMove = "Stalemate!"
			SetImageGadget(Selectfigure,FIGURE(A_B_C.a,A_B_C.b,A_B_C.c))
			Selectfigure=0
		Else
			RetMove=CommandLoop(move,1)
			If RetMove<>"YES" Then
				Return "No"
			Else
				Return "YES"
			EndIf
		EndIf
	Else
		SetStateMenu(hMessages,CInt(MenName5),1)
		If FlagStalemate = 1 Or FlagStalemate = 2 Then
			RetMove = "Stalemate!"
		Else
			RetMove=CommandLoop(move)
		EndIf
		SetStateMenu(hMessages,CInt(MenName5),0)
	EndIf

	If Left(RetMove,10) = "Checkmate!" Then
		Return "end"
	ElseIf Left(RetMove,22) = "MiniMAX is checkmated!" Then
		'If WHITEORBLACKGAME = 1 Then
		'	Colour = 1
		'Else
		'	Colour = -1
		'EndIf
		Dim As String sMess
		If FLAGAUTOPLAY = 0 Then
			sndPlaySound("Data\Sdata\Victory.wav",SND_ASYNC)
			sMess = Dimlanguage(1)
			CalcRating(1)
			iFlagEndOfGame = TRUE
		Else
			sMess = Dimlanguage(60)
		EndIf

		DisableWindow(hwnd,1)
		MessBox("",sMess)
		DisableWindow(hwnd,0)
		SetFocus(hwnd)
		Return "end"
	ElseIf Left(RetMove,10) = "Stalemate!" Then
		StopAutoPlay(0)
		CalcRating(0.5)
		iFlagEndOfGame = TRUE
		'If WHITEORBLACKGAME = 1 Then
		'	Colour = 1
		'Else
		'	Colour = -1
		'EndIf
		DisableWindow(hwnd,1)
		If FlagStalemate = 0 Then
			MessBox(Dimlanguage(49),Dimlanguage(2))
		ElseIf FlagStalemate = 1 Then
			MessBox(Dimlanguage(50),Dimlanguage(2))
		ElseIf FlagStalemate = 2 Then
			MessBox(Dimlanguage(51),Dimlanguage(2))
		EndIf
		DisableWindow(hwnd,0)
		SetFocus(hwnd)
		Return "end"
	ElseIf RetMove = "Illegal" Or RetMove = "" Or RetMove = " " Or RetMove = "  "	Then
		Return "No"
	Else
		Return RetMove
	EndIf
End Function

Sub GuiChess.Click(n As Integer,fl As bool=0)
	Dim As HBITMAP CHECKBIT
	Static As HBITMAP CHECKBIT_S
	If fl=1 Then
		If tempbitmap<>0 Then Free_Image(tempbitmap)
		A_B_C.a=-1
		A_B_C.b=-1
		A_B_C.c=-1
		Selectfigure=0
		Exit Sub
	EndIf
	If Selectfigure=0 And fl<>2 Then
		CHECKBIT=Cast(HBITMAP,SendMessage(GadgetID(n),STM_GETIMAGE,IMAGE_BITMAP,0))
		CHECKBIT_S=CHECKBIT
		If CHECKBIT<>0 Then
			For a As Integer=0 To 1
				For b As Integer=0 To CurentSize()
					For c As Integer=0 To 11
						If CHECKBIT=FIGURE(a,b,c) Then
							Dim As Integer w=IMAGE_WIDTH(CHECKBIT)
							If tempbitmap<>0 Then Free_Image(tempbitmap)
							tempbitmap=COPY_image(FIGURE(a,b,c))
							ImageStartDraw(tempbitmap)
								BoxDraw(0,0,w,w,255,-1,1,PS_DOT)
							StopDraw
							SetImageGadget(n,tempbitmap)
							Selectfigure=n
							A_B_C.a=a
							A_B_C.b=b
							A_B_C.c=c
							If a=1 Then
								Selectblackwhitenull=blacknull
							Else
								Selectblackwhitenull=whitenull
							EndIf
							Exit Sub
						EndIf
					Next
				Next
			Next
		EndIf
	ElseIf Selectfigure<>n Or fl=2 Then
		Dim As String Temp
		If fl<>2 Then
			PawnTo(Selectfigure,n,CHECKBIT_S)
			Temp=checkmove(n,Selectfigure,1,pawnto__)
		Else
			SetImageGadget(Selectfigure,FIGURE(A_B_C.a,A_B_C.b,A_B_C.c))
			Selectfigure=0
			Click(n)
			SetStateMenu(hMessages,CInt(MenName5),1)
			Temp=CommandLoop("PL")
			SetStateMenu(hMessages,CInt(MenName5),0)
		EndIf
		If Temp="No" Then
			SetImageGadget(Selectfigure,FIGURE(A_B_C.a,A_B_C.b,A_B_C.c))
			Selectfigure=0
			Click(n)
		ElseIf Temp="end" Then
			Selectfigure=0
			Click(n)
		ElseIf Temp="MiniMAX is checkmated!" Or Temp="Stalemate!" Then
			StopAutoPlay(0)
			If Temp="Stalemate!" Then
				If FlagStalemate = 0 Then
					MessBox(Dimlanguage(49),Dimlanguage(60))
				ElseIf FlagStalemate = 1 Then
					MessBox(Dimlanguage(50),Dimlanguage(60))
				ElseIf FlagStalemate = 2 Then
					MessBox(Dimlanguage(51),"                " & Dimlanguage(60) & "          ")
				EndIf
			Else
				MessBox("",Dimlanguage(60))
			EndIf
		Else
			If fl<>2 Then
				'PawnTo(Selectfigure,n,CHECKBIT_S)
				MoveFigure(n,Selectfigure)
				Temp=checkmove(n,Selectfigure,,pawnto__)
				click(0,1)
				pawnto__ = ""
				If Temp="end" Then Exit Sub
			EndIf
			For a As Integer=1 To 65
				If A_B_C.STRMASSS(a)=UCase(Mid(Temp,1,2)) Then
					Selectfigure=a
				EndIf
				If A_B_C.STRMASSS(a)=UCase(Mid(Temp,3,2)) Then
					n=a
				EndIf
			Next
			If Len(Temp)=5 Then
				If CheckPawnValid(Selectfigure,n,Cast(HBITMAP,SendMessage(GadgetID(Selectfigure),STM_GETIMAGE,IMAGE_BITMAP,0)))=1 Then
					ReplacePawnToQueen(Temp,1)
				EndIf
			EndIf
			CHECKBIT=Cast(HBITMAP,SendMessage(GadgetID(Selectfigure),STM_GETIMAGE,IMAGE_BITMAP,0))
			If CHECKBIT<>0 Then
				For a As Integer=0 To 1
					For b As Integer=0 To CurentSize()
						For c As Integer=0 To 11
							If CHECKBIT=FIGURE(a,b,c) Then
								A_B_C.a=a
								A_B_C.b=b
								A_B_C.c=c
								If a=1 Then
									Selectblackwhitenull=blacknull
								Else
									Selectblackwhitenull=whitenull
								EndIf
								Exit For,For,For
							EndIf
						Next
					Next
				Next
			EndIf
			MoveFigure(n,Selectfigure)
			click(0,1)
		EndIf
	EndIf
	pawnto__ = ""
End Sub

Sub GuiChess.ClearCheckMenu(beg As Integer, en As Integer,cur As Integer)
	For a As Integer=beg To en
		SetStateMenu(hMessages,a,0)
	Next
	SetStateMenu(hMessages,cur,3)
End Sub

Function GuiChess.CurentSize() As Integer
	Select Case  whbox
		Case 40:Return 0
		Case 60:Return 1
		Case 80:Return 2
	End Select
End Function

Sub GuiChess.NewGamePosition()
	SetPositionFromTable()
End Sub

Sub GuiChess.LoadImageGadgets(NR As bool=0)
	Dim As HCURSOR cur
	If NR=0 Then cur=LoadCursor(0,IDC_HAND)
	Dim As Integer g=1,c=CurentSize()
	For y As Integer=0 To 7
		For x As Integer=0 To 7
			If NR=0 Then
				ImageGadget( _
				g,_
				x*whbox+indent+4+c*2,_
				y*whbox+indent+7+c*2,_
				whbox,_
				whbox _
				)
				SetClassLong(GadgetID(g),GCL_HCURSOR,Cast(Long,cur))
			Else
				ResizeGadget(_
				g,_
				x*whbox+indent+4+c*2,_
				y*whbox+indent+7+c*2,_
				whbox,_
				whbox _
				)
			EndIf
			g+=1
		Next
	Next
	If NR = 0 Then
		ContainerGadget(CONTEINER,whbox*8+indent*2-182,whbox*8+indent*2-15,182,20)
		toolbar = CreateToolBar(,_
		CCS_ADJUSTABLE+CCS_NODIVIDER+TBSTYLE_FLAT+_
		256)
		UseGadgetList(hwnd)
		ContainerGadget(CONTEINER_F,10,whbox*8+indent*2-15,320,20)
		toolbar2 = CreateToolBar(,_
		CCS_ADJUSTABLE+CCS_NODIVIDER+TBSTYLE_FLAT)
		UseGadgetList(hwnd)
		For i As Integer = 0 To 21
			If i<8 Then
				ToolBarImageButton(ToolBar,TOOLBAR_UNDO+i,CInt(ImageTBar(i)))
				ToolBarToolTip(hwnd,TOOLBAR_UNDO+i,Dimlanguage(33+i))
			ElseIf i=8 Or i=9 Then
				ToolBarImageButton(ToolBar2,TOOLBAR_UNDO+i,CInt(ImageTBar(i)))
			Else
				ToolBarImageButton(ToolBar2,TOOLBAR_UNDO+i,CInt(ImageTBar(i)),,,,TBSTYLE_CHECKGROUP)
			EndIf
		Next
		HideGadget(CONTEINER_F,1)
	Else
		ResizeGadget(_
		CONTEINER,_
		whbox*8+indent*2-182,_
		whbox*8+indent*2-15,_
		182,_
		20 _
		)
		ResizeGadget(_
		CONTEINER_F,_
		10,_
		whbox*8+indent*2-15,_
		320,_
		20 _
		)
	EndIf
	SetGadgetColor(CONTEINER,Opti.Colorbg,0,1)
	SetGadgetColor(CONTEINER_F,Opti.Colorbg,0,1)
End Sub

Sub GuiChess.freeimage()
	For a As Integer=0 To 2
		For b As Integer=0 To 11
			Free_Image(FIGURE(0,a,b))
			Free_Image(FIGURE(1,a,b))
		Next
	Next
	Free_Image(background)
End Sub

Sub GuiChess.LoadImage(fl As Integer=0)
	Dim As String s:Dim As Integer i
	Dim As UByte R,G,B
	Restore nameimage
	For a As Integer=0 To 2
		Read s:Read i
		R=GetRValue(Opti.black)
		G=GetGValue(Opti.black)
		B=GetBValue(Opti.black)
		Dim As hbitmap bmp=Load_image(ExePath & s & Opti.FigureEndsName,RGB(R,G,B))
		R=GetRValue(Opti.white)
		G=GetGValue(Opti.white)
		B=GetBValue(Opti.white)
		Dim As hbitmap bmp1=Load_image(ExePath & s  & Opti.FigureEndsName,RGB(R,G,B))
		For b As Integer=0 To 11
			FIGURE(0,a,b)=Grab_Image(bmp,b*i,0,i,i)
			FIGURE(1,a,b)=Grab_Image(bmp1,b*i,0,i,i)
			If fl=0 Then
				CopyFIGURE(0,a,b)=Grab_Image(bmp,b*i,0,i,i)
				CopyFIGURE(1,a,b)=Grab_Image(bmp1,b*i,0,i,i)
			EndIf
		Next
		Free_Image(bmp):Free_Image(bmp1)
	Next
	b = LoByte(LoWord(Opti.Colorbg))
	g = HiByte(LoWord(Opti.Colorbg))
	r = LoByte(HiWord(Opti.Colorbg))
	Dim As Integer icol = bgr(r,g,b)

	For i As Integer = 0 To 9
		If ImageTBar(i)<>0 Then
			Free_Image(ImageTBar(i))
			If i<8 Then
				DeleteButtonToolBar(toolbar,7-i)
			EndIf
		EndIf
		ImageTBar(i) = Load_image(ExePath & "\Data\" & i+1 & ".png",icol)
		If fl Then
			If i<8 Then
				ToolBarImageButton(ToolBar,TOOLBAR_UNDO+i,CInt(ImageTBar(i)))
				ToolBarToolTip(hwnd,TOOLBAR_UNDO+i,Dimlanguage(33+i))
			EndIf
		EndIf
	Next

	Dim As HBITMAP temp_B = Load_image(ExePath & "\Data\small.png",icol)
	For i As Integer = 8 To 21
		If ImageTBar(i+2)<>0 Then
			If i<21 Then Free_Image(ImageTBar(i+2))
			DeleteButtonToolBar(toolbar2,21-i)
		EndIf
		If i<21 Then ImageTBar(i+2) = Grab_Image(temp_B,(i-8)*16,0,16,16)
		If fl Then
			If i = 8 Or i = 9 Then
				ToolBarImageButton(ToolBar2,TOOLBAR_UNDO+i,CInt(ImageTBar(i)))
			Else
				ToolBarImageButton(ToolBar2,TOOLBAR_UNDO+i,CInt(ImageTBar(i))_
				,,,,TBSTYLE_CHECKGROUP)
			EndIf
		EndIf
	Next
	Free_Image(temp_B)
End Sub

Sub GuiChess.drawBackGround()
	Dim As COLORREF tempColor
	Dim S_ As String
	Dim As Integer VLONG
	If background<>0 Then Free_Image(background)
	If blacknull<>0 Then Free_Image(blacknull)
	If whitenull<>0 Then Free_Image(whitenull)
	Dim As Integer w=whbox-(whbox\10)*2
	blacknull=Create_Image(w,w)
	whitenull=Create_Image(w,w)
	ImageStartDraw(blacknull)
		FillRectDraw(5,5,Opti.white)
	StopDraw
	ImageStartDraw(whitenull)
		FillRectDraw(5,5,Opti.black)
	StopDraw
	background=Create_Image( _
	whbox*8+indent*2, _
	whbox*8+indent*2 _
	)
	ImageStartDraw(background)
		FontDraw(Opti.hfont)
		FillRectDraw(5,5,Opti.Colorbg)
		BoxDraw( _
		indent-3, _
		indent, _
		whbox*8+6, _
		whbox*8+6 _
		)
		For h As Integer=0 To 7
			For w As Integer=0 To 7
				If w And flag Then
					If h And flag Then
						tempColor=Opti.white
					Else
						tempColor=Opti.black
					EndIf
				Else
					If h And flag Then
						tempColor=Opti.black
					Else
						tempColor=Opti.white
					EndIf
				EndIf
				BoxDraw( _
				w*whbox+indent,_
				h*whbox+indent+3,_
				whbox,_
				whbox,_
				tempColor,_
				tempColor _
				)
			Next
			If WHITEORBLACKGAME=1 Then
				If iflipBoard = 0 Then
					S_=Chr(&h41+h)
					VLONG=8-h
				Else
					S_=Chr(&h48-h)
					VLONG=h+1
				EndIf
			Else
				If iflipBoard = 0 Then
					S_=Chr(&h48-h)
					VLONG=h+1
				Else
					S_=Chr(&h41+h)
					VLONG=8-h
				EndIf
			EndIf
			TextDraw(_
			6,_
			h*whbox+indent+whbox\2-Opti.fontsize\2, _
			Str(VLONG), _
			Opti.Colorbg, _
			Opti.ColorABCD _
			)
			TextDraw( _
			h*whbox+indent+whbox\2-Opti.fontsize\2, _
			6, _
			S_, _
			Opti.Colorbg, _
			Opti.ColorABCD _
			)
		Next
	StopDraw
	ResizeWindow( _
	hwnd,_
	,_
	,_
	whbox*8+indent*2+8,_
	whbox*8+indent*2+55 _
	)
	SetGadgetColor(CONTEINER,Opti.Colorbg,0,1)
	WindowBackgroundImage(hwnd,background)
End Sub

Sub autoplay(p As Any Ptr)
	FLAGAUTOPLAY = 1
	Do
		Var t = Timer
		Obj.Click(0,2)
		If (Timer-t)< 1 Then Sleep 700
	Loop Until Obj.flagtimer=0
	Obj.flagtimer2=1
	DisableWindow(Obj.hwnd,0)
	setwindowtext(Obj.hwnd,Obj.Dimlanguage(13))
End Sub

Sub StopAutoPlay(fl As Integer=0)
	If fl=1 Then
		SendMessage(Obj.hwnd,WM_COMMAND,makelparam(1,M_AUTOPLAY),Cast(Lparam,Obj.MenName3))
		DisableWindow(Obj.hwnd,1)
		setwindowtext(Obj.hwnd,Obj.Dimlanguage(66))
	EndIf
	Modify_Menu(M_AUTOPLAY,Obj.MenName3,Obj.Dimlanguage(26))
	Obj.flagtimer=0
	FLAGAUTOPLAY = 0
End Sub

Sub interrupt(i As Integer)
	StopAutoPlay()
	If FLAGAUTOPLAY = 1 Then
Do:WindowEvent:Sleep(50):Loop Until obj.flagtimer2 = 1
	EndIf
	obj.flagtimer2 = 0
	FLAGAUTOPLAY = 0
	obj.newgame(i)
End Sub

Sub GuiChess.SCALE(i As Integer,id As Integer)
	whbox=i
	drawBackGround()
	LoadImageGadgets(1)
	UpdatePosition()
	Click(0,1)
	ScaleMenu=id
End Sub

Sub GuiChess.PLAYGAME(i As Integer)
	If iFlagEndOfGame = FALSE And iflagMyRating = FALSE And iAll_Moves>0 Then
		If MessBox("",Dimlanguage(61) & !"\r\n \r\n" & _
			Dimlanguage(62) & !"\r\n \r\n" & _
			Dimlanguage(63) & !"\r\n \r\n" ,MB_YESNO) = IDYES Then
			CalcRating(0)
			iFlagEndOfGame = FALSE
			iflagMyRating = FALSE
			interrupt(i)
		EndIf
	Else
		iFlagEndOfGame = FALSE
		iflagMyRating = FALSE
		interrupt(i)
	EndIf
End Sub

Sub GuiChess.EVENT_CHESS()
	Do
		event=WindowEvent()
		Select Case event
			Case EventClose
				If iFlagEndOfGame = FALSE And iflagMyRating = FALSE Then
					SaveInFile(1)
				Else
					szNameGame = " "
				EndIf
				SaveAndLoadOptions(1)
				freeimage()
				Exit Sub
			Case EventMenu
				If flagtimer=1 And EventNumber<>M_AUTOPLAY Then
					Select Case EventNumber
						Case M_LEVEL_1 To M_COMPMOVE,M_ABOUT To RND_PLAYER
							MessBox(Dimlanguage(41),Dimlanguage(65))
					End Select
				Else
					Select Case EventNumber
						Case M_EXIT
							If iFlagEndOfGame = FALSE And iflagMyRating = FALSE Then
								SaveInFile(1)
							Else
								szNameGame = " "
							EndIf
							SaveAndLoadOptions(1)
							freeimage()
							Exit Sub
						Case M_PLAYWHITE
							PlayGame(1)
						Case M_PLAYBLACK
							PlayGame(0)
						Case RND_PLAYER
							PlayGame(2)
						Case M_LEVEL_1 To M_LEVEL_9
							ClearCheckMenu(M_LEVEL_1,M_LEVEL_9,EventNumber)
							Var e=CommandLoop("SD" & EventNumber)
							level=EventNumber
						Case M_SCALE_100 To M_SCALE_200
							ClearCheckMenu(M_SCALE_100,M_SCALE_200,EventNumber)
							If EventNumber=M_SCALE_100 Then
								SCALE(40,M_SCALE_100)
							ElseIf EventNumber=M_SCALE_150 Then
								SCALE(60,M_SCALE_150)
							Else
								SCALE(80,M_SCALE_200)
							EndIf
						Case M_ROTATE
							iflipBoard Xor= 1
							drawBackGround()
							SetCoordinates()
							SetPositionFromTable()
						Case M_COMPMOVE
							Click(0,2)
						Case M_OPTION
							Option()
						Case M_AUTOPLAY
							If flagtimer=0 Then
								Modify_Menu(M_AUTOPLAY,Obj.MenName3,Obj.Dimlanguage(29))
								ThreadCreate(@autoplay())
								flagtimer=1
							Else
								StopAutoPlay()
							EndIf
						Case M_ABOUT
							MessBox("",Dimlanguage(3))
						Case HOTKEY_BACK
							BackMove()
						Case HOTKEY_FORWARD
							ForwardMove()
						Case MY_RATING
							MessageRating()
					End Select
				endif
			Case EventGadget
				Select Case EventNumber
					Case 1 To 64
						If iSetupFlag = 0 Then
							CLICK(EventNumber)
						Else
							Setup_Position(EventNumber)
						EndIf
					Case OPT_BLACK To OPT_ButS
						OptionsClick(EventNumber)
				End Select
				If flagtimer=1 And EventNumberToolBar<>TOOLBAR_AUTOGAME Then
					Select Case EventNumberToolBar
						Case TOOLBAR_UNDO To TOOLBAR_MOVE,TOOLBAR_SETUP To TOOLBAR_SAVE
							MessBox(Dimlanguage(41),Dimlanguage(65))
					End Select
				Else
					Select Case EventNumberToolBar
						Case TOOLBAR_UNDO
							BackMove()
						Case TOOLBAR_REDO
							ForwardMove()
						Case TOOLBAR_SAVE
							iFlagEndOfGame = TRUE
							SaveInFile()
						Case TOOLBAR_LOAD
							iFlagEndOfGame = TRUE
							LoadFromFile()
						Case TOOLBAR_OPTION
							Option()
						Case TOOLBAR_AUTOGAME
							iflagMyRating = TRUE
							If flagtimer=0 Then
								Modify_Menu(M_AUTOPLAY,Obj.MenName3,Obj.Dimlanguage(29))
								ThreadCreate(@autoplay())
								flagtimer=1
							Else
								StopAutoPlay()
							EndIf
						Case TOOLBAR_MOVE
							iflagMyRating = TRUE
							Click(0,2)
						Case TOOLBAR_SETUP
							iflagMyRating = TRUE
							iSetupFlag = 1
							Var iRet = MessBox(Dimlanguage(41),_
							Dimlanguage(42) & !"\r\n \r\n" & _
							Dimlanguage(43) & !"\r\n \r\n" & _
							Dimlanguage(44) & !"\r\n \r\n" & _
							Dimlanguage(45) & !"\r\n \r\n",_
							MB_YESNOCANCEL)

							If iRet = IDYES 	Then
								interrupt(1)
								Clear_Position()
								HideGadget(CONTEINER,1)
								HideGadget(CONTEINER_F,0)
							ElseIf iRet = IDNO 	Then
								Var L = level
								level = 1
								Var e=CommandLoop("SD1")
								interrupt(0)
								level = L
								e=CommandLoop("SD" & L)
								Clear_Position()
								HideGadget(CONTEINER,1)
								HideGadget(CONTEINER_F,0)
							Else
								iSetupFlag = 0
							EndIf
							SetPositionFromTable()
						Case TOOLBAR_CLEAR
							Clear_Position()
						Case TOOLBAR_OK
							If Check_king() = 1 Then
								HideGadget(CONTEINER,0)
								HideGadget(CONTEINER_F,1)
								InputPosition
								iSetupFlag = 0
								SetPositionFromTable()
							EndIf
					End Select
				EndIf

		End Select
		Sleep(5)
	Loop
End Sub

Function GuiChess.CheckPawnValid(sel As Integer, n As Integer,CHECKBIT As HBITMAP) As bool
	Dim As HBITMAP one,two,three,four
	one=FIGURE(0,CurentSize,0)
	two=FIGURE(1,CurentSize,0)
	three=FIGURE(0,CurentSize,6)
	four=FIGURE(1,CurentSize,6)
	Select Case CHECKBIT
		Case one,two
			w_b_g_f=0
			w_b_g_f_2 = 1
			Return 1
		Case three,four
			w_b_g_f = 1
			w_b_g_f_2 =2
			Return 1
	End Select
End Function

Sub GuiChess.PawnTo(sel As Integer, n As Integer,CHECKBIT As HBITMAP)
	If iflipBoard = 0 Then
		Select Case sel
			Case 9 To 16
				If n<sel Then
					If CheckPawnValid(sel,n,CHECKBIT)=1 Then
						If (w_b_g_f_2 = 1 And WHITEORBLACKGAME = 1) Or (w_b_g_f_2 = 2 And WHITEORBLACKGAME = 0) Then
							SelectPawnToQueen(sel,n)
						EndIf
					EndIf
				EndIf
			Case 49 To 56
				If n>sel Then
					If CheckPawnValid(sel,n,CHECKBIT)=1 Then
						If (w_b_g_f_2 = 2 And WHITEORBLACKGAME = 1) Or (w_b_g_f_2 = 1 And WHITEORBLACKGAME = 0) Then
							SelectPawnToQueen(sel,n)
						EndIf
					EndIf
				EndIf
		End Select
	Else
		Select Case sel
			Case 49 To 56
				If n>sel Then
					If CheckPawnValid(sel,n,CHECKBIT)=1 Then
						If (w_b_g_f_2 = 1 And WHITEORBLACKGAME = 1) Or (w_b_g_f_2 = 2 And WHITEORBLACKGAME = 0) Then
							SelectPawnToQueen(sel,n)
						EndIf
					EndIf
				EndIf
			Case 9 To 16
				If n<sel Then
					If CheckPawnValid(sel,n,CHECKBIT)=1 Then
						If (w_b_g_f_2 = 2 And WHITEORBLACKGAME = 1) Or (w_b_g_f_2 = 1 And WHITEORBLACKGAME = 0) Then
							SelectPawnToQueen(sel,n)
						EndIf
					EndIf
				EndIf
		End Select
	EndIf

	w_b_g_f_2 = 0
End Sub

Sub GuiChess.ReplacePawnToQueen(input_ As String, fl As bool=0)
	Dim As String fs=Mid(input_,5,1)
	Dim As Integer sel
	For i As Integer=1 To 65
		If A_B_C.STRMASSS(i)= UCase(Mid(input_,1,2)) Then
			sel = i
			Exit For
		EndIf
	Next
	If fs<>"" Then
		Dim As Integer opt
		If Mid(input_,2,1)="7" Then
			opt=0
		ElseIf Mid(input_,2,1)="2" Then
			opt=1
		Else
			Exit Sub
		EndIf
		Select Case fs
			Case "Q"
				A_B_C.c=5+opt*6
			Case "R"
				A_B_C.c=3+opt*6
			Case "B"
				A_B_C.c=2+opt*6
			Case "N"
				A_B_C.c=1+opt*6
		End Select
		If fl=1 Then
			SetImageGadget(sel,FIGURE(A_B_C.mass(sel),curentsize(),A_B_C.c))
		EndIf
	EndIf
End Sub

Sub GuiChess.SelectPawnToQueen(sel As Integer,n As Integer)
	DisableWindow(hwnd,1)
	Dim As String s
	Dim As Integer x,y,w,h,wb=w_b_g_f
	x=WindowX(hwnd)
	y=WindowY(hwnd)
	w=WindowWidth(hwnd)
	h=WindowHeight(hwnd)
	HWpQ=OpenWindow("",x+w\2-(whbox*4-(whbox\5)*4+4)\2,y+h\2,whbox*4-(whbox\5)*4+4,whbox-(whbox\5)+4,WS_VISIBLE Or WS_POPUP)
	ImageGadget(_
	Image_PQ,_
	2,_
	2,_
	whbox-(whbox\5),_
	whbox-(whbox\5),_
	FIGURE(wb,CurentSize,5+wb*6)_
	)
	ImageGadget(_
	Image_PR,_
	2+(whbox-(whbox\5)),_
	2,_
	whbox-(whbox\5),_
	whbox-(whbox\5),_
	FIGURE(wb,CurentSize,3+wb*6)_
	)
	ImageGadget(_
	Image_PB,_
	2+(whbox-(whbox\5))*2,_
	2,_
	whbox-(whbox\5),_
	whbox-(whbox\5),_
	FIGURE(wb,CurentSize,2+wb*6)_
	)
	ImageGadget(_
	Image_PN,_
	2+(whbox-(whbox\5))*3,_
	2,_
	whbox-(whbox\5),_
	whbox-(whbox\5),_
	FIGURE(wb,CurentSize,1+wb*6)_
	)
	Do
		event=WaitEvent
		If event=eventgadget Then
			Select Case EventNumber
				Case Image_PQ
					ReplacePawnToQueen(A_B_C.STRMASSS(sel) & A_B_C.STRMASSS(n) & "Q")
					pawnto__ = "Q"
					Exit Do
				Case Image_PR
					ReplacePawnToQueen(A_B_C.STRMASSS(sel) & A_B_C.STRMASSS(n) & "R")
					pawnto__ = "R"
					Exit Do
				Case Image_PB
					ReplacePawnToQueen(A_B_C.STRMASSS(sel) & A_B_C.STRMASSS(n) & "B")
					pawnto__ = "B"
					Exit Do
				Case Image_PN
					ReplacePawnToQueen(A_B_C.STRMASSS(sel) & A_B_C.STRMASSS(n) & "N")
					pawnto__ = "N"
					Exit Do
			End Select
		EndIf
	Loop
	DisableWindow(hwnd,0):Close_Window(HWpQ)
End Sub

Sub GuiChess.Option()
	If MessBox("",Dimlanguage(28),MB_YESNO)=IDNO Then Exit Sub
	hwnd_option=OpenWindow(Dimlanguage(4), 560, 204, 300, 298,WS_VISIBLE)
	CenterWindow(hwnd_option)
	TextGadget(OPT_BLACK, 10, 10, 25, 25, "",WS_DLGFRAME)
	SetGadgetColor(OPT_BLACK,Opti.black,0,1)
	TextGadget(OPT_WHITE, 10, 40, 25, 25, "",WS_DLGFRAME)
	SetGadgetColor(OPT_WHITE,Opti.white,0,1)
	TextGadget(OPT_ABC, 10, 70, 25, 25, "",WS_DLGFRAME)
	SetGadgetColor(OPT_ABC,Opti.ColorABCD,0,1)
	TextGadget(OPT_BG, 10, 100, 25, 25, "",WS_DLGFRAME)
	SetGadgetColor(OPT_BG,Opti.Colorbg,0,1)
	TextGadget(OPT_FONT, 10, 130, 25, 25, Str(Opti.fontsize),SS_CENTERIMAGE Or SS_CENTER Or WS_DLGFRAME)
	TextGadget(OPT_LANG, 10, 160, 25, 25, Opti.language,SS_CENTERIMAGE Or SS_CENTER Or WS_DLGFRAME)
	TextGadget(OPT_P1, 65, 10, 220, 25, Dimlanguage(5),SS_CENTERIMAGE)
	TextGadget(OPT_P2, 65, 40, 220, 25, Dimlanguage(6),SS_CENTERIMAGE)
	TextGadget(OPT_P3, 65, 70, 220, 25, Dimlanguage(7),SS_CENTERIMAGE)
	TextGadget(OPT_P4, 65, 100, 220, 25, Dimlanguage(8),SS_CENTERIMAGE)
	TextGadget(OPT_P5, 65, 130, 220, 25, Dimlanguage(9),SS_CENTERIMAGE)
	TextGadget(OPT_P6, 65, 160, 220, 25, Dimlanguage(10),SS_CENTERIMAGE)
	optionfiguretemp=Load_image(ExePath & "\Data\ff.png",&hf0f0f0)
	ImageGadget(OPT_FIGURE,9,190,25,25,optionfiguretemp)
	TextGadget(OPT_FIGURE_TEXT,65,190,220,25,Dimlanguage(32),SS_CENTERIMAGE)
	ButtonGadget(OPT_But, 10, 228, 105, 25, Dimlanguage(11))
	ButtonGadget(OPT_ButS, 170, 228, 105, 25, Dimlanguage(12))
End Sub

Sub GuiChess.OptionsClick(gadget As Integer)
	Dim As bool ex,ex1
	Select Case gadget
		Case OPT_BLACK
			Opti.black=ColorRequester()
			SetGadgetColor(OPT_BLACK,Opti.black,0,1)
		Case OPT_WHITE
			Opti.white=ColorRequester()
			SetGadgetColor(OPT_WHITE,Opti.white,0,1)
		Case OPT_ABC
			Opti.ColorABCD=ColorRequester()
			SetGadgetColor(OPT_ABC,Opti.ColorABCD,0,1)
		Case OPT_BG
			Opti.Colorbg=ColorRequester()
			SetGadgetColor(OPT_BG,Opti.Colorbg,0,1)
			SetGadgetColor(CONTEINER,Opti.Colorbg,0,1)
			SetGadgetColor(CONTEINER_F,Opti.Colorbg,0,1)
		Case OPT_FONT
			Opti.hfont=Cast(HFONT,FontRequester())
			Opti.fontsize=SelectedFontSize()
			Opti.fontname=SelectedFontName()
			SetGadgetText(OPT_FONT,Str(Opti.fontsize))
		Case OPT_LANG
			Var L=GetFilePart(OpenFileRequester("",ExePath &"\Lang","*"))
			If L<>"" Then Opti.language=L
			SetGadgetText(OPT_LANG,Opti.language)
		Case OPT_FIGURE
			LoadOptionFigure()
		Case OPT_But
			Opti.black=CopyOpti.black
			Opti.white=CopyOpti.white
			Opti.ColorABCD=CopyOpti.ColorABCD
			Opti.Colorbg=CopyOpti.Colorbg
			Opti.fontsize=CopyOpti.fontsize
			Opti.language=CopyOpti.language
			Opti.hfont=CopyOpti.hfont
			Opti.fontname=CopyOpti.fontname
			Opti.FigureEndsName=CopyOpti.FigureEndsName
			For a As Integer=0 To 1
				For b As Integer=0 To 2
					For c As Integer=0 To 11
						Free_Image(FIGURE(a,b,c))
						FIGURE(a,b,c)=CopyFIGURE(a,b,c)
					Next
				Next
			Next
			ex=1
		Case OPT_ButS
			CopyOpti.black=Opti.black
			CopyOpti.white=Opti.white
			CopyOpti.ColorABCD=Opti.ColorABCD
			CopyOpti.Colorbg=Opti.Colorbg
			CopyOpti.fontsize=Opti.fontsize
			CopyOpti.fontname=Opti.fontname
			CopyOpti.language=Opti.language
			DeleteObject(Cast(HGDIOBJ,CopyOpti.hfont))
			CopyOpti.hfont=Opti.hfont
			CopyOpti.FigureEndsName=Opti.FigureEndsName
			For a As Integer=0 To 1
				For b As Integer=0 To 2
					For c As Integer=0 To 11
						Free_Image(CopyFIGURE(a,b,c))
						CopyFIGURE(a,b,c)=FIGURE(a,b,c)
					Next
				Next
			Next
			ex=1
	End Select
	freeimage()
	LoadImage(1)
	LoadLang()
	LoadMenu(1)
	LoadImageGadgets(1)
	UpdatePosition()
	Click(0,1)
	drawBackGround()
	NewGame(1)
	If ex=1 Then
		Free_Image(optionfiguretemp)
		Close_Window(hwnd_option)
	EndIf
End Sub

Sub GuiChess.LoadMenu(fl As Integer=0)
	If fl=1 Then
		Delete_Menu(hMessages)
		SetWindowText(hwnd,Dimlanguage(13))
		SetWindowText(Obj.hwnd_option,Dimlanguage(4))
		Dim b As Integer=5
		For a As Integer=OPT_P1 To OPT_P6
			SetGadgetText(a,Dimlanguage(b)):b+=1
		Next
		SetGadgetText(OPT_But,Dimlanguage(11))
		SetGadgetText(OPT_ButS,Dimlanguage(12))
		SetGadgetText(OPT_FIGURE_TEXT,Dimlanguage(32))
	EndIf
	UseGadgetList(hwnd)
	hMessages=Create_Menu()
	MenName0=MenuTitle(hMessages,Dimlanguage(14))
	MenName1=MenuTitle(hMessages,Dimlanguage(15))
	MenName2=MenuTitle(hMessages,Dimlanguage(16))
	MenName3=MenuTitle(hMessages,Dimlanguage(17))
	MenName4=MenuTitle(hMessages,Dimlanguage(18))
	MenName5=OpenSubMenu(MenName0,Dimlanguage(19))
	MenuItem(M_PLAYWHITE,MenName5,Dimlanguage(20))
	MenuItem(M_PLAYBLACK,MenName5,Dimlanguage(21))
	MenuItem(RND_PLAYER,MenName5,Dimlanguage(64))
	MenuItem(M_OPTION,MenName0,Dimlanguage(22))
	MenuItem(M_EXIT,MenName0,Dimlanguage(23))
	MenName6=OpenSubMenu(MenName1,Dimlanguage(24))
	MenuItem(M_SCALE_100,MenName6,"100%")
	MenuItem(M_SCALE_150,MenName6,"150%")
	MenuItem(M_SCALE_200,MenName6,"200%")
	For a As Integer=M_LEVEL_1 To M_LEVEL_9
		MenuItem(a,MenName2,Str(a) & "    (" &  Dimlanguage(52) & " " & Rating(a) & ")" )
	Next
	MenuItem(M_COMPMOVE,MenName3,Dimlanguage(25))
	MenuItem(M_AUTOPLAY,MenName3,Dimlanguage(26))
	MenuItem(M_ABOUT,MenName4,Dimlanguage(27))
	MenuItem(MY_RATING,MenName4,Left(Dimlanguage(53),11))
	MenuItem(M_ROTATE,MenName1,Dimlanguage(48))
	SetStateMenu(hMessages,level,3)
	SetStateMenu(hMessages,ScaleMenu,3)
End Sub

Sub GuiChess.Begin()
	SaveAndLoadOptions(0)
	Opti.hfont=LoadFont(Opti.fontname,Opti.fontsize)
	CopyOpti.hfont = Opti.hfont
	LoadImage()
	hwnd=OpenWindow( _
	Dimlanguage(13),_
	300,_
	10,_
	whbox*8+indent*2+8,_
	whbox*8+indent*2+55,_
	WS_OVERLAPPED+WS_CAPTION+WS_SYSMENU+_
	WS_MINIMIZEBOX+WS_VISIBLE)
	AddKeyboardShortcut(hwnd,FVIRTKEY,VK_LEFT,HOTKEY_BACK)
	AddKeyboardShortcut(hwnd,FVIRTKEY,VK_RIGHT,HOTKEY_FORWARD)
	Var icon=LoadIcon(GetModuleHandle(0),MAKEINTRESOURCE(100))
	SendMessage(hwnd,WM_SETICON,ICON_BIG,Cast(Lparam,icon))
	SendMessage(hwnd,WM_SETICON,ICON_SMALL,Cast(Lparam,icon))
	CenterWindow(hwnd)
	UseGadgetList(hwnd)
	LoadMenu()
	LoadImageGadgets()
	NewGame(1)
	If szNameGame<>" " Then
		LoadFromFile(1)
	EndIf
	EVENT_CHESS()
End Sub


nameimage:
Data "\Data\100",32,"\Data\150",48,"\Data\200",64
