summaryrefslogtreecommitdiff
path: root/plugins/Chess4Net/PosBaseUnit.pas
blob: e45ea46b0c13f9f838c391bc72c923c772181b41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
unit PosBaseUnit;

interface

uses
  ChessBoardHeaderUnit, ChessRulesEngine, ChessBoardUnit, Classes;

type
  PMoveEst = ^TMoveEst;
  TMoveEst = record
    move: TMoveAbs;
    estimate: LongWord;
  end;

  TFieldNode = packed record
    bField: byte;
    bNextNode: byte; // сл. узел
    wNextNode: word;
    bNextValue: byte; // сл. значение данных
    wNextValue: word;
  end;

  TMoveNode = packed record
    wMove: word;
    estimate: LongWord;
    bNextValue: byte; // сл. значение данных
    wNextValue: word;
  end;

  TReestimate = procedure(moveEsts: TList; nRec: integer);

  TPosBase = class
  private
    fPos: file of TFieldNode;
    fMov: file of TMoveNode;
    Reestimate: TReestimate;
  public
    procedure Add(const posMove: TPosMove); // добавление позиции и хода в базу
    function Find(const pos: TChessPosition; moveEsts: TList = nil): boolean;
    constructor Create(fileNameNoExt: string; Reestimate: TReestimate = nil);
    destructor Destroy; override;
  end;

implementation

uses
  SysUtils;

type
  TCoord = record
    i,j: integer;
  end;

const
  POS_FILE_EXT = 'pos';
  MOV_FILE_EXT = 'mov';
  EMPTY_MOVE_NODE: TMoveNode =
    (wMove: 0; estimate: 0; bNextValue: 0; wNextValue: 0);

  FIELD_SEQ: array[1..64] of TCoord = // 13617 kb
    ((i: 1; j: 1), (i: 1; j: 2), (i: 1; j: 3), (i: 1; j: 4),
     (i: 1; j: 5), (i: 1; j: 6), (i: 1; j: 7), (i: 1; j: 8),
     (i: 8; j: 8), (i: 8; j: 7), (i: 8; j: 6), (i: 8; j: 5),
     (i: 8; j: 4), (i: 8; j: 3), (i: 8; j: 2), (i: 8; j: 1),
     (i: 2; j: 1), (i: 2; j: 2), (i: 2; j: 3), (i: 2; j: 4),
     (i: 2; j: 5), (i: 2; j: 6), (i: 2; j: 7), (i: 2; j: 8),
     (i: 7; j: 8), (i: 7; j: 7), (i: 7; j: 6), (i: 7; j: 5),
     (i: 7; j: 4), (i: 7; j: 3), (i: 7; j: 2), (i: 7; j: 1),
     (i: 3; j: 1), (i: 3; j: 2), (i: 3; j: 3), (i: 3; j: 4),
     (i: 3; j: 5), (i: 3; j: 6), (i: 3; j: 7), (i: 3; j: 8),
     (i: 6; j: 8), (i: 6; j: 7), (i: 6; j: 6), (i: 6; j: 5),
     (i: 6; j: 4), (i: 6; j: 3), (i: 6; j: 2), (i: 6; j: 1),
     (i: 4; j: 1), (i: 4; j: 2), (i: 4; j: 3), (i: 4; j: 4),
     (i: 4; j: 5), (i: 4; j: 6), (i: 4; j: 7), (i: 4; j: 8),
     (i: 5; j: 1), (i: 5; j: 2), (i: 5; j: 3), (i: 5; j: 4),
     (i: 5; j: 5), (i: 5; j: 6), (i: 5; j: 7), (i: 5; j: 8));

