packages feed

foo (empty) → 1.0

raw patch · 12 files changed

+2537/−0 lines, 12 filesdep +GLUTdep +OpenGLdep +basesetup-changed

Dependencies added: GLUT, OpenGL, base, containers, haskell98

Files

+ Court.hs view
@@ -0,0 +1,429 @@+-- ==================================
+-- Module name: Court
+-- Project: Foo
+-- Copyright (C) 2007  Bartosz Wójcik
+-- Created on: 01.10.2007
+-- Last update: 07.04.2008
+-- Version: %
+
+{-  This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+-}
+-- ==================================
+module Court where
+
+-- This module is simply user interface to Foo Engine.
+
+import Graphics.Rendering.OpenGL
+import Graphics.UI.GLUT
+import Data.Either
+import Data.IORef
+import System.Exit
+import List
+
+import Foo
+import FooField
+import FooMove
+import MyPrimitives
+
+-- import FooState
+
+-- List of predefined colours used in game
+courtBckgdCol  = Color4 0.1 0 0 1          -- black
+courtCol       = Color4 1 1 1 1            -- white
+lastPointCol   = Color4 1 0.5 0 1          -- orange
+activePointCol = Color4 1 0 0 1            -- red
+newMoveCol     = Color4 1 0 0 1            -- red
+fstMoveCol     = Color4 1 1 1 1            -- white
+sndMoveCol     = Color4 0 1 0 1            -- green
+lstMoveCol     = Color4 1 1 0 1            -- yellow
+
+-- Main graphical function.
+-- Initializes screen and controls the current game until it's finished.
+-- ======================================================================
+court :: (Ord b, Num b) => Int -> Int               -- size of field
+         -> (Bool, PlayingAlgorithm)                -- whether algorithm is 1st player and which one
+         -> (Bool, PlayingAlgorithm)                -- whether algorithm is 2nd player and which one
+         -> b                                       -- number of games to be played
+         -> IO ()
+court fL fW (fstPlayerComp,fstAlg) (sndPlayerComp,sndAlg) nbrGames = do
+-- ======================================================================
+  (progname, _) <- getArgsAndInitialize
+  initialDisplayMode $= [DoubleBuffered]
+  w <- createWindow ("Foo Field (C) Bartosz Wojcik 2008")
+  windowSize $= Size 400 550
+
+  -- List of states of game                                                               -- screen size is adjusted to game
+  activeVertex <- newIORef (0,0)                                                          -- vertex, mouse cursor points on
+  activeFstPlayer <- newIORef True                                                        -- True - 1st player on move; False - 2nd one
+  fstPlayerBegins <- newIORef True                                                        -- True - 1st player begins current game; False - opposite
+  lastPositionVertex <- newIORef (fromIntegral fW / 2, fromIntegral fL / 2 + 1)           -- vertex, last pass finished on
+  myScreenSize <- newIORef (Size 300 400)                                                 -- size of the visible screen
+  court <- newIORef (field fL fW)                                                         -- Foo.field - the Graph
+  rmdEdges <- newIORef []                                                                 -- list of removed edges for display purposes only
+  rmdLstMvEdges <- newIORef []                                                            -- list of removed edges of last move for display purposes only
+  gameNumber <- newIORef (nbrGames,1)                                                     -- game lasts until snd gameResult == fst gameResult
+  gameResult <- newIORef (0,0)
+
+  -- main display
+  displayCallback $= display fL fW activeVertex lastPositionVertex court rmdEdges rmdLstMvEdges gameNumber gameResult (playerName fstPlayerComp fstAlg) (playerName sndPlayerComp sndAlg)
+
+  -- screen is renormalized from 0,0 at bottom left to fW,fL+4
+  projection (-0.1) (fromIntegral fW + 0.1) 0 (fromIntegral fL + 4) 0 1
+
+  -- mouse movement control
+  if not fstPlayerComp || not sndPlayerComp
+     then passiveMotionCallback $= Just (mousePosition activeVertex (fromIntegral fW) (fromIntegral fL + 4) myScreenSize)
+     else passiveMotionCallback $= Nothing
+
+  -- action when window gets reshaped
+  reshapeCallback $= Just (reshape myScreenSize)
+
+  -- action on mouse click
+  keyboardMouseCallback $= Just (keyboardMouse activeVertex lastPositionVertex court rmdEdges rmdLstMvEdges activeFstPlayer fL fW w gameNumber gameResult fstPlayerBegins)
+
+  -- computer plays
+  if fstPlayerComp || sndPlayerComp
+     then idleCallback $= Just (idle activeVertex lastPositionVertex court rmdEdges rmdLstMvEdges activeFstPlayer fL fW w fstPlayerComp fstAlg sndPlayerComp sndAlg gameResult)
+     else idleCallback $= Nothing
+
+  mainLoop
+-- ======================================================================
+
+
+-- Computer plays
+-- ========================================================================
+idle activeVertex lastPositionVertex court rmdEdges rmdLstMvEdges activeFstPlayer
+     fL fW win fstPlayerComp fstAlg sndPlayerComp sndAlg gameResult = do
+-- ========================================================================
+   c <- readIORef court
+   lV <- readIORef lastPositionVertex
+   aV <- readIORef activeVertex
+   rmdE <- readIORef rmdEdges
+   rmdLME <- readIORef rmdLstMvEdges
+   aFP <- readIORef activeFstPlayer
+   if lVy lV == 0 || lVy lV == fromIntegral fL + 2 || vertices (vx lV) c == []    -- end of game
+      then postRedisplay Nothing
+      else if aFP && fstPlayerComp || not aFP && sndPlayerComp
+      then do
+         if aFP
+            then  putStrLn $ "Player1. Nbr possible moves: " ++ (show $ sizeMove 0 $ nextMove aFP (vx lV) c fL fW 0)
+            else  putStrLn $ "Player2. Nbr possible moves: " ++ (show $ sizeMove 0 $ nextMove aFP (vx lV) c fL fW 0)
+   -- Here starts computer's move
+         court $= (graphAfterPass c $ computerPlays (vx lV) c aFP)
+         lastPositionVertex $= ((\(x,y) -> (fromIntegral x,fromIntegral y)) $ head $ vOfMove $ computerPlays (vx lV) c aFP)
+         rmdEdges $= (lastMove2RmdEdges rmdLME aFP fstPlayerComp sndPlayerComp []) ++ rmdE
+         rmdLstMvEdges $= lOfP2lOfReEd (vOfMove $ computerPlays (vx lV) c aFP) [] lstMoveCol
+
+  -- Following line of code gives even 35% overhead!
+  -- Ther reason of this feature is not clear to me. The function that costs here is one that has been already called couple lines above.
+  -- I'd expect that its result is kept and can be applied with minimal overhead.
+
+  --       putStrLn $ show $ computerPlays (vx lV) c aFP               
+
+         lV' <- readIORef lastPositionVertex
+         activeFstPlayer $= newActivePlayer aFP (active (vx lV') c)
+
+         -- Actualize result if end of game
+         c' <- readIORef court                                               -- court after move
+
+         if lVy lV' == 0 || lVy lV' == fromIntegral fL + 2 || vertices (vx lV') c' == []    -- end of game
+            then readIORef gameResult >>= \gR -> gameResult $= actualizeResult gR lV' fL c' (not aFP)
+            else court $= c'
+
+         postRedisplay Nothing
+      else court $= c
+     where computerPlays v g aFP = bestMove $ mapSelectedMove (Play (alg aFP) aFP) (alg aFP) $ nextMove aFP v g fL fW 0
+           lOfP2lOfReEd (l1:[])    os col = os
+           lOfP2lOfReEd (l1:l2:ls) os col = lOfP2lOfReEd (l2:ls) ((l1,col):(l2,col):os) col
+           alg True = fstAlg
+           alg False = sndAlg
+-- ========================================================================
+
+-- Simple XOR.
+-- ========================================================================
+newActivePlayer True True   = True
+newActivePlayer False False = True
+newActivePlayer _     _     = False
+-- ========================================================================
+
+-- To case Vertex of field into vertex of graph.
+-- ========================================================================
+vx (x,y) = (round x,round y)
+-- ========================================================================
+
+-- ========================================================================
+lVy (x,y) = y
+-- ========================================================================
+
+-- ========================================================================
+col True  = fstMoveCol
+col False = sndMoveCol
+-- ========================================================================
+
+-- When left button is down and the activeVertex has edge with lastPositionVertex, then this constitutes next pass.
+-- ================================================================================
+keyboardMouse activeVertex lastPositionVertex court rmdEdges rmdLstMvEdges activeFstPlayer
+              fL fW win gameNumber gameResult fstPlayerBegins (MouseButton LeftButton) Down _ _ = do
+-- ================================================================================
+   c <- readIORef court
+   lV <- readIORef lastPositionVertex
+   aV <- readIORef activeVertex
+   rmdE <- readIORef rmdEdges
+   rmdLME <- readIORef rmdLstMvEdges
+   aFP <- readIORef activeFstPlayer
+   (gN,gI) <- readIORef gameNumber
+   if lVy lV == 0 || lVy lV == fromIntegral fL + 2 || vertices (vx lV) c == []    -- end of game
+      then if gN > gI
+         then do
+            putStrLn "End of Game"
+            renewGame activeVertex lastPositionVertex court rmdEdges rmdLstMvEdges activeFstPlayer fL fW gameNumber fstPlayerBegins
+            postRedisplay Nothing
+         else do
+            putStrLn "End of Tournament"
+            exitWith ExitSuccess
+            destroyWindow win
+            -- postRedisplay Nothing
+      else if activeV aV /= [] && chckEdge (vx lV) (vx aV) c                 -- if vertex belongs to field and there is an edge between it and last position one
+      then do
+         court $= rmEdge (vx lV) (vx aV) c                                   -- remove just chosen edge from field
+         rmdEdges $= ((vx lV),col aFP):((vx aV),col aFP):rmdE                -- add chosen edge to list of removed edges
+         lastPositionVertex $= aV                                            -- change of last position vertes
+         activeFstPlayer $= newActivePlayer aFP (active (vx aV) c)           -- check what player is on move afterwards
+
+         -- Actualize result if end of game
+         c' <- readIORef court                                               -- court after move
+         if lVy aV == 0 || lVy aV == fromIntegral fL + 2 || vertices (vx aV) c' == []    -- end of game
+            then readIORef gameResult >>= \gR -> gameResult $= actualizeResult gR aV fL c' (not aFP)
+            else court $= c'
+
+         postRedisplay Nothing
+      else court $= c
+   where activeV aV = filter (== aV) (verticesOfField fL fW)
+
+-- Other action with mouse click or keyboard usage are without effect.
+-- ================================================================================
+keyboardMouse _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ = return ()
+-- ================================================================================
+
+
+-- ========================================================================
+actualizeResult (gA,gB) (_,0) _  _ _                              = (gA + 1,gB)
+actualizeResult (gA,gB) (x,y) fL c aFP | y == fromIntegral fL + 2 = (gA,gB + 1)
+                                       | aFP                      = (gA + 0.5,gB)
+                                       | otherwise                = (gA,gB + 0.5)
+-- ========================================================================
+
+-- Creates list of passes in trerms of vertives mixed with colour of pass.
+-- ========================================================================
+lastMove2RmdEdges :: [(a, b)]
+                     -> Bool                    -- towards goal (_,0)
+                     -> Bool                    -- 1st player is computer
+                     -> Bool                    -- 2nd player is computer
+                     -> [(a, Color4 GLfloat)]   -- dragged output list
+                     -> [(a, Color4 GLfloat)]
+lastMove2RmdEdges []         _    _    _    os  = reverse os
+lastMove2RmdEdges ((v,c):ls) True True True os  = lastMove2RmdEdges ls True True True ((v,sndMoveCol):os)
+lastMove2RmdEdges ((v,c):ls) True _    _    os  = lastMove2RmdEdges ls True False False ((v,fstMoveCol):os)
+lastMove2RmdEdges ((v,c):ls) False True True os = lastMove2RmdEdges ls False True True ((v,fstMoveCol):os)
+lastMove2RmdEdges ((v,c):ls) False _    _    os = lastMove2RmdEdges ls False False False ((v,sndMoveCol):os)
+-- ========================================================================
+
+-- Reaction on mouse movement.
+-- If mouse cursor approaches vertex of field, it gets activated.
+-- If there is edge between active vertex and last vertex, it will be displayed.
+-- =========================================================
+mousePosition activeV fW fL myScreenSize (Position x y) = do
+-- =========================================================
+  s <- readIORef myScreenSize
+  if (dx s) <= 0.2 && (dy s) <= 0.2                            -- mouse cursor close to a vertex
+     then activeV $= (x'' s,fL - y'' s)
+     else activeV $= (0,0)
+  postRedisplay Nothing
+  where x' (Size w h) = fW * fromIntegral x / fromIntegral w
+        y' (Size w h) = fL * fromIntegral y / fromIntegral h
+        x'' s = fromIntegral $ round (x' s)
+        y'' s = fromIntegral $ round (y' s)
+        dx s = abs $ x'' s - x' s
+        dy s = abs $ y'' s - y' s
+-- =========================================================
+
+-- Current game finished, new one starts.
+-- =========================================================
+renewGame activeVertex lastPositionVertex court rmdEdges rmdLstMvEdges activeFstPlayer fL fW gameNumber fstPlayerBegins = do
+-- =========================================================
+  activeVertex $= (0,0)                                                                  -- vertex, mouse cursor points on
+  fPB <- readIORef fstPlayerBegins
+  activeFstPlayer $= not fPB                                                                -- True - 1st player on move; False - 2nd one
+  fstPlayerBegins $= not fPB
+  lastPositionVertex $= (fromIntegral fW / 2, fromIntegral fL / 2 + 1)                   -- vertex, last pass finished on
+  court $= field fL fW                                                                 -- Foo.field - the Graph
+  rmdEdges $= []                                                                         -- list of removed edges for display purposes only
+  rmdLstMvEdges $= []
+  (gN,gI) <- readIORef gameNumber
+  gameNumber $= (gN,gI + 1)
+-- =========================================================
+
+-- Size of screen has to be traced in order to show active vertex correctly.
+-- =========================================================
+reshape myScreenSize s@(Size w h) = do
+-- =========================================================
+  myScreenSize $= s
+  viewport $= (Position 0 0, s)
+-- =========================================================
+
+-- List of vertices that have to be displayed.
+-- =========================================================
+verticesOfField :: Int -> Int -> [(GLfloat,GLfloat)]
+verticesOfField fL fW = [(fromIntegral x,fromIntegral y) | x<-[0..fW], y<-[0..fL+2], y > 0 && y < fL+2 || x > 2 && x < 5 ]
+-- =========================================================
+
+-- Usual orthogonal projection
+-- =========================================================
+projection xl xu yl yu zl zu = do
+  matrixMode $= Projection
+  loadIdentity
+  ortho xl xu yl yu zl zu
+  matrixMode $= Modelview 0
+-- =========================================================
+
+-- =========================================================
+playerName False _ = "Human"
+playerName True  algorithm = show algorithm
+-- =========================================================
+
+-- Displays nothing - sometimes required for if statement
+-- =========================================================
+dispNothing = renderPrimitive Points $ vertex $ Vertex2 0 (0::GLfloat)
+-- =========================================================
+
+-- Main display function
+-- =========================================================
+display fL fW activeVertex lastPositionVertex court rmdEdges rmdLstMvEdges gameNumber gameResult fstName sndName = do
+-- =========================================================
+  clearColor $= courtBckgdCol
+  clear [ColorBuffer]
+
+  -- first display vertices inside field
+  loadIdentity
+  renderPrimitive Points $ do
+    currentColor $= courtCol
+    mapM_ (\(x,y) -> vertex$Vertex2 x y) (verticesOfField fL fW)
+
+  -- then display the court
+  loadIdentity
+  renderPrimitive LineLoop $ do
+    currentColor $= courtCol
+    vertex $ Vertex2 0 (1::GLfloat)
+    vertex $ Vertex2 (leftGoalLine::GLfloat) 1
+    vertex $ Vertex2 leftGoalLine 0
+    vertex $ Vertex2 rightGoalLine 0
+    vertex $ Vertex2 rightGoalLine 1
+    vertex $ Vertex2 fW' 1
+    vertex $ Vertex2 fW' (fL' + 1)
+    vertex $ Vertex2 rightGoalLine (fL' + 1)
+    vertex $ Vertex2 rightGoalLine (fL' + 2)
+    vertex $ Vertex2 leftGoalLine (fL' + 2)
+    vertex $ Vertex2 leftGoalLine (fL' + 1)
+    vertex $ Vertex2 0 (fL' + 1)
+
+  readIORef gameNumber >>= \x -> displayGameNumber x (fromIntegral fL)
+  readIORef gameResult >>= \x -> displayGameResult x (fromIntegral fL)
+  displayName fstName (fromIntegral fL + 1.5) fstMoveCol
+  displayName sndName 0.5 sndMoveCol
+
+  -- then display done movements
+  readIORef rmdEdges >>= \ls -> displayDoneMoves ls
+  readIORef rmdLstMvEdges >>= \ls -> displayDoneMoves ls
+
+  -- then display pass that finishes at mouse cursor - if there is such a pass
+  c <- readIORef court
+  lV <- readIORef lastPositionVertex
+  aV <- readIORef activeVertex
+  loadIdentity
+  currentColor $= newMoveCol
+  if activeV aV /= [] && chckEdge (vx lV) (vx aV) c
+     then displayPoints [lV,aV] Lines
+     else dispNothing
+
+  -- then emphasise vertex of end of last pass
+  loadIdentity
+  currentColor $= lastPointCol
+  filledCircleAtV lV (0.1::GLfloat)
+
+  -- then mark active vertex
+  loadIdentity
+  currentColor $= activePointCol
+  if activeV aV == []
+    then dispNothing
+    else filledCircleAtV (head $ activeV aV) (0.1::GLfloat)
+
+  swapBuffers
+  where leftGoalLine = fW' / 2 - 1
+        rightGoalLine = fW' / 2 + 1
+        fW' = fromIntegral fW
+        fL' = fromIntegral fL
+        activeV aV = filter (== aV) (verticesOfField fL fW)
+        vx (x,y) = (round x,round y)
+-- =========================================================
+
+-- Gets list of passes in terms of pair of vertices.
+-- Renders lines that reflect given passes. Passes are in 3 possible predefined colors and are rendered separatelly.
+-- ls == [((x,y),c)] where
+-- (x,y) - vertex; c - color
+-- =========================================================
+displayDoneMoves :: (Integral b, Integral a) => [((a, b), Color4 GLfloat)] -> IO ()
+-- =========================================================
+displayDoneMoves ls = do
+   loadIdentity
+   renderPrimitive Lines $ do
+      currentColor $= fstMoveCol
+      mapM_ (\(x,y) -> vertex$Vertex2 (fromIntegral x::GLfloat) (fromIntegral y)) (map fst $ filter ((== fstMoveCol).snd) ls)
+   loadIdentity
+   renderPrimitive Lines $ do
+      currentColor $= sndMoveCol
+      mapM_ (\(x,y) -> vertex$Vertex2 (fromIntegral x::GLfloat) (fromIntegral y)) (map fst $ filter ((== sndMoveCol).snd) ls)
+   loadIdentity
+   renderPrimitive Lines $ do
+      currentColor $= lstMoveCol
+      mapM_ (\(x,y) -> vertex$Vertex2 (fromIntegral x::GLfloat) (fromIntegral y)) (map fst $ filter ((== lstMoveCol).snd) ls)
+-- =========================================================
+
+-- =========================================================
+displayGameNumber (n,i) fL = do
+-- =========================================================
+   loadIdentity
+   translate $ Vector3 0 (fL + 3.5) (0::GLfloat)
+   scale 0.003 0.003 (1::GLfloat)
+   renderString Roman ("Game " ++ show i ++ " out of " ++ show n)
+-- =========================================================
+
+-- =========================================================
+displayGameResult (a,b) fL = do
+-- =========================================================
+   loadIdentity
+   translate $ Vector3 0 (fL + 2.5) (0::GLfloat)
+   scale 0.003 0.003 (1::GLfloat)
+   renderString Roman ("Result " ++ show a ++ " : " ++ show b)
+-- =========================================================
+
+-- =========================================================
+displayName name y col = do
+-- =========================================================
+   loadIdentity
+   translate $ Vector3 0 y (0::GLfloat)
+   scale 0.0021 0.0025 (1::GLfloat)
+   currentColor $= col
+   renderString Roman name
+-- =========================================================
+
+ Foo.hs view
@@ -0,0 +1,495 @@+-- ==================================
+-- Module name: Foo
+-- Project: Foo
+-- Copyright (C) 2007  Bartosz Wójcik
+-- Created on: 01.10.2007
+-- Last update: 07.04.2008
+-- Version: %
+
+{-  This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+-}
+-- ==================================
+module Foo
+
+where
+import Data.List+import Data.Bits
+import FooField
+import FooMove++-- FooState  has been developed as a brilliant idea, that unfortunatelly hasn't worked like expected.
+-- import FooState
+
+-- The program is supposed to play Pencil Soccer against human.
+-- The fileld is defined as a graph. The graph has edges everywhere there where there is a possibility to do a move.
+-- Once move is done, this affects directly the field - appropriate edge is removed
+-- (the idea is taken from Einstein - the space is not constant but changes affected by object and their moves).
++-- AlphaBeta extention helps to prune lot of moves without validatig them. Is useless in case moves are pruned in the way it has been finaly done here.+-- #define AlphaBeta
++
+-- Playing machine constists of:
+-- playing algorithm
+-- Bool - direction, whether played towards goal (_,0)
+-- space of possible moves
+
+data PlayingMachine = Play PlayingAlgorithm Bool Move
+                    | MinValue                                             -- Min value to use function max
+                    | MaxValue                                             -- Max value to use function min
+
+-- List of algorithm can be completed. To do this you have to do 3 actions:
+-- 1. Add algorithm name to the typedefinition
+-- 2. Complete instance Ord for new algorithm (define how moves will be examined)
+-- 3. Describe algorithm in the documentation.
+data PlayingAlgorithm = GoAhead
+                      | GoBackWatchOpponent
+                      | GoAheadWatchOpponent
+                      | PreventingOpponent40
+                      | PreventingOpponent50+                      | Watch2Ahead
+                      | Watch3Ahead+                      deriving (Eq,Ord,Enum,Read,Show)
+
+
+moveOfMachine :: PlayingMachine -> Move
+moveOfMachine (Play _ _ m) = m
+
+-- Selects the best move out of given list of moves.
+bestMove :: [PlayingMachine] -> Move
+bestMove m = moveOfMachine $ foldr max MinValue m
+
+-- Selects the best move out of given list of moves.
+bestMoveWrapped :: [PlayingMachine] -> PlayingMachine
+bestMoveWrapped m = foldr max MinValue m
+
+-- Selects the worst move of the give tree of moves. This is in order to examine possible opponent moves.
+worstMove :: [PlayingMachine] -> PlayingMachine
+worstMove m = foldr min MaxValue m
++-- =============
+#ifdef AlphaBeta
+-- =============
+
+bestMoveAlphaBeta :: PlayingMachine -> [PlayingMachine] -> PlayingMachine
+bestMoveAlphaBeta alpha m = foldr (maxOrBetterThan alpha) MinValue m
+
+worstMoveAlphaBeta :: PlayingMachine -> [PlayingMachine] -> PlayingMachine
+worstMoveAlphaBeta alpha m = foldr (minOrWorseThan alpha) MaxValue m
+
+minOrWorseThan :: (Ord a) => a -> a -> a -> a
+minOrWorseThan alpha x y | alpha > y = y
+                         | otherwise = min x y
+
+maxOrBetterThan :: (Ord a) => a -> a -> a -> a
+maxOrBetterThan alpha x y | alpha < y = y
+                          | otherwise = max x y+-- ======
+#endif
+-- ======
+
+
+instance Eq (PlayingMachine) where
+   MinValue == MinValue = True
+   MaxValue == MaxValue = True
+   _ == _ = False++
+-- =================================================
+-- Instance of compare function is playing engine.
+-- Max over all defined moves gives the chosen move.
+-- =================================================
+-- ================================
+instance Ord (PlayingMachine) where
+-- ================================
+   -- There are compared moves of same generations (depths,plies). Generation doesn't access information about own predescor.
+   -- If algorithm requires this information this has to be done in tricky way, not directly.
+
+   -- Full description of MinValue and MaxValue constructors. --
+   -- =============================================================================================== --
+   compare MinValue _         = LT
+   compare _        MinValue  = GT
+   compare MaxValue _         = GT
+   compare _        MaxValue  = LT
+   -- =============================================================================================== --
+
+   -- Full description of UnfinishedMove constructor. --
+   -- It has been so described that such a move will never be selected.
+   -- =============================================================================================== --
+   compare (Play _ _ (UnfinishedMove _ _))              (Play _ _ (UnfinishedMove _ _))         = EQ
+   compare (Play _ _ (UnfinishedMove _ i))              (Play _ _ _)  | odd i                   = GT
+                                                                      | otherwise               = LT
+   compare (Play _ _ _)                             (Play _ _ (UnfinishedMove _ i)) | odd i     = LT
+                                                                                    | otherwise = GT
+   -- =============================================================================================== --
+
+
+   -- Full description of Goal constructor. --
+   -- =============================================================================================== --
+   compare (Play _ _ (Goal _))                          (Play _ _ (Goal _))                     = EQ
+   compare (Play _ _ (Goal _))                          (Play _ _ _)                            = GT
+   compare (Play _ _ _)                                 (Play _ _ (Goal _))                     = LT
+   -- =============================================================================================== --
+
+   -- Full description of HalfGoal constructor. --
+   -- =============================================================================================== --
+   compare (Play _ _ (HalfGoal _ _))                    (Play _ _ (HalfGoal _ _))               = EQ
+   compare (Play _ _ (HalfGoal _ _))                    (Play _ _ _)                            = GT
+   compare (Play _ _ _)                                 (Play _ _ (HalfGoal _ _))               = LT
+   -- =============================================================================================== --
+
+   -- Full description of LostGoal constructor. --
+   -- =============================================================================================== --
+   compare (Play _ d (LostGoal ((x,y):vs)))             (Play _ _ (LostGoal ((x',y'):vs')))     = EQ
+   compare (Play _ _ _)                                 (Play _ _ (LostGoal _))                 = GT
+   compare (Play _ _ (LostGoal _))                      (Play _ _ _)                            = LT
+   -- =============================================================================================== --
+
+
+   -- Specialization for GoAheadWatchOpponent algorithm.--
+   -- =============================================================================================== --
+   compare p@(Play GoAheadWatchOpponent _ (LastPass _ _ _ _ _ 0 _)) p' = compareWatchingOpponent p p'
+   compare p p'@(Play GoAheadWatchOpponent _ (LastPass _ _ _ _ _ 0 _)) = compareWatchingOpponent p p'
+   -- =============================================================================================== --
+   -- =============================================================================================== --
+   compare p@(Play GoBackWatchOpponent _ (LastPass _ _ _ _ _ 0 _)) p' = compareWatchingOpponent p p'
+   compare p p'@(Play GoBackWatchOpponent _ (LastPass _ _ _ _ _ 0 _)) = compareWatchingOpponent p p'
+   -- =============================================================================================== -- 
+
++   -- Specialization for PreventingOpponent40 algorithm.--
+   -- =============================================================================================== --
+   compare (Play PreventingOpponent40 d m@(LastPass v g l w n i _))
+           p@(Play PreventingOpponent40 _ (LostHalfGoal _ _))
+#ifdef AlphaBeta
+           | i == 0    = compare (worstMoveAlphaBeta p $ mapMove (Play PreventingOpponent40 d ) $ nextMove d (head v) g l w 1) p
+#else
+           | i == 0    = compare (worstMove $ mapSelectedMove (Play PreventingOpponent40 d ) PreventingOpponent40 $ nextMove d (head v) g l w 1) p
+#endif
+           | otherwise = GT
+           -- ================== --
+   compare p@(Play PreventingOpponent40 _ (LostHalfGoal _ _))
+           (Play PreventingOpponent40 d m@(LastPass v g l w n i _))
+           | i == 0    = compare p (worstMove $ mapSelectedMove (Play PreventingOpponent40 d ) PreventingOpponent40 $ nextMove d (head v) g l w 1)
+           | otherwise = LT
+           -- ================== --
+   compare (Play PreventingOpponent40 d (LastPass ((x,y):vs)    g  l w n  i  _))
+           (Play PreventingOpponent40 _ (LastPass ((x',y'):vs') g' _ _ n' i' _))
+#ifdef AlphaBeta
+           | i == 0                            = compare (worstMoveAlphaBeta alpha $ mapMove (Play PreventingOpponent40 d ) $ nextMove d (x,y)   g  l w 1)
+                                                         (alpha)
+#else
+           | i == 0                            = compare (worstMove $ mapSelectedMove (Play PreventingOpponent40 d ) PreventingOpponent40 $ nextMove d (x,y)   g  l w 1)
+                                                         (worstMove $ mapSelectedMove (Play PreventingOpponent40 d ) PreventingOpponent40 $ nextMove d (x',y') g' l w 1)
+#endif
+
+           | y > y' && not d                   = GT
+           | y > y' &&  d                      = LT
+           | y < y' && not d                   = LT
+           | y < y' &&  d                      = GT
+           | y == y' && cTM < cTM'             = GT
+           | y == y' && cTM > cTM'             = LT
+           | otherwise                         = EQ
+           where cTM  | yY < l' / 2 && d
+                      || yY >= l' / 2 && not d = abs $ fromIntegral w / 2 - fromIntegral x
+                      | yY >= l' / 2 && d
+                      || yY < l' / 2 && not d = fromIntegral w / 2 - abs (fromIntegral w / 2 - fromIntegral x)
+                 cTM' | yY' < l' / 2 && d
+                      || yY' >= l' / 2 && not d = abs $ fromIntegral w / 2 - fromIntegral x'
+                      | yY' >= l' / 2 && d
+                      || yY' < l' / 2 && not d = fromIntegral w / 2 - abs (fromIntegral w / 2 - fromIntegral x')
+                 l' = fromIntegral l
+                 yY' = fromIntegral y'
+                 yY = fromIntegral y
+#ifdef AlphaBeta
+                 alpha = worstMove $ mapMove (Play PreventingOpponent40 d ) $ nextMove d (x',y') g' l w 1
+#endif
+   -- =============================================================================================== --
++   -- Specialization for PreventingOpponent50 algorithm.--
+   -- =============================================================================================== --
+   compare (Play PreventingOpponent50 d m@(LastPass v g l w n i _))
+           p@(Play PreventingOpponent50 _ (LostHalfGoal _ _))
+#ifndef AlphaBeta
+           | i == 0    = compare (worstMove $ mapSelectedMove (Play PreventingOpponent50 d ) PreventingOpponent50 $ nextMove d (head v) g l w 1) p
+#endif
+           | otherwise = GT
+           -- ================== --
+   compare p@(Play PreventingOpponent50 _ (LostHalfGoal _ _))
+           (Play PreventingOpponent50 d m@(LastPass v g l w n i _))
+           | i == 0    = compare p (worstMove $ mapSelectedMove (Play PreventingOpponent50 d ) PreventingOpponent50 $ nextMove d (head v) g l w 1)
+           | otherwise = LT
+           -- ================== --
+   compare (Play PreventingOpponent50 d (LastPass ((x,y):vs)    g  l w n  i  _))
+           (Play PreventingOpponent50 _ (LastPass ((x',y'):vs') g' _ _ n' i' _))
+#ifndef AlphaBeta
+           | i == 0                            = compare (worstMove $ mapSelectedMove (Play PreventingOpponent50 d ) PreventingOpponent50 $ nextMove d (x,y)   g  l w 1)
+                                                         (worstMove $ mapSelectedMove (Play PreventingOpponent50 d ) PreventingOpponent50 $ nextMove d (x',y') g' l w 1)
+#endif
+
+           | y > y' && not d                   = GT
+           | y > y' &&  d                      = LT
+           | y < y' && not d                   = LT
+           | y < y' &&  d                      = GT
+           | y == y' && cTM < cTM'             = GT
+           | y == y' && cTM > cTM'             = LT
+           | otherwise                         = EQ
+           where cTM  | yY < l' / 2 && d
+                      || yY >= l' / 2 && not d = abs $ fromIntegral w / 2 - fromIntegral x
+                      | yY >= l' / 2 && d
+                      || yY < l' / 2 && not d = fromIntegral w / 2 - abs (fromIntegral w / 2 - fromIntegral x)
+                 cTM' | yY' < l' / 2 && d
+                      || yY' >= l' / 2 && not d = abs $ fromIntegral w / 2 - fromIntegral x'
+                      | yY' >= l' / 2 && d
+                      || yY' < l' / 2 && not d = fromIntegral w / 2 - abs (fromIntegral w / 2 - fromIntegral x')
+                 l' = fromIntegral l
+                 yY' = fromIntegral y'
+                 yY = fromIntegral y
+   -- =============================================================================================== --
+
+{-   -- Specialization for GoBackLookForward algorithm.--
+   -- =============================================================================================== --
+   compare (Play GoBackLookForward d m@(LastPass v g l w n i _))
+           p@(Play GoBackLookForward _ (LostHalfGoal _ _))
+           | i == 0    = compare (worstMove $ mapMove (Play GoBackLookForward d ) $ nextMove d (head v) g l w 1) p
+           | otherwise = GT
+           -- ================== --
+   compare p@(Play GoBackLookForward _ (LostHalfGoal _ _))
+           (Play GoBackLookForward d m@(LastPass v g l w n i _))
+           | i == 0    = compare p (worstMove $ mapMove (Play GoBackLookForward d ) $ nextMove d (head v) g l w 1)
+           | otherwise = LT
+           -- ================== --
+   compare (Play GoBackLookForward d (LastPass ((x,y):vs)    g  l w n  i  _))
+           (Play GoBackLookForward _ (LastPass ((x',y'):vs') g' _ _ n' i' _))
+           | i == 0                            = compare (worstMove $ mapMove (Play GoBackLookForward d ) $ nextMove d (x,y)   g  l w 1)
+                                                         (worstMove $ mapMove (Play GoBackLookForward d ) $ nextMove d (x',y') g' l w 1)
+           | y > y' && not d                   = LT
+           | y > y' &&  d                      = GT
+           | y < y' && not d                   = GT
+           | y < y' &&  d                      = LT
+           | y == y' && cTM < cTM'             = GT
+           | y == y' && cTM > cTM'             = LT
+           | otherwise                         = EQ
+           where cTM  | yY < l' / 2 && d
+                      || yY >= l' / 2 && not d = abs $ fromIntegral w / 2 - fromIntegral x
+                      | yY >= l' / 2 && d
+                      || yY < l' / 2 && not d = fromIntegral w / 2 - abs (fromIntegral w / 2 - fromIntegral x)
+                 cTM' | yY' < l' / 2 && d
+                      || yY' >= l' / 2 && not d = abs $ fromIntegral w / 2 - fromIntegral x'
+                      | yY' >= l' / 2 && d
+                      || yY' < l' / 2 && not d = fromIntegral w / 2 - abs (fromIntegral w / 2 - fromIntegral x')
+                 l' = fromIntegral l
+                 yY' = fromIntegral y'
+                 yY = fromIntegral y
+   -- =============================================================================================== -- -}
+++   -- Specialization for Watch2Ahead algorithm.--+   -- =============================================================================================== --
+   compare (Play Watch2Ahead d m@(LastPass v g l w n i _))
+           p@(Play Watch2Ahead _ (LostHalfGoal _ _))
+#ifdef AlphaBeta
+           | i == 0    = compare (worstMoveAlphaBeta p $ mapMove (Play Watch2Ahead d ) $ nextMove d (head v) g l w 1) p
+           | i == 1    = compare (bestMoveAlphaBeta p $ mapMove (Play Watch2Ahead d ) $ nextMove d (head v) g l w 2) p
+#else
           | i == 0    = compare (worstMove $ mapSelectedMove (Play Watch2Ahead d ) Watch2Ahead $ nextMove d (head v) g l w 1) p
+           | i == 1    = compare (bestMoveWrapped $ mapSelectedMove (Play Watch2Ahead d ) Watch2Ahead $ nextMove d (head v) g l w 2) p
+#endif
+           | otherwise = GT
+           -- ================== --
+   compare p@(Play Watch2Ahead _ (LostHalfGoal _ _))
+           (Play Watch2Ahead d m@(LastPass v g l w n i _))
+           | i == 0    = compare p (worstMove $ mapSelectedMove (Play Watch2Ahead d ) Watch2Ahead $ nextMove d (head v) g l w 1)
+           | i == 1    = compare p (bestMoveWrapped $ mapSelectedMove (Play Watch2Ahead d ) Watch2Ahead $ nextMove d (head v) g l w 2)
+           | otherwise = LT
+           -- ================== --
+   compare (Play Watch2Ahead d (LastPass ((x,y):vs)    g  l w n  i  _))
+           (Play Watch2Ahead _ (LastPass ((x',y'):vs') g' _ _ n' i' _))
+#ifdef AlphaBeta
+           | i == 0                            = compare (worstMoveAlphaBeta alpha $ mapMove (Play Watch2Ahead d ) $ nextMove d (x,y)   g  l w 1)
+                                                         (alpha)
+           | i == 1                            = compare (bestMoveAlphaBeta beta $ mapMove (Play Watch2Ahead d ) $ nextMove d (x,y)   g  l w 2)
+                                                         (beta)
+#else
+           | i == 0                            = compare (worstMove $ mapSelectedMove (Play Watch2Ahead d ) Watch2Ahead $ nextMove d (x,y)   g  l w 1)
+                                                         (worstMove $ mapSelectedMove (Play Watch2Ahead d ) Watch2Ahead $ nextMove d (x',y') g' l w 1)
+           | i == 1                            = compare (bestMoveWrapped $ mapSelectedMove (Play Watch2Ahead d ) Watch2Ahead $ nextMove d (x,y)   g  l w 2)
+                                                         (bestMoveWrapped $ mapSelectedMove (Play Watch2Ahead d ) Watch2Ahead $ nextMove d (x',y') g' l w 2)
+#endif
+           | y > y' && not d                   = GT
+           | y > y' &&  d                      = LT
+           | y < y' && not d                   = LT
+           | y < y' &&  d                      = GT
+           | y == y' && cTM < cTM'             = GT
+           | y == y' && cTM > cTM'             = LT
+           | otherwise                         = EQ
+           where cTM  | yY < l' / 2 && d
+                      || yY >= l' / 2 && not d = abs $ fromIntegral w / 2 - fromIntegral x
+                      | yY >= l' / 2 && d
+                      || yY < l' / 2 && not d = fromIntegral w / 2 - abs (fromIntegral w / 2 - fromIntegral x)
+                 cTM' | yY' < l' / 2 && d
+                      || yY' >= l' / 2 && not d = abs $ fromIntegral w / 2 - fromIntegral x'
+                      | yY' >= l' / 2 && d
+                      || yY' < l' / 2 && not d = fromIntegral w / 2 - abs (fromIntegral w / 2 - fromIntegral x')
+                 l' = fromIntegral l
+                 yY' = fromIntegral y'
+                 yY = fromIntegral y
+#ifdef AlphaBeta
+                 alpha = worstMove $ mapMove (Play Watch2Ahead d ) $ nextMove d (x',y') g' l w 1
+                 beta  = bestMoveWrapped $ mapMove (Play Watch2Ahead d ) $ nextMove d (x',y') g' l w 2
+#endif+   -- =============================================================================================== --
++   -- Specialization for Watch3Ahead algorithm.--
+   -- =============================================================================================== --
+   compare (Play Watch3Ahead d m@(LastPass v g l w n i _))
+           p@(Play Watch3Ahead _ (LostHalfGoal _ _))
+#ifndef AlphaBeta
+           | i == 0    = compare (worstMove $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (head v) g l w 1) p
+           | i == 1    = compare (bestMoveWrapped $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (head v) g l w 2) p
+           | i == 2    = compare (worstMove $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (head v) g l w 3) p
+#endif
+           | otherwise = GT
+           -- ================== --
+   compare p@(Play Watch3Ahead _ (LostHalfGoal _ _))
+           (Play Watch3Ahead d m@(LastPass v g l w n i _))
+           | i == 0    = compare p (worstMove $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (head v) g l w 1)
+           | i == 1    = compare p (bestMoveWrapped $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (head v) g l w 2)
+           | i == 2    = compare p (worstMove $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (head v) g l w 3)
+           | otherwise = LT
+           -- ================== --
+   compare (Play Watch3Ahead d (LastPass ((x,y):vs)    g  l w n  i  _))
+           (Play Watch3Ahead _ (LastPass ((x',y'):vs') g' _ _ n' i' _))
+#ifndef AlphaBeta
+           | i == 0                            = compare (worstMove $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (x,y)   g  l w 1)
+                                                         (worstMove $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (x',y') g' l w 1)
+           | i == 1                            = compare (bestMoveWrapped $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (x,y)   g  l w 2)
+                                                         (bestMoveWrapped $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (x',y') g' l w 2)
+           | i == 2                            = compare (worstMove $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (x,y)   g  l w 3)
+                                                         (worstMove $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (x',y') g' l w 3)
+#endif
+           | y > y' && not d                   = GT
+           | y > y' &&  d                      = LT
+           | y < y' && not d                   = LT
+           | y < y' &&  d                      = GT
+           | y == y' && cTM < cTM'             = GT
+           | y == y' && cTM > cTM'             = LT
+           | otherwise                         = EQ
+           where cTM  | yY < l' / 2 && d
+                      || yY >= l' / 2 && not d = abs $ fromIntegral w / 2 - fromIntegral x
+                      | yY >= l' / 2 && d
+                      || yY < l' / 2 && not d = fromIntegral w / 2 - abs (fromIntegral w / 2 - fromIntegral x)
+                 cTM' | yY' < l' / 2 && d
+                      || yY' >= l' / 2 && not d = abs $ fromIntegral w / 2 - fromIntegral x'
+                      | yY' >= l' / 2 && d
+                      || yY' < l' / 2 && not d = fromIntegral w / 2 - abs (fromIntegral w / 2 - fromIntegral x')
+                 l' = fromIntegral l
+                 yY' = fromIntegral y'
+                 yY = fromIntegral y
+#ifdef AlphaBeta
+                 alpha = worstMove $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (x',y') g' l w 1
+                 beta  = bestMoveWrapped $ mapSelectedMove (Play Watch3Ahead d ) Watch3Ahead $ nextMove d (x',y') g' l w 2
+#endif
+   -- =============================================================================================== --
+
+   -- Basic description of LostHalfGoal constructor. --
+   -- =============================================================================================== --
+   compare (Play _ _ (LostHalfGoal _ _))         (Play _ _ (LostHalfGoal _ _))        = EQ
+   compare (Play _ _ (LastPass _ _ _ _ _ i _))   (Play _ _ (LostHalfGoal _ _))        = GT
+   compare (Play _ _ (LostHalfGoal _ _))         (Play _ _ (LastPass _ _ _ _ _ i' _)) = LT
+   -- =============================================================================================== --
+
+   compare (Play a  d  (LastPass ((x,y):vs)    g  l  w  n  i  m))
+           (Play a' d' (LastPass ((x',y'):vs') g' l' w' n' i' m'))
+           | y > y' && not d                   = GT
+           | y > y' &&  d                      = LT
+           | y < y' && not d                   = LT
+           | y < y' &&  d                      = GT
+           | y == y' && cTM < cTM'             = GT
+           | y == y' && cTM > cTM'             = LT
+           | y == y' && cTM == cTM' && n > n'  = GT
+           | y == y' && cTM == cTM' && n < n'  = LT
+           | y == y' && cTM == cTM' && n == n' = EQ
+           where cTM  = abs $ fromIntegral w / 2 - fromIntegral x
+                 cTM' = abs $ fromIntegral w / 2 - fromIntegral x'
+
+   compare _ _ = EQ       -- just in case
+-- ====================================
+-- end of instance Ord (PlayingMachine)
+-- ====================================
+-- ----------------------------------------------------------------------
+
+-- Idea is following.
+-- If opponent can score a goal after current move this move is value 0.
+-- If move is LostHalfGoal its value is 1.
+-- If move is Goal, its value is VERY BIG.
+-- Otherwise value of the move is algorithm dependent; higher, closer to opponent goal move finishes.
+-- Then compare moves.
+compareWatchingOpponent :: PlayingMachine -> PlayingMachine -> Ordering
+compareWatchingOpponent p1 p2 | p1' == 0   = LT
+                              | p2' == 0   = GT
+                              | otherwise  = compare (valueOfMove p1) (valueOfMove p2)
+                              where p1' = valueOfMove $ nextWorstMove p1
+                                    p2' = valueOfMove $ nextWorstMove p2
+
+-- Select worst (for us) opponent answer.
+nextWorstMove :: PlayingMachine -> PlayingMachine
+nextWorstMove (Play a d (LastPass ((x,y):vs) g l w _ i _)) = worstMove $ mapMove (Play a d ) $ nextMove d (x,y) g l w (i + 1)
+nextWorstMove p = p
+
+-- Give value of the move.
+valueOfMove :: PlayingMachine -> Int
+-- Different algorithms use different ways of scoring.
+valueOfMove (Play GoBackWatchOpponent d (LastPass ((x,y):vs) _ l w n _ _)) | d         = y*l + w - (round $ abs $ fromIntegral w / 2 - fromIntegral x) + n
+                                                                           | otherwise = (l-y)*l + w - (round $ abs $ fromIntegral w / 2 - fromIntegral x) + n
+valueOfMove (Play _ d (LastPass ((x,y):vs) _ l w n _ _)) | d         = (l-y)*l + w - (round $ abs $ fromIntegral w / 2 - fromIntegral x) + n
+                                                         | otherwise = y*l + w - (round $ abs $ fromIntegral w / 2 - fromIntegral x) + n
+valueOfMove (Play _ _ (LostGoal _)) = 0
+valueOfMove (Play _ _ (LostHalfGoal _ _)) = 1
+valueOfMove (Play _ _ (HalfGoal _ _)) = 1000
+valueOfMove _ = 0
+
+++-- Maps given function on selected leaves of tree of moves.+-- It select moves that finish match and given number of the others.+-- This function has very important meaning for the efficiency and speed of playing machines. +-- It is a main hash function. It bases on observations, that:+--    Longer moves diminish space of moves, so selecting longer moves leads to faster playing machines+--    When many moves finish in the same vetrex, longer ones are usually not worse than shorter. +--    Short moves shoudn't be pruned if they are Goal, LostGoal, HalfGoal nad LostHalfGoal. Otherwise they might be omitted by plaiyng machine.+-- Balance between speed when not much moves are selected to next ply and risk that some important moves will be omitted has been selected on experimental way.+-- It is not ensured that all possible end vertices are represented by at least 1 move. This would be strong improvement of this function+-- although would lead to additional costs that then would need to be checed if they are acceptable.   +
+mapSelectedMove f  PreventingOpponent40       m = takeLastMove 40 0 $ mapMove f m+mapSelectedMove f  PreventingOpponent50       m = takeLastMove 50 0 $ mapMove f m+mapSelectedMove f  Watch2Ahead                m = takeLastMove 30 0 $ mapMove f m+mapSelectedMove f  Watch3Ahead                m = takeLastMove 18 0 $ mapMove f m+mapSelectedMove f  _                          m = takeLastMove 1000 0 $ mapMove f m++-- Takes from the list of moves (wrapped into PlayingMachine) one move each type that finishes match (assuming they are always firsts elements of the list)+-- and 'n' next elements (they are supposed to be LastPass)+takeLastMove :: Int -> Int -> [PlayingMachine] -> [PlayingMachine]+takeLastMove n bits lp@((Play _ _ (LastPass _ _ _ _ _ _ _)):ls)                 = take n lp+takeLastMove n bits (p@(Play _ _ (Goal _)):lp)                 | testBit bits 0 = takeLastMove n bits lp+                                                               | otherwise      = p : takeLastMove n (setBit bits 0) lp+takeLastMove n bits (p@(Play _ _ (HalfGoal _ _)):lp)           | testBit bits 1 = takeLastMove n bits lp+                                                               | otherwise      = p : takeLastMove n (setBit bits 1) lp+takeLastMove n bits (p@(Play _ _ (LostGoal _)):lp)             | testBit bits 2 = takeLastMove n bits lp+                                                               | otherwise      = p : takeLastMove n (setBit bits 2) lp+takeLastMove n bits (p@(Play _ _ (LostHalfGoal _ _)):lp)       | testBit bits 3 = takeLastMove n bits lp+                                                               | otherwise      = p : takeLastMove n (setBit bits 3) lp+takeLastMove n bits (p:lp)                                                      = p : takeLastMove n bits lp+takeLastMove n _ []                                                             = []+
+ FooField.hs view
@@ -0,0 +1,166 @@+-- ==================================
+-- Module name: FooField
+-- Project: Foo
+-- Copyright (C) 2007  Bartosz Wójcik
+-- Created on: 01.10.2007
+-- Last update: 07.04.2008
+-- Version: %
+
+{-  This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+-}
+-- ==================================
+module FooField
+where
+
+-- This module provides bunch of functions creating filed for the game, manipulating on this field and giving different
+-- information about current field status or part of it.
+
+-- Field is a graph that consists of list of unique vertices, each of 2 coortinates, where the vetex has following informaion:
+-- one flag whether vertex is "active"
+-- list of vertices it has edge to.
+
+import Data.List
+
+-- One of 2 precompiler options have to be active:
+-- either ArrayGraph or MapGraph (MapGraph brings 10-30% acceleration of playing machine)
+#define MapGraph
+-- #define ArrayGraph++-- Next option is meaningfull only in ArrayGraph case.+-- It accelerates playing machine a bit, but less in comparison to MapGraph option.
+#define DiffArrayGraph
++-- --------------------------------
-- Field definition based on Arrays+-- --------------------------------
+#ifdef ArrayGraph
+
+#ifdef DiffArrayGraph
+import Data.Array.Diff
+#else
+import Array
+#endif
+
+type Vertex = (Int,Int)
+type Value = (Bool,[Vertex])
+#ifdef DiffArrayGraph
+type Graph = DiffArray Vertex Value
+#else
+type Graph = Array Vertex Value
+#endif
+
+-- Initial filed
+field :: Int -> Int -> Graph
+field fL fW = array ((0,0),(fW,fL+2)) [((x,y),(x == hW && y == hL || x == 0 || x == fW || (y == 1 || y == fL+1) && x /= hW, -- whether vertex is already 'active'
+                                           [(a,b) | a<-[(x-1)..(x+1)] , b<-[(y-1)..(y+1)],                                  -- edges to all neighbour fields
+                                                    b > 1 || y > 1 || x == hW || a == hW,                                   -- line on the goal has some limitations
+                                                    b < fL+1 || y < fL+1 || x == hW || a == hW,                             -- line on 2nd goal as well
+                                                    b >= 0, b < fL + 3,                                                     -- field length limitations
+                                                    x > 0 || a > 0,                                                         -- side line
+                                                    x < fW || a < fW,                                                       -- 2nd side line
+                                                    (a,b) /= (x,y)]))                                                       -- no edge to the same vertex
+                                             | x<-[0..fW], y<-[0..fL+2]]                                                    -- field's coordinates
+              where hL = round (fromIntegral fL / 2) + 1 -- half of Length - position of the middle of the filed
+                    hW = round (fromIntegral fW / 2)     -- half of Width  - position of the middle of the filed
+
+
+-- Removes edge from the graph. Edge is entered as 2 vertices.
+rmEdge :: Vertex -> Vertex -> Graph -> Graph
+rmEdge v1 v2 g = g // [(v1,(True,[v | v <- vertices v1 g, v /= v2])),(v2,(True,[v | v <- vertices v2 g, v /= v1]))]
+
+-- Removes connections between successors of v2 and v2.
+-- Use it: rmEdges (vertices v g) v g
+rmEdges :: [Vertex] -> Vertex -> Graph -> Graph
+rmEdges vl v2 g = g // ([(v2,(True,[]))] ++ [(v1,(active v1 g,[v | v <- vertices v1 g, v /= v2])) | v1 <- vl])
+
+-- List of vertices that constuct edges with given vertex.
+vertices :: Vertex -> Graph -> [Vertex]
+vertices v g = snd(g!v)
+
+-- Whether vertex is active
+active :: Vertex -> Graph -> Bool
+active v g = fst(g!v)
+
+-- Checks if there is edge between 2 vertices.
+chckEdge :: Vertex -> Vertex -> Graph -> Bool
+chckEdge v1 v2 g = (== [v2]) $ filter (== v2) (vertices v1 g)
+#endif
++-- --------------------------------
-- Field definition based on Maps+-- --------------------------------
+#ifdef MapGraph
+import qualified Data.Map as Map
+import Array
+
+
+type Vertex = (Int,Int)
+type Value = (Bool,[Vertex])
+type Graph = Map.Map Vertex Value
+
+-- Initial filed
+field :: Int -> Int -> Graph
+field fL fW = Map.fromList [((x,y),(x == hW && y == hL || x == 0 || x == fW || (y == 1 || y == fL+1) && x /= hW, -- whether vertex is already 'active'
+                                           [(a,b) | a<-[(x-1)..(x+1)] , b<-[(y-1)..(y+1)],                                  -- edges to all neighbour fields
+                                                    b > 1 || y > 1 || x == hW || a == hW,                                   -- line on the goal has some limitations
+                                                    b < fL+1 || y < fL+1 || x == hW || a == hW,                             -- line on 2nd goal as well
+                                                    b >= 0, b < fL + 3,                                                     -- field length limitations
+                                                    x > 0 || a > 0,                                                         -- side line
+                                                    x < fW || a < fW,                                                       -- 2nd side line
+                                                    (a,b) /= (x,y)]))                                                       -- no edge to the same vertex
+                                             | x<-[0..fW], y<-[0..fL+2]]                                                    -- field's coordinates
+              where hL = round (fromIntegral fL / 2) + 1 -- half of Length - position of the middle of the filed
+                    hW = round (fromIntegral fW / 2)     -- half of Width  - position of the middle of the filed
+
+
+-- Removes edge from the graph. Edge is entered as 2 vertices.
+rmEdge :: Vertex -> Vertex -> Graph -> Graph
+rmEdge v1 v2 g = Map.adjust (rmSuccesor v2) v1 $ Map.adjust (rmSuccesor v1) v2 g
+
+rmSuccesor :: Vertex -> Value -> Value
+rmSuccesor succesor (val,ls) = (True,[v | v <- ls, v /= succesor])
+
+-- Removes all edges of vertex v.
+-- First removes connections between successors of v and v then vice versa (as connections are directed).
+rmSuccesors :: Vertex -> Graph -> Graph
+rmSuccesors v g = (Map.adjust (\(val,vs) -> (val,[])) v . rmEdges (vertices v g) v) g
+
+-- Removes connections between successors of v2 and v2.
+-- Use it: rmEdges (vertices v g) v g
+rmEdges :: [Vertex] -> Vertex -> Graph -> Graph
+rmEdges []      v2 g = g
+rmEdges (v1:vl) v2 g = rmEdges vl v2 (Map.adjust (rmSuccesor v1) v2 g)
+
+-- List of vertices that constuct edges with given vertex.
+vertices :: Vertex -> Graph -> [Vertex]
+vertices v g = snd(g Map.! v)
+
+-- Whether vertex is active
+active :: Vertex -> Graph -> Bool
+active v g = fst(g Map.! v)
+
+-- Checks if there is edge between 2 vertices.
+chckEdge :: Vertex -> Vertex -> Graph -> Bool
+chckEdge v1 v2 g = (== [v2]) $ filter (== v2) (vertices v1 g)
+#endif
+
+-- Returns a mark of given edge. The mark is unique within defined graph.+-- Used for recognition same moves that are separatelly unfolded.
+markEdge :: (Num b, Ord b) => b -> (b, b) -> (b, b) -> b
+markEdge fW v1 v2 = 4 * (maxX * fW + maxY) + edgeNum
+                  where (maxX,maxY) = max v1 v2
+                        (minX,minY) = min v1 v2
+                        edgeNum | minY >  maxY = 0
+                                | minY == maxY = 1
+                                | minX == maxX = 2
+                                | otherwise    = 3
+
+ FooMove.hs view
@@ -0,0 +1,377 @@+-- ==================================
+-- Module name: FooMove
+-- Project: Foo
+-- Copyright (C) 2007  Bartosz Wójcik
+-- Created on: 01.10.2007
+-- Last update: 07.04.2008
+-- Version: %
+
+{-  This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+-}
+-- ==================================
+module FooMove
+where
+
+import qualified Data.Map as Map
+import Data.List
+import FooField
+import Monad
++-- This module constructs space of possible moves for a given field, initial vertex and direction towards one of the goals.
+-- Provides bunch of funcions manipulating on moves.
+++
+-- One of following has to be active:
+-- MoveSimple
+-- MoveImproved1    (expected acceleration x5 to x30)
+-- MergePlies
+   -- MergePlies reduces numer of examined moves by recognizing duplications even if they are split into plies.
+   -- Additionally it reduces moves' comparison overhead as it stops only when given number of plies is created.
+   -- Comparing function gets at very beginnig final space of moves of given ply.
+   -- MergePlies makes AlphaBeta useless, so it's cheaper to switch it off.+   -- Finally MergePlies hasn't resulted in playing machine acceleration and I dropped its further development. By now I'm not sure if this option compiles.
+
+-- #define MoveSimple
+#define MoveImproved1
+-- #define MergePlies
+
+-- MoveImproved2 is optional for MoveImproved1 switched on.+-- It switches on more efficient way of duplicated moves recognition. It assumes that duplicated move has to have a cycle
+-- and doesn't check moves that don't have cycles.
+#define MoveImproved2
+
+
+-- Each move consists of passes. Pass is an existing edge between 2 vetices. Each pass can be either
+-- intermedium pass - such one that doesn't finish move;
+-- final pass - such one that finishes move.
+
+-- Vertex - vertex
+-- Graph - graph
+-- l - length of field
+-- w - width of field
+-- Bool - whether Vertex is active. Inactive vertices lead to LastPass.
+-- n - number of pass in the move
+-- i - number of depth. The real move is depth 0, move against is depth 1 etc.+
+data Move = NextPass                                -- intermedate, recently constructed pass. Contains all information required to continue constructin space of passes.
+                     [Vertex]                                   -- List of vertices constructing move until this point.
+                     Graph                                      -- Graph after pass.
+                     Int Int                                    -- Size of field. Lenght and width.
+                     Bool                                       -- Active last vertex flag.
+                     Int                                        -- Number of passes within the move
+                     Int                                        -- Depth of the move. 0-inspected move; 1-ply + 1;...
+#ifdef MergePlies
+                     [Vertex]                                   -- List of vertices constructing move until end of ply 0.
+#else
+                     [Move]                                     -- List of moves that can start from this point under current circumstances
+#endif
+                     (Map.Map Int Bool)                         -- Set of edges of current move ordered by edge mark
+                     (Map.Map Vertex Int)                       -- Set of ordered vertices having number of occurences within the move. Used for cycle recognition.
+          | Pass [Move]                             -- intermediate pass keeps just pointer to next passes
+          | LastPass                                -- Last pass within the move. Doesn't finish the game.
+                     [Vertex] Graph Int Int Int Int [Move]      -- See description of NextPass
+#ifdef MergePlies
+                     Vertex                                   -- Last vertex after move of last examined ply.
+#endif
+
+          | Goal [Vertex]                           -- Move finished in the opponent's goal. Keeps list of vertices constructing it.
+          | LostGoal [Vertex]                       -- Move finished in the own goal. Keeps list of vertices constructing it.
+          | LostHalfGoal [Vertex] Graph             -- Move finished because of no passes available. Keeps list of vertices constructing it.
+          | HalfGoal [Vertex] Graph                 -- The same but occured while examining possible opponent's moves.
+          | UnfinishedMove [Vertex] Int             -- Too many passes to examine this move further.
+
+
+instance Show (Move) where
+   show (Pass _) = "Pass"
+#ifdef MergePlies
+   show (LastPass v _ _ _ _ i _ _) = "LastPass " ++ concat (map show v)
+#else
+   show (LastPass v _ _ _ _ i _) = "LastPass " ++ concat (map show v)
+#endif
+   show (Goal v) = "Goal " ++ concat (map show v)
+   show (LostGoal v) = "LostGoal " ++ concat (map show v)
+   show (LostHalfGoal v _) = "LostHalfGoal " ++ concat (map show v)
+   show (HalfGoal v _) = "HalfGoal " ++ concat (map show v)
+   show (UnfinishedMove v _) = "UnfinishedMove " ++ concat (map show v)
+
+-- Cast move on vertices axe.
+vOfMove :: Move -> [Vertex]
+vOfMove (Pass _)                 = []
+#ifdef MergePlies
+vOfMove (LastPass v _ _ _ _ _ _ _) = v
+#else
+vOfMove (LastPass v _ _ _ _ _ _) = v
+#endif
+vOfMove (Goal v)                 = v
+vOfMove (LostGoal v)             = v
+vOfMove (LostHalfGoal v _)       = v
+vOfMove (HalfGoal v _)           = v
+vOfMove (UnfinishedMove v _)     = v
+
+-- Returns field after move.
+graphAfterPass :: Graph -> Move -> Graph
+#ifdef MergePlies
+graphAfterPass g afterBestMove@(LastPass _ g' _ _ _ _ _ _) = g'
+#else
+graphAfterPass g afterBestMove@(LastPass _ g' _ _ _ _ _) = g'
+#endif
+graphAfterPass g afterBestMove@(LostHalfGoal _ g')       = g'
+graphAfterPass g afterBestMove@(HalfGoal _ g')           = g'
+graphAfterPass g _                                       = g
+
+-- ====================================
+-- Function constructing space of moves
+-- ====================================++-- ==========+-- MoveSimple
+-- ==========+#ifdef MoveSimple
+
+nextPass :: Bool -> Move -> Move
+-- Below 3 lines have to be adjusted on experimental way for the processor power.
+nextPass d (NextPass vs g fL fW True 5 2 [] _ _)   | vertices (head vs) g /= []        = UnfinishedMove vs 2
+nextPass d (NextPass vs g fL fW True 8 1 [] _ _)   | vertices (head vs) g /= []        = UnfinishedMove vs 1
+nextPass d (NextPass vs g fL fW True 13 0 [] _ _)  | vertices (head vs) g /= []        = UnfinishedMove vs 0
+nextPass d (NextPass vs g fL fW True n i [] m mV)  | even i && noPass                  = LostHalfGoal vs g
+                                                   | noPass                            = HalfGoal vs g
+                                                   | otherwise                         = Pass [nextPass d (NextPass (v':vs) (rmEdge v v' g) fL fW (active v' g) (n+1) i [] m mV) |v' <- vertices v g]
+                                              where v = head vs
+                                                    noPass = vertices v g == []
+nextPass d (NextPass vs g fL fW False n i [] _ _) | y == 0 && d || y == fL + 2 && not d      = Goal vs
+                                                  | y == 0 && not d || y == fL + 2 && d      = LostGoal vs
+                                                  | otherwise                                = LastPass vs g fL fW n i [nextMove d v g fL fW (i+1)]
+                                       where y = snd v
+                                             v = head vs
+
+-- ==================================================================+-- The main function of this modul that returns full space of moves.
+-- ==================================================================+-- Later I'll use lazyness to limit this space to size which I think will be practical. Full space of moves is by now too big for my hardware.
+-- d - if plays towards (_,0) goal
+-- v - initial vertex
+-- g - initial graph
+-- fL, fW - field size (length, width)
+-- i - depth number - first move has depth 0, answer depth 1, etc...
+nextMove :: Bool -> Vertex -> Graph -> Int -> Int -> Int -> Move
+nextMove d v g fL fW i = nextPass d (NextPass [v] g fL fW True 0 i [] Map.empty Map.empty)
+-- ==================================================================+
+#endif
+
+-- Returns numer of possible moves for given tree of moves until given depth.
+sizeMove :: (Num b) => Int -> Move -> b
+sizeMove t (Pass m)                             = foldr ((+).sizeMove t) 0 m
+sizeMove t (LastPass _ _ _ _ _ i m) | i == t    = 1
+                                    | otherwise = foldr ((+).sizeMove t) 0 m
+sizeMove _          _                           = 1
+
+-- Walks through tree of moves folding it using given function f.
+foldMove :: (b -> b -> b) -> b -> Move -> b
+foldMove f value (Pass m) = foldr (f . foldMove f value) value m
+foldMove _ value _        = value
+
+-- Maps given function on all leaves of tree of moves.
+mapMove :: (Move -> a) -> Move -> [a]
+mapMove f (Pass ms) = concat $ map (mapMove f) ms
+mapMove f m         = [f m]
+
+-- ===================================================
+
+-- =============+-- MoveImproved1
+-- =============
+-- Processes current move one pass further. Move is processed so, that first all next passes for until now recognized moves are
+-- processed, then duplicated moves are removed and so on. Kind of "breadth-first search".+#ifdef MoveImproved1
+nextPass :: Bool -> Move -> [Move]
+nextPass d (NextPass vs g fL fW True n i [] m mV)| even i && noPass      = [LostHalfGoal vs g]
+                                                 | noPass                = [HalfGoal vs g]
+                                                 | otherwise             = [NextPass (v':vs) (rmEdge v v' g) fL fW (active v' g) (n+1) i [] (Map.insert (markEdge fW v v') True m) (Map.insertWith (+) v' 1 mV) |v' <- vertices v g] 
+                                                 where v = head vs
+                                                       noPass = vertices v g == []
+nextPass d (NextPass vs g fL fW False n i [] _ _) | y == 0 && d || y == fL + 2 && not d  = [Goal vs]
+                                                  | y == 0 && not d || y == fL + 2 && d  = [LostGoal vs]
+                                                  | otherwise                            = [LastPass vs g fL fW n i [nextMove d v g fL fW (i+1)]]
+                                          where y = snd v
+                                                v = head vs
+-- ==================================================================+-- The main function of this modul that returns full space of moves.
+-- ==================================================================+-- Later I'll use lazyness to limit this space to size which I think will be practical. Full space of moves is by now too big for my hardware.
+-- d - if plays towards (_,0) goal (direction)
+-- v - initial vertex
+-- g - initial graph
+-- fL, fW - field size (length, width)
+-- i - depth number - first move has depth 0, answer depth 1, etc...
+nextMove :: Bool -> Vertex -> Graph -> Int -> Int -> Int -> Move
+nextMove d v g fL fW i = Pass (nNextMove d [NextPass [v] g fL fW True 1 i [] (Map.empty) (Map.insert v 1 Map.empty)]) 
+-- ==================================================================++-- Applies nextPass to all by now recognized moves.
+nextAllPasses :: Bool -> [Move] -> [Move]
+nextAllPasses d ls = (concat $ map (nextPass d) ls) +
++-- Couple of functions that categorize moves.
+isNextPass :: Move -> Bool
+isNextPass (NextPass _ _ _ _ _ _ _ _ _ _) = True
+isNextPass _                              = False++isLastPass :: Move -> Bool
+isLastPass (LastPass _ _ _ _ _ _ _) = True
+isLastPass _                        = False
++finishesMatch :: Move -> Bool
+finishesMatch (Goal _ )          = True+finishesMatch (LostGoal _)       = True+finishesMatch (HalfGoal _ _)     = True+finishesMatch (LostHalfGoal _ _) = True
+finishesMatch _                  = False
+
+-- Removes duplicated moves from the list using Map of edges, each move caries with it.
+-- Use it as follows: pruneMoves (Map.empty) ls [], where ls is list of moves to be pruned.
+pruneMoves :: Map.Map (Map.Map Int Bool) Bool -> [Move] -> [Move]
+pruneMoves _ []                                                                 = []
+pruneMoves t (l@(NextPass vs g fL fW True n i ms m _):ls)  | Map.member m t     = pruneMoves t ls
+                                                           | otherwise          = (l:(pruneMoves (Map.insert m True t) ls))
+pruneMoves t (l:ls)                                                             = (l:(pruneMoves t ls))
++-- For given list of moves it makes next step in BFS.+-- This function already presorts moves in the following way.+--   Moves that finish match are first.+--   Moves that don't finish match are afterwards and they are presoted on their length - longer first, shorter afterwards.
+nNextMove :: Bool -> [Move] -> [Move]
+nNextMove _ [] = []
+nNextMove d ls = newFinishingMatch ++ nNextMove d (((movesNotToPrune.newNotFinishedMoves) newMoves) ++ pruneMoves (Map.empty) ((movesPossiblyToPrune.newNotFinishedMoves) newMoves)) ++ newFinishedMoves
+               where newMoves = nextAllPasses d ls+                     newFinishingMatch = [m | m <- newMoves, finishesMatch m]                     
+                     newFinishedMoves = [m | m <- newMoves, isLastPass m]
+                     newNotFinishedMoves ls = [m | m <- ls, isNextPass m]
+#endif
+
++-- =============+-- MoveImproved2
+-- =============
+
+#ifndef MergePlies
+#ifdef MoveImproved2
+
+movesPossiblyToPrune :: [Move] -> [Move]
+movesPossiblyToPrune ls = [m | m <- ls, cycleInLastPass m]
+
+movesNotToPrune :: [Move] -> [Move]
+movesNotToPrune ls = [m | m <- ls, not $ cycleInLastPass m]
++-- Function recognizes cycle after each BFS step.+-- Cycle exists if the last visited vertex has been already visited within current move before.
+cycleInLastPass :: Move -> Bool
+cycleInLastPass (NextPass vs _ _ _ _ _ _ _ _ mV) = Map.findWithDefault 0 (head vs) mV > 1
++
+-- Very rough and ... order of moves
+-- Argumets: Direction towards (_,0) goal and list of moves.
+lessThan :: Bool -> Move -> Move -> Bool
+lessThan _ (LostGoal _) _ = True
+lessThan _ (LostHalfGoal _ _) _ = True
+lessThan True  (LastPass ((x,y):vs) _ _ _ _ _ _) (LastPass ((x',y'):vs') _ _ _ _ _ _) = y > y'
+lessThan False (LastPass ((x,y):vs) _ _ _ _ _ _) (LastPass ((x',y'):vs') _ _ _ _ _ _) = y < y'
+lessThan _ (LastPass _ _ _ _ _ _ _) _ = True
+lessThan _ (HalfGoal _ _) _ = True
+lessThan _ _ _ = False
+
+#else
+
+movesPossiblyToPrune :: [Move] -> [Move]
+movesPossiblyToPrune ls = ls
+
+movesNotToPrune :: [Move] -> [Move]
+movesNotToPrune ls = []
+
+#endif
+#endif
+
+
+-- ===================================================
+-- ==========+-- MergePlies
+-- ==========
+#ifdef MergePlies
+nextPass :: Bool -> Int -> Move -> [Move]
+nextPass d ply (NextPass vs g fL fW True n i [] m mV vs0)| even i && noPass      = [LostHalfGoal vs g]
+                                                         | noPass                = [HalfGoal vs g]
+                                                         | i > 0                 = [NextPass (v':vs) (rmEdge v v' g) fL fW (active v' g) (n+1) i [] (Map.insert (markEdge fW v v') True m) (Map.insertWith (+) v' 1 mV) vs0 |v' <- vertices v g]
+                                                         | otherwise             = [NextPass (v':vs) (rmEdge v v' g) fL fW (active v' g) (n+1) i [] (Map.insert (markEdge fW v v') True m) (Map.insertWith (+) v' 1 mV) (v':vs) |v' <- vertices v g]
+                                                 where v = head vs
+                                                       noPass = vertices v g == []
+nextPass d ply (NextPass vs g fL fW False n i [] _ _ vs0) | y == 0 && d || y == fL + 2 && not d  = [Goal vs]
+                                                          | y == 0 && not d || y == fL + 2 && d  = [LostGoal vs]
+                                                          | ply > i                              = [NextPass (v':vs) (rmEdge v v' g) fL fW (active v' g) (n+1) (i+1) [] (Map.insert (markEdge fW v v') True m) (Map.insertWith (+) v' 1 mV) vs0 |v' <- vertices v g]
+                                                          | otherwise                            = [LastPass vs0 g fL fW n i [] (head vs) ]
+                                          where y = snd v
+                                                v = head vs
+-- ==================================================================+-- The main function of this modul that returns full space of moves.
+-- ==================================================================
+-- d - if plays towards (_,0) goal
+-- v - initial vertex
+-- g - initial graph
+-- fL, fW - field size (length, width)
+-- i - depth number - first move has depth 0, answer depth 1, etc...
+-- ply - number of plies function has to explore. It finished when i > ply
+nextMove :: Bool -> Vertex -> Graph -> Int -> Int -> Int -> Int -> Move
+nextMove d v g fL fW i ply = Pass (nNextMove d ply [NextPass [v] g fL fW True 1 i [] (Map.empty) (Map.insert v 1 Map.empty) [v] ])
+-- ==================================================================
+
+nextAllPasses :: Bool -> Int -> [Move] -> [Move]
+nextAllPasses d ply ls = (concat $ map (nextPass d ply) ls)
+
+isNextPass :: Move -> Bool
+isNextPass (NextPass _ _ _ _ _ _ _ _ _ _ _) = True
+isNextPass _                                = False
+
+-- Removes duplicated moves from the list using Map of edges, each move caries with it.
+-- Use it as follows: pruneMoves (Map.empty) ls [], where ls is list of moves to be pruned.
+-- This function is not beautiful. It validates each move against Map of moves and updates this Map concurently.
+-- pruneMoves :: Map.Map (Map.Map Int Int) Bool -> [Move] -> [Move] -> [Move]
+-- pruneMoves _ []                                          os                      = os
+-- pruneMoves t (l@(NextPass vs g fL fW True n i ms m):ls)  os | Map.member m t     = pruneMoves t ls os
+--                                                            | otherwise          = pruneMoves (Map.insert m True t) ls (l:os)
+-- pruneMoves t (l:ls)                                      os                      = pruneMoves t ls (l:os)
+pruneMoves :: Map.Map (Map.Map Int Bool) Bool -> [Move] -> [Move]
+pruneMoves _ []                                                                   = []
+pruneMoves t (l@(NextPass vs g fL fW True n i ms m _ _):ls)  | Map.member m t     = pruneMoves t ls
+                                                             | otherwise          = (l:(pruneMoves (Map.insert m True t) ls))
+pruneMoves t (l:ls)                                                               = (l:(pruneMoves t ls))
+
+nNextMove :: Bool -> Int -> [Move] -> [Move]
+nNextMove _ _ [] = []
+nNextMove d ply ls = newFinishedMoves ++ nNextMove d ply (((movesNotToPrune.newNotFinishedMoves) newMoves) ++ pruneMoves (Map.empty) ((movesPossiblyToPrune.newNotFinishedMoves) newMoves))
+               where newMoves = nextAllPasses d ply ls
+                     newFinishedMoves = [m | m <- newMoves, not $ isNextPass m]
+                     newNotFinishedMoves ls = [m | m <- ls, isNextPass m]
+
+movesPossiblyToPrune :: [Move] -> [Move]
+movesPossiblyToPrune ls = [m | m <- ls, cycleInLastPass m]
+
+movesNotToPrune :: [Move] -> [Move]
+movesNotToPrune ls = [m | m <- ls, not $ cycleInLastPass m]
+
+cycleInLastPass :: Move -> Bool
+cycleInLastPass (NextPass vs _ _ _ _ _ _ _ _ mV _) = Map.findWithDefault 0 (head vs) mV > 1
+
+#endif
+
+ MyPrimitives.hs view
@@ -0,0 +1,75 @@+-- ==================================
+-- Module name: MyPrimitives
+-- Project: Foo
+-- Copyright (C) 2007  Bartosz Wójcik
+-- Created on: 01.10.2007
+-- Last update: 28.11.2007
+-- Version: %
+
+{-  This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+-}
+-- ==================================
+module MyPrimitives where
+
+import Graphics.UI.GLUT
+import Graphics.Rendering.OpenGL
+
+-- Displays given primitive with given list of 2D vertices.
+-- displayPoints :: (Vertex (Vertex2 b)) => [(b, b)] -> PrimitiveMode -> IO ()
+displayPoints points primitiveShape = do
+  renderPrimitive primitiveShape $ mapM_ (\(x,y)->vertex$Vertex2 x y) points
+--  flush
+
+-- =========================================================================
+-- Some functions creating and rendering circles in different configurations
+-- =========================================================================
+
+-- Returns list of vertices that construct circle.
+-- Input - radius of circle and number of points constructing circle.
+-- More points - circle is more precise, but function takes more time to construct it.
+circlePoints :: (Floating a, Enum a) => a -> a -> [(a, a)]
+circlePoints radius number
+ = [let alpha = 2*pi*i/number
+    in  (radius*(sin (alpha)) ,radius * (cos (alpha)))
+   |i <- [1,2..number]]
+
+-- Returns list of vertices that construct circle of given radius.
+-- 64 points constructing circle were taken from experiment result.
+circle :: (Floating a, Enum a) => a -> [(a, a)]
+circle radius = circlePoints radius 64
+
+-- Returns list of vertices that construct circle of given radius.
+-- 16 points constructing circle were taken from experiment result for small circles.
+circleSmall :: (Floating a, Enum a) => a -> [(a, a)]
+circleSmall radius = circlePoints radius 16
+
+-- Displays circle of given radius
+-- renderCircle :: (Floating a, Enum a, Vertex (Vertex2 a)) => a -> IO ()
+renderCircle r = displayPoints (circle r) LineLoop
+
+-- Displays filled circle of given radius
+fillCircle r = displayPoints (circle r) Polygon
+
+-- Displays filled small circle of given radius
+fillCircleSmall r = displayPoints (circleSmall r) Polygon
+
+-- Displays filled circle at given point
+-- filledCircleAt :: (Vertex (Vertex2 a), Enum a, Floating a) => GLfloat -> GLfloat -> a -> IO ()
+filledCircleAt x y r = do
+  translate$Vector3 x y (0::GLfloat)
+  fillCircle r
+
+-- Displays filled circle at given point
+-- filledCircleAtV :: (Vertex (Vertex2 a), Enum a, Floating a) => (GLfloat, GLfloat) -> a -> IO ()
+filledCircleAtV (x,y) r = filledCircleAt x y r
+ PlayFoo.hs view
@@ -0,0 +1,63 @@+-- ==================================
+-- Module name: PlayFoo
+-- Project: Foo
+-- Copyright (C) 2007  Bartosz Wójcik
+-- Created on: 01.10.2007
+-- Last update: 28.11.2007
+-- Version: %
+
+{-  This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+-}
+-- ==================================
+module Main where
+
+-- Simply user interface aksing for initial game parameters.
+
+import Court
+import Foo
+
+main = do
+     player1 <- selectPlayer1
+     alg1 <- selectAlgorithm player1
+     player2 <- selectPlayer2
+     alg2 <- selectAlgorithm player2
+     nbrOfGames <- selectNumerOfGames
+     court 8 8 (player1,toEnum alg1) (player2,toEnum alg2) nbrOfGames
+
+
+algDisp :: [String]
+algDisp = ["Select playing algorithm"] ++ map (\(a,n) -> (show a ++ " - " ++ show n)) (zip [GoAhead ..] [0..])
+
+algNum :: [String]
+algNum = map (\(a,n) -> (show n)) (zip [GoAhead ..] [0..])
+
+enterValue :: [String] -> [String] -> IO String
+enterValue possibleValues messages = do
+   mapM putStrLn messages
+   word <- getLine
+   if any (word ==) possibleValues
+      then return word
+      else enterValue possibleValues messages
+
+selectPlayer1 :: IO Bool
+selectPlayer1 = enterValue ["c","h"] ["Enter Player 1","c - computer","h - human"] >>= (\x -> return (x == "c"))
+selectPlayer2 :: IO Bool
+selectPlayer2 = enterValue ["c","h"] ["Enter Player 2","c - computer","h - human"] >>= (\x -> return (x == "c"))
+
+selectAlgorithm :: Bool -> IO Int
+selectAlgorithm True = enterValue algNum algDisp >>= (\x -> return (read x))
+selectAlgorithm False = return 0
+
+selectNumerOfGames :: IO Int
+selectNumerOfGames = enterValue (map show [1..12]) ["Enter number of games {1,..,12}"] >>= (\x -> return (read x)) 
+ Setup.lhs view
@@ -0,0 +1,3 @@+#!/usr/bin/env runhaskell+> import Distribution.Simple+> main = defaultMain
+ TestCourt.hs view
@@ -0,0 +1,129 @@+-- ==================================
+-- Module name: TestCourt
+-- Project: Foo
+-- Copyright (C) 2007  Bartosz Wójcik
+-- Created on: 01.10.2007
+-- Last update: 28.11.2007
+-- Version: %
+
+{-  This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+-}
+-- ==================================
+module Main where
+
+-- Test module.
+
+import Court
+import Foo
+import FooMove
+import FooField+import FooState
+import qualified Data.Map as Map
+import Data.List
+
+
+main = court 8 8 (True,PreventingOpponent2) (True,Watch2Ahead2) 1
+-- main = court 8 8 (True,PreventingOpponent) (True,Watch2Ahead) 1
+-- main = court 8 8 (True,PreventingOpponent) (True,CheckDist1PlyHash2) 1
+
+{-
+-- testField = Map.insert (5,4) (True,[(a,b) | a<-[4..6] , b<-[3..5],(a,b) /= (5,4)]) $ Map.insert (4,4) (True,[(a,b) | a<-[3..5] , b<-[3..5],(a,b) /= (4,4)]) $ Map.insert (5,5) (True,[(a,b) | a<-[4..6] , b<-[4..6],(a,b) /= (5,5)]) (field 8 8)
+testField =  myFold activateVertex (field 8 8) [(5,4),(4,4),(5,5),(6,5),(6,4)]
+testField2 =  myFold activateVertex (field 8 8) [(1,3),(1,4)]
+testField3 =  myFold activateVertex (field 8 8) [(4,4),(4,3),(4,2),(4,1)]
+
+myFold f v [] = v
+myFold f v (l:ls) = myFold f (f v l) ls
+
+activateVertex :: Graph -> Vertex -> Graph
+activateVertex graph (x,y) = Map.insert (x,y) (True,[(a,b) | a<-[(x-1)..(x+1)] , b<-[(y-1)..(y+1)],(a,b) /= (x,y)]) graph
+
+size = sizeMove 0 $ nextMove True (4,5) testField 8 8 0
+size1  = sizeMove 0 $ nextMove True (4,5) (field 8 8) 8 8 0
+
+move2Vs (LastPass vs _ _ _ _ _ _) = vs
+
+testMove  = nextMove True (4,5) testField 8 8 0
+testMoveX = nextMoveX True (4,5) testField 8 8 0
+testMove3X = nextMoveX True (4,5) testField3 8 8 0
+testMove3 = nextMove True (4,5) testField3 8 8 0
+testMove2X = nextMoveX True (1,4) testField2 8 8 0
+testMove2 = nextMove True (1,4) testField2 8 8 0
+testMove1 = nextMove True (4,5) (field 8 8) 8 8 0
+
+listMove (Pass m) = map move2Vs m
+
+
+
+-- !!
+
+nextPassX :: Bool -> Move -> [Move]
+nextPassX d (NextPass vs g fL fW True n i [] m mV)| even i && noPass      = [LostHalfGoal vs g]
+                                                 | noPass                = [HalfGoal vs g]
+                                                 | otherwise             = [NextPass (v':vs) (rmEdge v v' g) fL fW (active v' g) (n+1) i [] (Map.insert (markEdge fW v v') True m) (Map.insertWith (+) v' 1 mV) |v' <- vertices v g] -- Map.insertWith (+)
+                                                 where v = head vs
+                                                       noPass = vertices v g == []
+nextPassX d (NextPass vs g fL fW False n i [] _ _) | y == 0 && d || y == fL + 2 && not d  = [Goal vs]
+                                                  | y == 0 && not d || y == fL + 2 && d  = [LostGoal vs]
+                                                  | otherwise                            = [LastPass vs g fL fW n i [nextMoveX d v g fL fW (i+1)]]
+                                          where y = snd v
+                                                v = head vs
+
+nextMoveX :: Bool -> Vertex -> Graph -> Int -> Int -> Int -> Move
+nextMoveX d v g fL fW i = Pass (nNextMoveX d [NextPass [v] g fL fW True 1 i [] (Map.empty) (Map.insert v 1 Map.empty)])
+
+nextAllPassesX :: Bool -> [Move] -> [Move]
+nextAllPassesX d ls = (concat $ map (nextPassX d) ls)
+
+
+nNextMoveX :: Bool -> [Move] -> [Move]
+nNextMoveX _ [] = []
+nNextMoveX d ls = newFinishedMoves ++ nNextMoveX d (movesNotToPruneX newNotFinishedMoves ++ pruneMoves (Map.empty) (movesPossiblyToPruneX newNotFinishedMoves))
+               where newMoves = nextAllPassesX d ls
+                     newFinishedMoves = [m | m <- newMoves, not $ isNextPass m]
+                     newNotFinishedMoves = [m | m <- newMoves, isNextPass m]
+
+movesPossiblyToPruneX :: [Move] -> [Move]
+movesPossiblyToPruneX ls = [m | m <- ls, cycleInLastPassX m]
+
+movesNotToPruneX :: [Move] -> [Move]
+movesNotToPruneX ls = [m | m <- ls, not $ cycleInLastPassX m]
+
+cycleInLastPassX :: Move -> Bool
+cycleInLastPassX (NextPass vs _ _ _ _ _ _ _ _ mV) = Map.findWithDefault 0 (head vs) mV > 1
+-}
+
+gr = field 8 8
+
+tI0 = [(3,0),(4,0),(5,0)]
+
+tI1 = inactVertConnectedTo tI0 [] gr
+tI2 = inactVertConnectedTo tI1 tI0 gr
+tI3 = inactVertConnectedTo tI2 (tI0 ++ tI1) gr
+tI4 = inactVertConnectedTo tI3 (tI0 ++ tI1 ++ tI2) gr
+
+tI21 = nub $ fst $ tI21X
+tI21X = inactVertConnectedTo2 tI0 gr
+tI22 = nub $ fst $ tI22X
+tI22X = inactVertConnectedTo2 tI21 (snd $ tI21X)
+tI23 = nub $ fst $ tI23X
+tI23X = inactVertConnectedTo2 tI22 (snd $ tI22X)
+tI24 = nub $ fst $ tI24X
+tI24X = inactVertConnectedTo2 tI23 (snd $ tI23X)
+
tD1 = distanceMap 1 False 8 8 gr+tD2 = distanceMap 2 False 8 8 gr+tD3 = distanceMap 3 False 8 8 gr+tD n = distanceMap n False 8 8 gr+dOfV v = distanceOfVertex v 3 (Map.unions [snd tD3,snd tD2,snd tD1]) False 8 8 gr+
+ copying.txt view
@@ -0,0 +1,621 @@+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+ foo.cabal view
@@ -0,0 +1,33 @@+name:               foo+version:            1.0+homepage:           http://sourceforge.net/projects/fooengine/?abmode=1+synopsis:           Paper soccer, an OpenGL game.+description:+    Foo (abbreviation from football) is a playing machine of Paper Soccer, a+    pencil and paper game for two players, described in WIKIPEDIA. Written+    in Haskell, contains also simply interface using HOpenGL library.+    Provides bunch of playing algorithms.+category:           Game+license:            GPL+license-file:       copying.txt+author:             Bartosz Wójcik+maintainer:         none+extra-source-files: fooDocu.tex+cabal-version:      >= 1.2+build-type:         Simple++flag small_base+    description: Choose the new smaller, split-up base package.++executable foo+    main-is:            PlayFoo.hs+    other-modules:      Court+                        Foo+                        FooField+                        FooMove+                        MyPrimitives+                        TestCourt++    extensions:         CPP+    ghc-options:        -O2 -funbox-strict-fields+    build-depends:      base, OpenGL, GLUT, haskell98, containers
+ fooDocu.tex view
@@ -0,0 +1,133 @@+\documentclass[a4paper]{article}
+\usepackage[cp1250]{inputenc}
+\title{Foo Project Documentation}
+\author{Bartosz Wójcik}
+\date{08.04.2008}
+\begin{document}
+\maketitle
+\begin{abstract}
+Project {\tt Foo} is implementation of a playing machine for Paper Soccer, a pencil and paper game for two players, described in WIKIPEDIA. Written in Haskell, contains also simply user interface using HOpenGL library. The project is focused on the engine, more precisely --- on the theoretical side of the solution.
+{\tt Foo} delivers two solutions: a game, where end user can play against machine, and stand alone playing machine that needs an interface to be used further.
+\end {abstract}
+
+\section{Objective}
+This document contains game description, user guide and theoretical details of the implementation.
+
+\section{Game description}
+The game has been described in WIKIPEDIA under 'Paper Soccer'. Please refer to it in order to learn rules {\tt http://en.wikipedia.org/wiki/Paper\_Soccer}.
+
+Rules of this game can be completed by simply odd-on. Player who does the move that finishes game due to no further available move left, loses only half a point.
+
+Size of the court can be defined almost without limits. Although playing machine supports any field size, $8 \times 8$ one has been chosen for end user game.
+
+\section{How can I install Foo on my PC?}
+Follow below instructions.
+
+\subsection{Install GHC}
+First install Haskell compiler. I've used GHC only, so there is no guarantee that solution work under other Haskell impementations. GHC you can find here: {\tt http://www.haskell.org/ghc/}. Follow installing instructions there. The newest installation contains required GLUT and OpenGL Libraries.
+
+\subsection{Compile sources}
+Download sources to separate directory and compile them there using following command {\tt ghc --make -package GLUT PlayFoo.hs -cpp -o PlayFoo}. This works assuming you have direct acess to GHC compiler.
+
+\subsection{Shortcut for Windows}
+Widnows users can download binary package. It has to be decompressed in any place and used as it is.
+
+\section {User guide}
+Just run executable you've downloaded or compiled. Then choose who plays against whom in serie of questions. Then play or observe how two algorithms play one against another.
+You play by selecting move with mouse.
+Playing machine displays in console number of avaiable moves for each its turn.
+Once current game has finished you have to click on the game window to get next one game or quit.
+
+Because single game lasts relatively short, it is usual that one plays couple games in row. Results of single games are cumulated and total result is considered as match result.
+
+\subsection {Playing Machines}
+
+There are following algorithms available.
+\begin{verbatim}
+GoAhead - 0
+GoBackWatchOpponent - 1
+GoAheadWatchOpponent - 2
+PreventingOpponent40 - 3
+PreventingOpponent50 - 4
+Watch2Ahead - 5
+Watch3Ahead - 6
+\end{verbatim}
+
+They are presented in the ascending power order. More powerful algoritm, longer you need to wait for the response. I've tested all of them on PC Intel Core2 Duo 2,2GHz 2GB RAM and in this configuration I have to disrecommend you using the last, 6th one. On the other hand on the Intel Pentum 1,8Ghz 256MB RAM the 5th algorithm was still playable.
+
+
+\section{User interface}
+User interface is very simply. It renders filed, nodes of net (vertices), and done moves. It also highlights the possible passes during 
+manipulating with mouse, and shows current result and names of players.
+
+\section {Technical details regarding the game}
+
+There are couple important details that make this game amazingly not easy to put into simply playing machine. I'll describe them in the next paragraphs.
+
+\subsection {Space of Moves}
+For Playing Machines the size of space of moves of the game is basic problem to cope with. Bigger space is, cannot algorithms process many plies and are weaker. Bigger space is, more advanced move prunes methods have to be implemented. What is space of the moves of {\tt Foo}?
+It is very unstable. In first move it contains only $8$ possiblities. Usually it varies between $10$ to $100$ moves. Sometimes (once or twice times during the single game) it contains even to $1000$ possibilities. 
+The biggest space of moves I've seen was about $5000$ moves. This all for field $8 \times 8$. Imagine then that you want to build powerfull playing machine scaning $5$ plies of moves. Such a machine will have to cope often with about than $100^5$ which is $10^{10}$ moves. Besides of some cases (once or twice in single game) where this number will be bigger.
+There is also additional difficulty. If one ply contains many moves, lot of them (meaningfull percent) will lead to similar big or bigger next ply. One thing more --- more plyes are scaned, more moves will lead to huge next ply.
+This is unpleasant point of {\tt Foo} --- space of moves sometimes explodes.
+
+\subsection {Number of Moves}
+Players play until game is over. How many moves will they do? The answer is easy: The initial field's size is limitation of number of moves. Each move finishes in one of not yet achieved nodes of field. So for field $8 \times 8$ we have limit of 50 moves. Not many -- easy for playing machine.
+
+\subsection {Game's goal}
+Easier is to describe the goal of the game, easier is to implement the move selection. {\tt Foo} has very easy to implement goal: score a goal, don't let you score a goal, do not finish move in vegetables. The easy algorithm "force ahead to opponent's goal" is also quite powerfull. Still there is a little difficulty. There are some situations where "brutal force" is not a good solution. This is easy noticably by human playes, but "brutal force" would need to scan 6 or more plies in order to find this out. Exists then better solution?
+For sure, I'll desribe one attempt later.
+
+\subsection {Game's rules}
+Difficult, sophisticated rules lead usually to complex solutions and bring problems. {\tt Foo} doesn't bring here problems, besides one. In many situation it is possible to create same move in many different ways. This leads to increased number of moves. Percentage of such moves is bigger for plies where there are many moves already. Therefore this can kill your solution if you won't recognize and prune duplicates.
+
+\section{Technical details regarding implementation}
+
+I had pleasure to cope with problems I've described above. Eventually I managed to create hardly acceptable result, at least from expectations' point of view. I wanted to create playing machine that can beat myself. It is not the case.
+
+\subsection{Recognition of duplicates}
+In order to find duplicates I search space of moves using Breadth-First Search method. Each time new added edge to the current move constructs a cycle within the move, there is posibility to get same move in 2nd way, adding edges of cycle in opposite order. In this way duplicates are recognized and pruned.
+What are consequences of using BFS? For example the Alpha-Beta pruning is not possible to use.
+
+\subsection{Space of Moves}
+Finally this problem became the most difficult one I had to fight against. Working in pure functional language I was able to define number of plies to be scaned, but not the number of moves I want my solution scans in total withing one turn. As number of moves vary from few to thousends, this difficulty is capital and therefore I find functional solution here not well fitting.
+
+Finally I've found method to limit number of moves within each ply separatelly. This limitation is very drastic and still brings acceptable solution. In details I've limited algorithms as follows.
+
+\begin{itemize}
+\item {\tt GoAhead} --- $1$ ply, $1000$ moves.
+\item {\tt GoBackWatchOpponent} --- $1 {1\over 2}$ plies, limit $1000$ moves a ply.
+\item {\tt GoAheadWatchOpponent} --- $1 {1\over 2}$ plies, limit $1000$ moves a ply.
+\item {\tt PreventingOpponent40} --- $2$ plies, limit $40$ moves a ply --- $p \times 1600$ scaned moves.
+\item {\tt PreventingOpponent50} --- $2$ plies, limit $50$ moves a ply --- $p \times 2500$ scaned moves.
+\item {\tt Watch2Ahead} --- $3$ plies, limit $30$ moves a ply --- $p \times 27000$ scaned moves.
+\item {\tt Watch3Ahead} --- $4$ plies, limit $18$ moves a ply --- $p \times 105000$ scaned moves.
+\end{itemize}
+
+where $p$ is average number of moves really existed in the ply divide by ply limt of the algorithm. So for {\tt Watch3Ahead} assuming average $100$ moves a ply, we get ${100 \over 18} \times 105000 \approx 60*10^5$ scaned moves.
+They are limits only! If you remember the number of moves per ply I've mentioned above, you'll notice that for last 2 algorithms limits are almost always reached.
+Do you think that $60 \times 10^5$ scaned moves is not much? I think so too. Why then is the solution so slow? Bad implementation?
+I've checked how are distributed costs of process. The most time cosuming process is graph update and manipulation on vertices within graph. Would this be done ineffectively?
+The answer is: yes. And the explanation is: this is overhead of functional language.
+
+Let me explain this. 
+There are done two manipulations on graph: search and remove. How much they cost? Depending on data strucutre. Indexed arrays should give costs O(1). Binary trees --- O(log n), where n is number of elements in tree. But, there is a problem here --- in functional language arrays cannot be modified, therefore delete of element from array leads to copying the whole array --- costs O(n)! Because of this I had to use binary trees as a solution. The fast solution in descriptive language would need to contain fast graph manipulation functions.
+
+And the last thing. How did I manage to limit number of evaluated moves within one ply? The solution is very easy but I don't spoil you pleasure of working on this. If you want to know, you can find this in the sources.
+
+\subsection {Game's goal}
+
+I've mentioned above, that "brutal force" solution brings some difficulties. Please notice that this solution prefers moves that finish close to the opponent's goal. "Close" in meaning of number of passes. But actually moves contain different number of passes, so the better idea would be to consider distance from goal in meaning of moves.
+
+I've spent a lot of time implementing such solution but failed. My solutions worked too slow. Again the reason was functional language.
+
+It's much more difficult to calculate distance from any two vertices in meaning of moves than in meaning of passes. Therefore it is necessary to store calculated values and update them only when necessary. This leads to sophisticated data model and complicated rules of modification of state of field.
+Such a solution gives potentialy many possibilities of tuning of algoritms. There are five meaningful factors algorithm can base on.
+\begin{itemize}
+\item Distance from opponent's goal.
+\item Distance from own goal (these two are not complementary!).
+\item Number of vertices where next move can be finished and which are in distance $1$ from opponents goal.
+\item Number of vertices where next move can be finished and which are in distance $1$ from own goal.
+\item Goals can be not accessible.
+\end{itemize}
+\end{document}
+ readme.txt view
@@ -0,0 +1,13 @@+1. The game has been described in WIKIPEDIA under 'Paper Soccer'. Please refer to there in order to learn rules. http://en.wikipedia.org/wiki/Paper_Soccer
+Rules of this game can be completed by simply rule. Player who does the move that finishes because there is no further available move left, loses only half a point.
+Size of the court can be defined almost without limits, but as first option size $8 \times 8$ has been chosen.
+
+2. Install Foo
+
+2.1 Install GHC
+First install Haskell compiler. I've used GHC only. You can find it here: http://www.haskell.org/ghc/. Follow installing instructions there. The newest installation contains required GLUT and OpenGL Libraries.
+
+2.2 Compile sources
+Download sources to separate directory and compile there using following command 
+ghc --make -package GLUT PlayFoo.hs -O -fvia-C -cpp -o PlayFoo 
+This works assuming you have direct acess to GHC compiler.