aboutsummaryrefslogtreecommitdiff
path: root/Demos/Pong/Main.hs
diff options
context:
space:
mode:
Diffstat (limited to 'Demos/Pong/Main.hs')
-rw-r--r--Demos/Pong/Main.hs83
1 files changed, 83 insertions, 0 deletions
diff --git a/Demos/Pong/Main.hs b/Demos/Pong/Main.hs
new file mode 100644
index 0000000..4dbe0a3
--- /dev/null
+++ b/Demos/Pong/Main.hs
@@ -0,0 +1,83 @@
1{-# LANGUAGE ImportQualifiedPost #-}
2
3module Main where
4
5import Data.Maybe (mapMaybe)
6import Graphics.Rendering.OpenGL.GL (($=))
7import Graphics.Rendering.OpenGL.GL qualified as GL
8import Pong
9import Spear.App
10import Spear.Game
11import Spear.Math.AABB
12import Spear.Math.Spatial2
13import Spear.Math.Vector
14import Spear.Window
15
16data GameState = GameState
17 { window :: Window,
18 world :: [GameObject]
19 }
20
21main =
22 withWindow (900, 600) (2, 0) (Just "Pong") initGame $
23 loop step
24
25initGame :: Window -> Game () GameState
26initGame window = do
27 gameIO $ do
28 GL.clearColor $= GL.Color4 0.7 0.5 0.7 1.0
29 GL.matrixMode $= GL.Modelview 0
30 GL.loadIdentity
31 return $ GameState window newWorld
32
33step :: Elapsed -> Dt -> [InputEvent] -> Game GameState Bool
34step elapsed dt inputEvents = do
35 gs <- getGameState
36 gameIO . process $ inputEvents
37 let events = translate inputEvents
38 modifyGameState $ \gs ->
39 gs
40 { world = stepWorld elapsed dt events (world gs)
41 }
42 getGameState >>= \gs -> gameIO . render $ world gs
43 return (not $ exitRequested inputEvents)
44
45render world = do
46 GL.clear [GL.ColorBuffer]
47 mapM_ renderGO world
48
49renderGO :: GameObject -> IO ()
50renderGO go = do
51 let (AABB2 (Vector2 xmin' ymin') (Vector2 xmax' ymax')) = aabb go
52 (Vector2 xcenter ycenter) = pos go
53 (xmin, ymin, xmax, ymax) = (f2d xmin', f2d ymin', f2d xmax', f2d ymax')
54 GL.preservingMatrix $ do
55 GL.translate (GL.Vector3 (f2d xcenter) (f2d ycenter) 0)
56 GL.renderPrimitive (GL.TriangleStrip) $ do
57 GL.vertex (GL.Vertex2 xmin ymax)
58 GL.vertex (GL.Vertex2 xmin ymin)
59 GL.vertex (GL.Vertex2 xmax ymax)
60 GL.vertex (GL.Vertex2 xmax ymin)
61
62process = mapM_ procEvent
63
64procEvent (Resize w h) = do
65 GL.viewport $= (GL.Position 0 0, GL.Size (fromIntegral w) (fromIntegral h))
66 GL.matrixMode $= GL.Projection
67 GL.loadIdentity
68 GL.ortho 0 1 0 1 (-1) 1
69 GL.matrixMode $= GL.Modelview 0
70procEvent _ = return ()
71
72translate = mapMaybe translate'
73
74translate' (KeyDown KEY_LEFT) = Just MoveLeft
75translate' (KeyDown KEY_RIGHT) = Just MoveRight
76translate' (KeyUp KEY_LEFT) = Just StopLeft
77translate' (KeyUp KEY_RIGHT) = Just StopRight
78translate' _ = Nothing
79
80exitRequested = any (== (KeyDown KEY_ESC))
81
82f2d :: Float -> GL.GLdouble
83f2d = realToFrac