constructor TPosBase.Create(fileNameNoExt: string; Reestimate: TReestimate = nil);
begin
  AssignFile(fPos, fileNameNoExt + '.' + POS_FILE_EXT);
{$I-}
  Reset(fPos);
{$I+}
  if IOResult <> 0 then
    Rewrite(fPos);

  AssignFile(fMov, fileNameNoExt + '.' + MOV_FILE_EXT);    
{$I-}
  Reset(fMov);
{$I+}
  try
    if IOResult <> 0 then
      Rewrite(fMov);
  except
    Close(fPos);
    raise;
  end;
  self.Reestimate := Reestimate;
end;

destructor TPosBase.Destroy;
begin
  CloseFile(fPos); // TODO: Here occurs an error if client is closed unforced
  CloseFile(fMov);
end;


function EncodeAddInf(const pos: TChessPosition): byte;
begin
  Result := pos.en_passant;
  if WhiteKingSide in pos.castling then
    Result := Result or $80;
  if WhiteQueenSide in pos.castling then
    Result := Result or $40;
  if BlackKingSide in pos.castling then
    Result := Result or $20;
  if BlackQueenSide in pos.castling then
    Result := Result or $10;
end;


function EncodeMove(const move: TMoveAbs): word;
begin
  with move do
    Result := ((((((((i0-1) shl 3) or (j0-1)) shl 3) or (i-1)) shl 3) or (j-1)) shl 3) or Ord(prom_fig);
end;


procedure TPosBase.Add(const posMove: TPosMove);
var
  addInf: byte;
  fn: TFieldNode;

  procedure AddPosNodes(k: integer; r: integer = -1);
  var
    l, nr: integer;
    mn: TMoveNode;
    estList: TList;
  begin
    // Добавление узлов позиции
    if r >= 0 then
      begin
        nr := FileSize(fPos);
        fn.bNextValue := nr and $FF;
        fn.wNextValue := nr shr 8;
        Seek(fPos, r);
        write(fPos, fn);
        Seek(fPos, nr);
      end
    else
      nr := 0;
    for l := k to 66 do // 65 - доп. инф, 66 - цвет.
      begin
        if l = 66 then
          begin
            fn.bField := ord(posMove.pos.color);
            nr := FileSize(fMov);
          end
        else
          begin
            if l <= 64 then
              fn.bField := ord(posMove.pos.board[FIELD_SEQ[l].i, FIELD_SEQ[l].j])
            else // l = 65
              fn.bField := addInf;
            inc(nr);
          end;
        fn.bNextNode := nr and $FF;
        fn.wNextNode := nr shr 8;
        fn.bNextValue := 0;
        fn.wNextValue := 0;
        write(fPos, fn);
      end;
    // формирование записи хода
    mn := EMPTY_MOVE_NODE;
    mn.wMove := EncodeMove(posMove.move);
    if Assigned(Reestimate) then
    begin
      estList := TList.Create;
      try
        estList.Add(Pointer(mn.estimate));
        Reestimate(estList, 0);
        mn.estimate := LongWord(estList[0]);
      finally
        estList.Free;
      end;  
    end;
    Seek(fMov, FileSize(fMov));
    write(fMov, mn);
  end;

var
  k, r, pr, rm, moveSet, moveCount: integer;
  mv: word;
  mn: TMoveNode;
  enc_mv: word;
  estList: TList;
