-
Notifications
You must be signed in to change notification settings - Fork 11
/
Main.hs
68 lines (61 loc) · 2.48 KB
/
Main.hs
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
-- This software is copyright (c) 1996-2005 by
-- John Tromp
-- Insulindeweg 908
-- 1095 DX Amsterdam
-- Netherlands
-- E-mail: john.tromp at gmail.com
--
-- This notice must not be removed.
-- This software must not be sold for profit.
-- You may redistribute if your distributees have the
-- same rights and restrictions.
module Main where
import Data.Bits
import Data.Char
import Data.Word
import Data.Array.MArray
import Data.Array.IO
import Data.IORef
import Numeric
import CPUTime
import IO
import Connect4(width,height,Game(Game),listGame,isWonGame,isWinnable,goodMoves,size,bsize,moveEval,encode)
import GameTreeSearch(Hash(Hash),GameTree(GTLoss,GTDraw,GTBranch),alphabeta,loss,losswin,win,newTT,TTable,statsTT,intlog,getPosed,ratio,locksize)
ttsize = 8306069 -- should be at least 2^bsize-locksize
makeGameTree game@(Game n _ _ _) h0 h1 =
if n==size-1 then GTDraw else -- assume last move doesn't win
if null children then GTLoss else
if n==size-2 then GTDraw -- two moves left without opponent win is a draw
else GTBranch (Hash lock hash) h0 children where
key = encode game
lock = fromIntegral (key `shiftR` (bsize - locksize))
hash = fromIntegral (key `mod` (fromIntegral ttsize))
children = [(h,makeGameTree g h1 h0) | (h,g) <- goodMoves game]
solve line = do
let moves = map ((\i->i-1).digitToInt) $ filter isDigit line
let game@(Game n _ _ _) = listGame moves
if (isWonGame game) then putStrLn "already lost" else
if isWinnable game then putStrLn "instant win" else do
tt <- newTT ttsize :: IO TTable
hist0 <- thaw moveEval :: IO (IOUArray Int Int)
hist1 <- thaw moveEval :: IO (IOUArray Int Int)
putStrLn$("\nSolving "++).shows n.(("-ply position after "++line)++)$" . . ."
nodes <- newIORef 0 :: IO (IORef Word64)
tstart <- getCPUTime
score <- alphabeta nodes tt losswin (makeGameTree game hist0 hist1)
tend <- getCPUTime
posed <- getPosed tt
n <- readIORef nodes
putStrLn $ ("score = "++).shows score.(" ("++).(("-<=>+"!!(score-loss)):).
(") work = "++) $ show $ intlog posed
let msecs = (tend-tstart) `div` 1000000000
putStrLn $ shows n . (" pos / "++) . shows msecs .
(" msec = "++) . showFFloat (Just 1) (ratio n msecs) $ " Kpos/sec"
stats <- statsTT tt
putStrLn stats
main = do
putStrLn $ ("Fhourstones 3.1 (Haskell)\nBoardsize = "++) .
shows width . ('x':) . shows height . ("\nUsing "++) .
shows ttsize $ " transposition table entries."
input <- getContents
mapM_ solve $ lines input