Page 1 of 3

Distance to King

Posted: Fri Jan 08, 2010 9:08 pm
by aberent
I have read that some computer chess engines will use the distance to king as a variable in the Evaluation Function.

Does anyone know an efficient way of calculating this distance?

Re: Distance to King

Posted: Fri Jan 08, 2010 9:24 pm
by hgm
Look it up in a table indexed by (square - kingSquare).

Re: Distance to King

Posted: Fri Jan 08, 2010 10:12 pm
by aberent
I am not sure that works for me. I have the board indexed like so:

0 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

So by simply subtracting the values 24 woud be right next to 23 which is not true.

Re: Distance to King

Posted: Fri Jan 08, 2010 11:03 pm
by rjgibert
For whatever reason, HG was assuming a 0x88 representation where the square difference index works. For more information, see

http://chessprogramming.wikispaces.com/0x88

Re: Distance to King

Posted: Fri Jan 08, 2010 11:04 pm
by hgm
This is why it is better to use 0x88 numbering:

Code: Select all

00 01 02 03 04 05 06 07
16 17 18 19 20 21 22 23
32 33 34 35 ....
You can convert one into the other by nr0x88 = nrPlain + (nrPlain & 070); or of course use another table lookup for that, nr0x88 = table[nrPlain].

Re: Distance to King

Posted: Fri Jan 08, 2010 11:37 pm
by gladius
Well, it depends on what distance you want as well :). The dumb method is still pretty fast for king walk distance:

distance = abs(file(king) - file(piece)) + abs(rank(king) - rank(piece));

Calculating file/rank is trivial:

file = index & 7;
rank = index >> 3;

Re: Distance to King

Posted: Sat Jan 09, 2010 9:27 am
by hgm
Your King cannot walk diagonally?

Re: Distance to King

Posted: Sat Jan 09, 2010 12:19 pm
by Richard Allbert
True, but you can precalculate the table at engine startup using the long way round (shown below) and reference the table when eval is called.

Richard

Re: Distance to King

Posted: Sat Jan 09, 2010 3:46 pm
by Vinvin
hgm wrote:Your King cannot walk diagonally?
LOL !
I'd say : Max(Abs(FileKingX-FileTargetX) , Abs(FileKingY-FileTargetY)) .

So it's the maximum distance in vertical/horizontal

Re: Distance to King

Posted: Sat Jan 09, 2010 6:02 pm
by bob
hgm wrote:Look it up in a table indexed by (square - kingSquare).
or

distance = Max( abs(Rank(king) - rank(square)), abs(file(king) - file(square)));

That computes the so-called "taxicab distance" You take the largest of the vertical and horizontal distances.