begin
  addInf := EncodeAddInf(posMove.pos);
  if FileSize(fPos) = 0 then
    begin
      AddPosNodes(1);
      exit;
    end;
  r := 0;
  for k := 1 to 66 do // 65 - доп. инф, 66 - цвет.
    begin
      Seek(fPos, r);
      read(fPos, fn);
      while ((k <= 64) and (fn.bField <> ord(posMove.pos.board[FIELD_SEQ[k].i, FIELD_SEQ[k].j]))) or
            ((k = 65) and (fn.bField <> addInf)) or
            ((k = 66) and (fn.bField <> ord(posMove.pos.color))) do
        begin
          pr := r;
          r := (fn.wNextValue shl 8) or fn.bNextValue;
          if r = 0 then
            begin
              AddPosNodes(k, pr);
              exit;
            end;
          Seek(fPos, r);
          read(fPos, fn);
        end; { while }
      // значение в цепочке найдено
      r := (fn.wNextNode shl 8) or fn.bNextNode;
    end;

  moveCount := 0;
  moveSet := -1;
  estList := TList.Create;
  try
    rm := r;
    enc_mv := EncodeMove(posMove.move);
    repeat
      pr := r;
      Seek(fMov, r);
      read(fMov, mn);

      mv := mn.wMove;
      if mv = enc_mv then
        moveSet := moveCount;

      if Assigned(Reestimate) then
        estList.Add(Pointer(mn.estimate));

      inc(moveCount);
      r := (mn.wNextValue shl 8) or mn.bNextValue;
    until r = 0;

    if moveSet < 0 then // хода нет в списке, добавляем
      begin
        // связывание нового узла с текущим узлом
        r := FileSize(fMov);
        mn.bNextValue := r and $FF;
        mn.wNextValue := r shr 8;
        Seek(fMov, pr);
        write(fMov, mn);
        // Добавление нового узла ходов
        mn := EMPTY_MOVE_NODE;
        mn.wMove := enc_mv;
        Seek(fMov, r);
        write(fMov, mn);

        if Assigned(Reestimate) then
          estList.Add(Pointer(mn.estimate));
        moveSet := moveCount;
      end;

      if Assigned(Reestimate) then
        begin
          Reestimate(estList, moveSet);
          for k := 0 to estList.Count - 1 do
            begin
              Seek(fMov, rm);
              read(fMov, mn);
              if mn.estimate <> LongWord(estList[k]) then
                begin
                  mn.estimate := LongWord(estList[k]);
                  Seek(fMov, rm);
                  write(fMov, mn);
                end;
              rm := (mn.wNextValue shl 8) or mn.bNextValue;
            end;
        end;
  finally
    estList.Free;
  end;  
end;


function TPosBase.Find(const pos: TChessPosition; moveEsts: TList = nil): boolean;

  function DecodeMove(enc_move: word): TMoveAbs;
  begin
   with Result do
     begin
       prom_fig := TFigureName(enc_move and $07);
       enc_move := enc_move shr 3;
       j := (enc_move and $07) + 1;
       enc_move := enc_move shr 3;
       i := (enc_move and $07) + 1;
       enc_move := enc_move shr 3;
       j0 := (enc_move and $07) + 1;
       enc_move := enc_move shr 3;
       i0 := (enc_move and $07) + 1;
     end;
  end;

var
  k, r: integer;
  fn: TFieldNode;
  mn: TMoveNode;
  pme: PMoveEst;
label
  here;
begin
  Result := FALSE;
  for k := 0 to moveEsts.Count - 1 do
    dispose(moveEsts[k]);
  moveEsts.Clear;
  if FileSize(fPos) = 0 then
    exit;

  r := 0;
  for k := 1 to 66 do // 65 - доп. инф, 66 - цвет.
    begin
here:
      Seek(fPos, r);
      read(fPos, fn);
      r := (fn.wNextNode shl 8) or fn.bNextNode;
      while ((k <= 64) and (fn.bField <> ord(pos.board[FIELD_SEQ[k].i, FIELD_SEQ[k].j]))) or
            ((k = 65) and (fn.bField <> EncodeAddInf(pos))) or
            ((k = 66) and (fn.bField <> ord(pos.color))) do
        begin
          r := (fn.wNextValue shl 8) or fn.bNextValue;
          if r = 0 then
            exit
          else
            goto here;
        end; { while }
    end; { for }

  Result := TRUE;
  if not Assigned(moveEsts) then
    exit;

  // Заполнение списка ходов
  repeat
    Seek(fMov, r);
    read(fMov, mn);

    new(pme);
    pme^.move := DecodeMove(mn.wMove);
    pme^.estimate := mn.estimate;
    moveEsts.Add(pme);

    r := (mn.wNextValue shl 8) or mn.bNextValue;
  until r = 0;
end;

end.