Featured image of post MDN ブロックくずしゲームでウェブゲーム開発に入門してみた。その7

MDN ブロックくずしゲームでウェブゲーム開発に入門してみた。その7

「衝突検出」編

このプログラムはGitHub Pagesで公開しています。

MDN web docs にある 「そのままのJavaScriptを使ったブロックくずしゲーム」 の7番目のステップ。

lesson07

1
2
3
aki:~/breakout$ cp -r lesson06/ lesson07
aki:~/breakout$ cd lesson07/
aki:~/breakout/lesson07$

lesson06 をコピーした lesson07 を用意して続きを始める。

今回は 衝突検出

衝突検出関数

最初の第一歩として、毎フレーム描画されるたびに全てのブロックを通してループし、ひとつひとつのブロックの位置をボールの座標と比較する衝突検出関数を作成しましょう。コードがより読みやすくなるように、衝突検出のループの中でブロックオブジェクトを保存する変数bを定義します。

1
2
3
4
5
6
7
8
function collisionDetection() {
    for(var c=0; c<brickColumnCount; c++) {
        for(var r=0; r<brickRowCount; r++) {
            var b = bricks[c][r];
            // いろいろな計算
        }
    }
}

もしボールの中央がブロックの1つの座標の内部だったらボールの向きを変えます。ボールの中央がブロックの内部にあるためには次の4つの命題が全て真でなければなりません。

  • ボールのx座標がブロックのx座標より大きい
  • ボールのx座標がブロックのx座標とその幅の和より小さい
  • ボールのy座標がブロックのy座標より大きい
  • ボールのy座標がブロックのy座標とその高さの和より小さい

コードに書き下ろしてみましょう。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function collisionDetection() {
    for(var c=0; c<brickColumnCount; c++) {
        for(var r=0; r<brickRowCount; r++) {
            var b = bricks[c][r];
            if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) {
                dy = -dy;
            }
        }
    }
}

上記のブロックを自分のコードのkeyUpHandler()関数の下に追加してください。

これでどうだ。

  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
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
module Breakout (component) where

import Prelude
import CSS (background, block, display, margin, marginBottom, marginLeft, marginRight, marginTop, padding, px, rgb)
import CSS.Common (auto)
import Control.Monad.Rec.Class (forever)
import Control.Monad.ST (for)
import Control.Monad.ST as ST
import Control.Monad.ST.Ref as STRef
import Data.Foldable (any)
import Data.Int as Int
import Data.Map (Map)
import Data.Map as Map
import Data.Maybe (Maybe(..))
import Data.Time.Duration (Milliseconds(..))
import Data.Traversable (for_)
import Data.Tuple (Tuple(..))
import Effect (Effect)
import Effect.Aff as Aff
import Effect.Aff.Class (class MonadAff)
import Graphics.Canvas (CanvasElement, Dimensions)
import Graphics.Canvas as Canvas
import Halogen (SubscriptionId)
import Halogen as H
import Halogen.HTML as HH
import Halogen.HTML.CSS (style)
import Halogen.HTML.Properties as HP
import Halogen.Query.Event (eventListener)
import Halogen.Subscription as HS
import Math as Math
import Web.Event.Event as E
import Web.HTML (window)
import Web.HTML.HTMLDocument as HTMLDocument
import Web.HTML.Location as Location
import Web.HTML.Window as Window
import Web.UIEvent.KeyboardEvent as KE
import Web.UIEvent.KeyboardEvent.EventTypes as KET

canvasId :: String
canvasId = "myCanvas"

paddleHeight = 10.0 :: Number

paddleWidth = 75.0 :: Number

ballRadius = 10.0 :: Number

brickRowCount = 3 :: Int

brickColumnCount = 5 :: Int

brickWidth = 75 :: Int

brickHeight = 20 :: Int

brickPadding = 10 :: Int

brickOffsetTop = 30 :: Int

brickOffsetLeft = 30 :: Int

newtype BricksIndex
  = BricksIndex { row :: Int, column :: Int }

derive newtype instance showBricksIndex :: Show BricksIndex

