You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.4 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. {-# LANGUAGE ExistentialQuantification #-}
  2. {-# LANGUAGE TemplateHaskell #-}
  3. {-# OPTIONS -Wall #-}
  4. module StrategyManager where
  5. import Control.DeepSeq
  6. import System.Random(StdGen)
  7. import Datatypes.Game(Game,Command)
  8. import Control.DeepSeq (NFData(..))
  9. type Score = Int
  10. type StrategyIdx = Int
  11. type FinishedGame = ([Command], Score, StrategyIdx)
  12. type GameComputation = [StrategyWrapper]
  13. data StrategyWrapper = forall a. (Strategy a) => MkStrategyWrapper a
  14. | FinishedGame ([Command], Int)
  15. instance NFData StrategyWrapper where
  16. rnf (MkStrategyWrapper a) = seq a ()
  17. rnf (FinishedGame b) = seq b ()
  18. initWrapper :: Strategy a => a -> StrategyWrapper
  19. initWrapper a = getbest a `deepseq` (MkStrategyWrapper $! a)
  20. class (NFData a) => Strategy a where
  21. initst :: Game -> StdGen -> [[Command]] -> a
  22. advance :: a -> Either a ([Command], Int)
  23. getbest :: a -> ([Command], Int)
  24. advanceWrapper :: StrategyWrapper -> StrategyWrapper
  25. advanceWrapper (FinishedGame result) = (FinishedGame result)
  26. advanceWrapper (MkStrategyWrapper strategy) = wrapResult $ advance strategy
  27. where
  28. wrapResult (Left nextStrategy) = MkStrategyWrapper nextStrategy
  29. wrapResult (Right result) = FinishedGame result
  30. finishedWrapper :: StrategyWrapper -> Bool
  31. finishedWrapper (FinishedGame _) = True
  32. finishedWrapper _ = False
  33. getbestWrapper :: StrategyWrapper -> ([Command], Int)
  34. getbestWrapper (FinishedGame result) = result
  35. getbestWrapper (MkStrategyWrapper st) = getbest st
  36. --- puo essere parallelizzato ---
  37. finishedGameComputation :: GameComputation -> Bool
  38. finishedGameComputation gc = and $ map finishedWrapper gc
  39. -- Ritorna i comandi con i punti piu l indice della strategia
  40. getBestGameComputation :: GameComputation -> FinishedGame
  41. getBestGameComputation gameComputation = bestGame
  42. where
  43. resultsFromAlgorithms = (map getbestWrapper gameComputation)
  44. algoIdxs = take (length resultsFromAlgorithms) [ i | i <- [0..]]
  45. bestGames = zipWith (\(a,b) c -> (a,b,c)) resultsFromAlgorithms algoIdxs
  46. bestGame = foldl findBest ([], 0, 0) bestGames
  47. findBest best nextBest = if ((bestScore best) > (bestScore nextBest))
  48. then best
  49. else nextBest
  50. bestScore (_, score, _) = score
  51. advanceGameComputation :: GameComputation -> GameComputation
  52. advanceGameComputation gc = map advanceWrapper gc