summaryrefslogtreecommitdiffstats
path: root/HTanks.hs
blob: d5536b2c84e74c751f3dfaab70598543b7d3a54f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
{-# LANGUAGE PatternGuards #-}

import Game
import Level
import Render
import Tank

import GLDriver
import GLX

import Control.Concurrent (threadDelay)
import Control.Monad.State
import Data.Maybe
import System.Time


main :: IO ()
main = do
  gl <- initGL glxDriver
  
  let gameState = GameState {level = testLevel, tanks = [Tank 0.5 0.5 0]}
  
  when (initialized gl) $ do
         time <- getClockTime
         
         setup 800 600
         runGame gameState $ mainLoop gl time
         
         deinitGL gl

minFrameTime :: Integer
minFrameTime = 10000

mainLoop :: Driver a => a -> ClockTime -> Game ()
mainLoop gl time = do
  run <- liftIO $ handleEvents gl
  
  render
  
  liftIO $ swapBuffers gl
  
  newTime <- liftIO getClockTime
  let td = timeDiff newTime time
  when (td < minFrameTime) $
       liftIO $ threadDelay $ fromIntegral (minFrameTime - td)
  
  newTime <- liftIO getClockTime
  
  --liftIO $ print $ timeDiff newTime time
  
  when run $ mainLoop gl newTime


timeDiff :: ClockTime -> ClockTime -> Integer
timeDiff (TOD s1 ps1) (TOD s2 ps2) = (s1-s2)*1000000 + (ps1-ps2)`div`1000000


handleEvents :: Driver a => a -> IO Bool
handleEvents gl = do
  event <- nextEvent gl
  if (isJust event)
      then
          handleEvent $ fromJust event
      else
          return True

handleEvent :: SomeEvent -> IO Bool
handleEvent ev
    | Just QuitEvent <- fromEvent ev = return False
    | Just (ResizeEvent w h) <- fromEvent ev = do
                                resize w h
                                return True
    | otherwise                      = return True