derive newtype instance ordBricksIndex :: Ord BricksIndex

derive newtype instance eqBricksIndex :: Eq BricksIndex

newtype Brick
  = Brick { x :: Number, y :: Number }

derive newtype instance showBrick :: Show Brick

type Bricks
  = Map BricksIndex Brick

type Dataset
  = { x :: Number
    , y :: Number
    , dx :: Number
    , dy :: Number
    , paddleX :: Number
    , leftPressed :: Boolean
    , rightPressed :: Boolean
    , bricks :: Bricks
    }

type State
  = { maybeCanvas :: Maybe CanvasElement
    , maybeTimer :: Maybe SubscriptionId
    , dataset :: Dataset
    }

data Action
  = Initialize
  | Tick
  | HandleKeyDown KE.KeyboardEvent
  | HandleKeyUp KE.KeyboardEvent

component :: forall query input output m. MonadAff m => H.Component query input output m
component =
  H.mkComponent
    { initialState
    , render
    , eval:
        H.mkEval
          $ H.defaultEval
              { handleAction = handleAction
              , initialize = Just Initialize
              }
    }

initialState :: forall i. i -> State
initialState _ =
  { maybeCanvas: Nothing
  , maybeTimer: Nothing
  , dataset:
      { x: 0.0
      , y: 0.0
      , dx: 0.0
      , dy: 0.0
      , paddleX: 0.0
      , leftPressed: false
      , rightPressed: false
      , bricks: Map.empty
      }
  }

render :: forall m. State -> H.ComponentHTML Action () m
render state =
  HH.main
    [ style do
        margin (px 0.0) (px 0.0) (px 0.0) (px 0.0)
        padding (px 0.0) (px 0.0) (px 0.0) (px 0.0)
    ]
    [ HH.canvas
        [ style do
            background (rgb 238 238 238)
            display block
            marginTop (px 0.0)
            marginRight auto
            marginBottom (px 0.0)
            marginLeft auto
        , HP.id canvasId
        , HP.width 480
        , HP.height 320
        ]
    , HH.text $ show state.dataset
    ]

handleAction :: forall output m. MonadAff m => Action -> H.HalogenM State Action () output m Unit
handleAction = case _ of
  Initialize -> do
    -- keyboard event
    document <- H.liftEffect $ Window.document =<< window
    H.subscribe' \_ ->
      eventListener
        KET.keydown
        (HTMLDocument.toEventTarget document)
        (map HandleKeyDown <<< KE.fromEvent)
    H.subscribe' \_ ->
      eventListener
        KET.keyup
        (HTMLDocument.toEventTarget document)
        (map HandleKeyUp <<< KE.fromEvent)
    -- timer
    sid <- H.subscribe =<< timer Tick
    --
    init <- H.liftEffect initialize
    H.put init { maybeTimer = Just sid }
  Tick -> do
    (state :: State) <- H.get
    case { a: state.maybeCanvas, b: state.maybeTimer } of
      { a: Just canvas, b: Just timerSubscriptionId } -> do
        ret <- H.liftEffect $ draw canvas state.dataset
        if ret.gameover then do
          H.liftEffect $ Window.alert "GAME OVER" =<< window
          H.liftEffect $ Location.reload =<< Window.location =<< window
          H.unsubscribe timerSubscriptionId
        else
          H.modify_ \st -> st { dataset = ret.nextDataset }
      _ -> pure unit
  HandleKeyDown ev
    | KE.key ev == "Right" || KE.key ev == "ArrowRight" -> do
      H.liftEffect $ E.preventDefault (KE.toEvent ev)
      H.modify_ \st -> st { dataset { rightPressed = true } }
    | KE.key ev == "Left" || KE.key ev == "ArrowLeft" -> do
      H.liftEffect $ E.preventDefault (KE.toEvent ev)
      H.modify_ \st -> st { dataset { leftPressed = true } }
    | otherwise -> pure unit
  HandleKeyUp ev
    | KE.key ev == "Right" || KE.key ev == "ArrowRight" -> do
      H.liftEffect $ E.preventDefault (KE.toEvent ev)
      H.modify_ \st -> st { dataset { rightPressed = false } }
    | KE.key ev == "Left" || KE.key ev == "ArrowLeft" -> do
      H.liftEffect $ E.preventDefault (KE.toEvent ev)
      H.modify_ \st -> st { dataset { leftPressed = false } }
    | otherwise -> pure unit
  where
  initialize :: Effect State
  initialize =
    Canvas.getCanvasElementById canvasId
      >>= case _ of
          Nothing -> pure $ initialState unit
          Just canvas -> do
            dim <- Canvas.getCanvasDimensions canvas
            pure
              { maybeCanvas: Just canvas
              , maybeTimer: Nothing
              , dataset:
                  { x: dim.width / 2.0
                  , y: dim.height - 30.0
                  , dx: 2.0
                  , dy: (-2.0)
                  , paddleX: (dim.width - paddleWidth) / 2.0
                  , leftPressed: false
                  , rightPressed: false
                  , bricks: Map.empty
                  }
              }

draw :: CanvasElement -> Dataset -> Effect { nextDataset :: Dataset, gameover :: Boolean }
draw canvas dataset = do
  dim <- H.liftEffect $ Canvas.getCanvasDimensions canvas
  ctx <- Canvas.getContext2D canvas
  --
  Canvas.clearRect ctx { x: 0.0, y: 0.0, width: dim.width, height: dim.height }
  drawBall
  drawPaddle dim
  bricks <- pure $ coordinateBricks dataset.bricks
  drawBricks bricks
  pure
    let
      collisioned = collisionDetection { x: dataset.x, y: dataset.y } bricks

      dy' = if collisioned then (-dataset.dy) else dataset.dy
    in
      nextDataset dataset { dy = dy', bricks = bricks } dim
  where
  drawBall :: Effect Unit
  drawBall = do
    ctx <- Canvas.getContext2D canvas
    --
    Canvas.beginPath ctx
    Canvas.arc ctx
      { x: dataset.x
      , y: dataset.y
      , radius: ballRadius
      , start: 0.0
      , end: Math.pi * 2.0
      }
    Canvas.setFillStyle ctx "#0095DD"
    Canvas.fill ctx
    Canvas.closePath ctx

  drawPaddle :: Dimensions -> Effect Unit
  drawPaddle { height: height } = do
    ctx <- Canvas.getContext2D canvas
    --
    Canvas.beginPath ctx
    Canvas.rect ctx
      { x: dataset.paddleX
      , y: height - paddleHeight
      , width: paddleWidth
      , height: paddleHeight
      }
    Canvas.setFillStyle ctx "#0095DD"
    Canvas.fill ctx
    Canvas.closePath ctx

  drawBricks :: Bricks -> Effect Unit
  drawBricks bricks =
    for_ bricks \(Brick brick) -> do
      ctx <- Canvas.getContext2D canvas
      Canvas.beginPath ctx
      Canvas.rect ctx
        { x: brick.x
        , y: brick.y
        , width: Int.toNumber brickWidth
        , height: Int.toNumber brickHeight
        }
      Canvas.setFillStyle ctx "#0095DD"
      Canvas.fill ctx
      Canvas.closePath ctx

  coordinateBricks :: Bricks -> Bricks
  coordinateBricks bricks =
    ST.run do
      var <- STRef.new bricks
      for 0 brickColumnCount \c ->
        for 0 brickRowCount \r ->
          let
            key = BricksIndex { row: r, column: c }

            value = Brick (coord key)
          in
            STRef.modify (Map.insert key value) var
      STRef.read var
    where
    coord :: BricksIndex -> { x :: Number, y :: Number }
    coord (BricksIndex { row: r, column: c }) =
      { x: (c * (brickWidth + brickPadding)) + brickOffsetLeft # Int.toNumber
      , y: (r * (brickHeight + brickPadding)) + brickOffsetTop # Int.toNumber
      }

  collisionDetection :: { x :: Number, y :: Number } -> Bricks -> Boolean
  collisionDetection ball bricks =
    let
      (xs :: Array (Tuple BricksIndex Brick)) = Map.toUnfoldableUnordered bricks
    in
      any collisioned xs
    where
    collisioned :: Tuple BricksIndex Brick -> Boolean
    collisioned (Tuple _ (Brick brick)) =
      between brick.x (brick.x + (Int.toNumber brickWidth)) ball.x
        && between brick.y (brick.y + (Int.toNumber brickHeight)) ball.y

nextDataset :: Dataset -> Dimensions -> { nextDataset :: Dataset, gameover :: Boolean }
nextDataset dataset c =
  let
    { x: x, y: y, dx: dx, dy: dy } = dataset

    r = ballRadius

    newPaddleX = case { left: dataset.leftPressed, right: dataset.rightPressed } of
      { left: false, right: true } -> dataset.paddleX + 7.0
      { left: true, right: false } -> dataset.paddleX - 7.0
      _ -> dataset.paddleX

    { nextDy: nextDy, gameover: gameover } =
      let
        touchTheCeiling = (y + dy) < r

        touchTheFloor = (y + dy) > (c.height - r)

        touchThePaddle = touchTheFloor && between dataset.paddleX (dataset.paddleX + paddleWidth) (x + dx)
      in
        case true of
          _
            | touchTheCeiling -> { nextDy: (-dy), gameover: false }
            | touchThePaddle -> { nextDy: (-dy), gameover: false }
            | touchTheFloor -> { nextDy: (-dy), gameover: true }
            | otherwise -> { nextDy: dy, gameover: false }
  in
    { nextDataset:
        dataset
          { x = x + dx
          , y = y + dy
          , dx =
            if between r (c.width - r) (x + dx) then
              dx
            else
              (-dx)
          , dy = nextDy
          , paddleX = clamp 0.0 (c.width - paddleWidth) newPaddleX
          }
    , gameover: gameover
    }

timer :: forall m a. MonadAff m => a -> m (HS.Emitter a)
timer val = do
  { emitter, listener } <- H.liftEffect HS.create
  _ <-
    H.liftAff $ Aff.forkAff
      $ forever do
          Aff.delay $ Milliseconds 10.0
          H.liftEffect $ HS.notify listener val
  pure emitter

lesson07-1

期待通り動いている。

衝突検出を有効にする

いろいろやってこうなった。

  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
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
module Breakout (component) where

import Prelude
import CSS (background, block, display, margin, marginBottom, marginLeft, marginRight, marginTop, padding, px, rgb)
import CSS.Common (auto)
import Control.Monad.Rec.Class (forever)
import Control.Monad.ST (for)
import Control.Monad.ST as ST
import Control.Monad.ST.Ref as STRef
import Data.Array as Array
import Data.Generic.Rep (class Generic)
import Data.Int as Int
import Data.Map (Map)
import Data.Map as Map
import Data.Maybe (Maybe(..))
import Data.Show.Generic (genericShow)
import Data.Time.Duration (Milliseconds(..))
import Data.Traversable (for_)
import Data.Tuple (Tuple(..))
import Effect (Effect)
import Effect.Aff as Aff
import Effect.Aff.Class (class MonadAff)
import Graphics.Canvas (CanvasElement, Dimensions)
import Graphics.Canvas as Canvas
import Halogen (SubscriptionId)
import Halogen as H
import Halogen.HTML as HH
import Halogen.HTML.CSS (style)
import Halogen.HTML.Properties as HP
import Halogen.Query.Event (eventListener)
import Halogen.Subscription as HS
import Math as Math
import Web.Event.Event as E
import Web.HTML (window)
import Web.HTML.HTMLDocument as HTMLDocument
import Web.HTML.Location as Location
import Web.HTML.Window as Window
import Web.UIEvent.KeyboardEvent as KE
import Web.UIEvent.KeyboardEvent.EventTypes as KET

canvasId :: String
canvasId = "myCanvas"

paddleHeight = 10.0 :: Number

paddleWidth = 75.0 :: Number

ballRadius = 10.0 :: Number

brickRowCount = 3 :: Int

brickColumnCount = 5 :: Int

brickWidth = 75 :: Int

brickHeight = 20 :: Int

brickPadding = 10 :: Int

brickOffsetTop = 30 :: Int

brickOffsetLeft = 30 :: Int

data BrickStatus
  = InActive
  | Active

derive instance genericBrickStatus :: Generic BrickStatus _

derive instance eqBrickStatus :: Eq BrickStatus

instance showBrickStatus :: Show BrickStatus where
  show = genericShow

newtype BricksIndex
  = BricksIndex { row :: Int, column :: Int }

derive newtype instance showBricksIndex :: Show BricksIndex

derive newtype instance ordBricksIndex :: Ord BricksIndex

derive newtype instance eqBricksIndex :: Eq BricksIndex

newtype Brick
  = Brick { x :: Number, y :: Number, status :: BrickStatus }

derive newtype instance showBrick :: Show Brick

type Bricks
  = Map BricksIndex Brick

type Dataset
  = { x :: Number
    , y :: Number
    , dx :: Number
    , dy :: Number
    , paddleX :: Number
    , leftPressed :: Boolean
    , rightPressed :: Boolean
    , bricks :: Bricks
    }

type State
  = { maybeCanvas :: Maybe CanvasElement
    , maybeTimer :: Maybe SubscriptionId
    , dataset :: Dataset
    }

data Action
  = Initialize
  | Tick
  | HandleKeyDown KE.KeyboardEvent
  | HandleKeyUp KE.KeyboardEvent

component :: forall query input output m. MonadAff m => H.Component query input output m
component =
  H.mkComponent
    { initialState
    , render
    , eval:
        H.mkEval
          $ H.defaultEval
              { handleAction = handleAction
              , initialize = Just Initialize
              }
    }

initialState :: forall i. i -> State
initialState _ =
  { maybeCanvas: Nothing
  , maybeTimer: Nothing
  , dataset:
      { x: 0.0
      , y: 0.0
      , dx: 0.0
      , dy: 0.0
      , paddleX: 0.0
      , leftPressed: false
      , rightPressed: false
      , bricks: Map.empty
      }
  }

render :: forall m. State -> H.ComponentHTML Action () m
render state =
  HH.main
    [ style do
        margin (px 0.0) (px 0.0) (px 0.0) (px 0.0)
        padding (px 0.0) (px 0.0) (px 0.0) (px 0.0)
    ]
    [ HH.canvas
        [ style do
            background (rgb 238 238 238)
            display block
            marginTop (px 0.0)
            marginRight auto
            marginBottom (px 0.0)
            marginLeft auto
        , HP.id canvasId
        , HP.width 480
        , HP.height 320
        ]
    , HH.text $ show state.dataset
    ]

handleAction :: forall output m. MonadAff m => Action -> H.HalogenM State Action () output m Unit
handleAction = case _ of
  Initialize -> do
    -- keyboard event
    document <- H.liftEffect $ Window.document =<< window
    H.subscribe' \_ ->
      eventListener
        KET.keydown
        (HTMLDocument.toEventTarget document)
        (map HandleKeyDown <<< KE.fromEvent)
    H.subscribe' \_ ->
      eventListener
        KET.keyup
        (HTMLDocument.toEventTarget document)
        (map HandleKeyUp <<< KE.fromEvent)
    -- timer
    sid <- H.subscribe =<< timer Tick
    --
    init <- H.liftEffect initialize
    H.put init { maybeTimer = Just sid }
  Tick -> do
    (state :: State) <- H.get
    case { a: state.maybeCanvas, b: state.maybeTimer } of
      { a: Just canvas, b: Just timerSubscriptionId } -> do
        ret <- H.liftEffect $ draw canvas state.dataset
        if ret.gameover then do
          H.liftEffect $ Window.alert "GAME OVER" =<< window
          H.liftEffect $ Location.reload =<< Window.location =<< window
          H.unsubscribe timerSubscriptionId
        else
          H.modify_ \st -> st { dataset = ret.nextDataset }
      _ -> pure unit
  HandleKeyDown ev
    | KE.key ev == "Right" || KE.key ev == "ArrowRight" -> do
      H.liftEffect $ E.preventDefault (KE.toEvent ev)
      H.modify_ \st -> st { dataset { rightPressed = true } }
    | KE.key ev == "Left" || KE.key ev == "ArrowLeft" -> do
      H.liftEffect $ E.preventDefault (KE.toEvent ev)
      H.modify_ \st -> st { dataset { leftPressed = true } }
    | otherwise -> pure unit
  HandleKeyUp ev
    | KE.key ev == "Right" || KE.key ev == "ArrowRight" -> do
      H.liftEffect $ E.preventDefault (KE.toEvent ev)
      H.modify_ \st -> st { dataset { rightPressed = false } }
    | KE.key ev == "Left" || KE.key ev == "ArrowLeft" -> do
      H.liftEffect $ E.preventDefault (KE.toEvent ev)
      H.modify_ \st -> st { dataset { leftPressed = false } }
    | otherwise -> pure unit
  where
  initialize :: Effect State
  initialize =
    Canvas.getCanvasElementById canvasId
      >>= case _ of
          Nothing -> pure $ initialState unit
          Just canvas -> do
            dim <- Canvas.getCanvasDimensions canvas
            pure
              { maybeCanvas: Just canvas
              , maybeTimer: Nothing
              , dataset:
                  { x: dim.width / 2.0
                  , y: dim.height - 30.0
                  , dx: 2.0
                  , dy: (-2.0)
                  , paddleX: (dim.width - paddleWidth) / 2.0
                  , leftPressed: false
                  , rightPressed: false
                  , bricks: Map.empty
                  }
              }

draw :: CanvasElement -> Dataset -> Effect { nextDataset :: Dataset, gameover :: Boolean }
draw canvas dataset = do
  dim <- H.liftEffect $ Canvas.getCanvasDimensions canvas
  ctx <- Canvas.getContext2D canvas
  --
  Canvas.clearRect ctx { x: 0.0, y: 0.0, width: dim.width, height: dim.height }
  drawBall
  drawPaddle dim
  bricks <- pure $ coordinateBricks dataset.bricks
  drawBricks bricks
  pure $ nextDataset dataset { bricks = bricks } dim
  where
  drawBall :: Effect Unit
  drawBall = do
    ctx <- Canvas.getContext2D canvas
    --
    Canvas.beginPath ctx
    Canvas.arc ctx
      { x: dataset.x
      , y: dataset.y
      , radius: ballRadius
      , start: 0.0
      , end: Math.pi * 2.0
      }
    Canvas.setFillStyle ctx "#0095DD"
    Canvas.fill ctx
    Canvas.closePath ctx

  drawPaddle :: Dimensions -> Effect Unit
  drawPaddle { height: height } = do
    ctx <- Canvas.getContext2D canvas
    --
    Canvas.beginPath ctx
    Canvas.rect ctx
      { x: dataset.paddleX
      , y: height - paddleHeight
      , width: paddleWidth
      , height: paddleHeight
      }
    Canvas.setFillStyle ctx "#0095DD"
    Canvas.fill ctx
    Canvas.closePath ctx

  drawBricks :: Bricks -> Effect Unit
  drawBricks bricks =
    for_ bricks case _ of
      (Brick brick)
        | brick.status == Active -> do
          ctx <- Canvas.getContext2D canvas
          Canvas.beginPath ctx
          Canvas.rect ctx
            { x: brick.x
            , y: brick.y
            , width: Int.toNumber brickWidth
            , height: Int.toNumber brickHeight
            }
          Canvas.setFillStyle ctx "#0095DD"
          Canvas.fill ctx
          Canvas.closePath ctx
      _ -> pure unit

  coordinateBricks :: Bricks -> Bricks
  coordinateBricks bricks =
    ST.run do
      var <- STRef.new bricks
      for 0 brickColumnCount \c ->
        for 0 brickRowCount \r ->
          let
            key = BricksIndex { row: r, column: c }

            value = coord Active key
          in
            STRef.modify (Map.insertWith modify key value) var
      STRef.read var
    where
    modify :: Brick -> Brick -> Brick
    modify (Brick current) (Brick new) = Brick new { status = current.status }

    coord :: BrickStatus -> BricksIndex -> Brick
    coord status (BricksIndex { row: r, column: c }) =
      Brick
        { x: (c * (brickWidth + brickPadding)) + brickOffsetLeft # Int.toNumber
        , y: (r * (brickHeight + brickPadding)) + brickOffsetTop # Int.toNumber
        , status: status
        }

nextDataset :: Dataset -> Dimensions -> { nextDataset :: Dataset, gameover :: Boolean }
nextDataset dataset c =
  let
    { x: x, y: y, dx: dx, dy: dy } = dataset

    r = ballRadius

    newPaddleX = case { left: dataset.leftPressed, right: dataset.rightPressed } of
      { left: false, right: true } -> dataset.paddleX + 7.0
      { left: true, right: false } -> dataset.paddleX - 7.0
      _ -> dataset.paddleX

    collisionedBrick = collisionDetection { x: x, y: y } dataset.bricks

    { nextBricks: nextBricks, collisioned: collisioned } = case collisionedBrick of
      Nothing ->
        { nextBricks: dataset.bricks
        , collisioned: false
        }
      Just (Tuple key value) ->
        { nextBricks: Map.insert key value dataset.bricks
        , collisioned: true
        }

    { nextDy: nextDy, gameover: gameover } =
      let
        touchTheCeiling = (y + dy) < r

        touchTheFloor = (y + dy) > (c.height - r)

        touchThePaddle = touchTheFloor && between dataset.paddleX (dataset.paddleX + paddleWidth) (x + dx)
      in
        case true of
          _
            | touchTheCeiling -> { nextDy: (-dy), gameover: false }
            | touchThePaddle -> { nextDy: (-dy), gameover: false }
            | touchTheFloor -> { nextDy: (-dy), gameover: true }
            | collisioned -> { nextDy: (-dy), gameover: false }
            | otherwise -> { nextDy: dy, gameover: false }
  in
    { nextDataset:
        dataset
          { x = x + dx
          , y = y + dy
          , dx =
            if between r (c.width - r) (x + dx) then
              dx
            else
              (-dx)
          , dy = nextDy
          , paddleX = clamp 0.0 (c.width - paddleWidth) newPaddleX
          , bricks = nextBricks
          }
    , gameover: gameover
    }
  where
  collisionDetection :: { x :: Number, y :: Number } -> Bricks -> Maybe (Tuple BricksIndex Brick)
  collisionDetection ball bricks =
    Array.head
      $ map inactivate
      $ Map.toUnfoldableUnordered
      $ Map.filterWithKey collisioned bricks
    where
    inactivate :: Tuple BricksIndex Brick -> Tuple BricksIndex Brick
    inactivate (Tuple idx (Brick brick)) =
      Tuple
        idx
        $ Brick
            brick { status = InActive }

    collisioned :: BricksIndex -> Brick -> Boolean
    collisioned _ (Brick brick) = case brick.status of
      InActive -> false
      Active
        | between brick.x (brick.x + (Int.toNumber brickWidth)) ball.x
            && between brick.y (brick.y + (Int.toNumber brickHeight)) ball.y -> true
        | otherwise -> false

timer :: forall m a. MonadAff m => a -> m (HS.Emitter a)
timer val = do
  { emitter, listener } <- H.liftEffect HS.create
  _ <-
    H.liftAff $ Aff.forkAff
      $ forever do
          Aff.delay $ Milliseconds 10.0
          H.liftEffect $ HS.notify listener val
  pure emitter

breakout-game

ボールをぶつけたブロックが消せました。

GitHubリポジトリ

コードはGitHub上にあります。
https://github.com/ak1211/breakout

まだつづく

よてい

comments powered by Disqus

This website uses cookies to improve your experience.
このサイトは「Googleアナリティクス」を使用しています。
Googleアナリティクスはデータの収集のためにCookieを使用しています。


Built with Hugo
テーマ StackJimmy によって設計されています。