git.dumitru.net mucegai / master src / Mucegai.elm
master

Tree @master (Download .tar.gz)

Mucegai.elm @masterraw · history · blame

  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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
port module Mucegai exposing (main, init, update, view)

import Browser
import Html exposing (Html, button, div, span, text)
import Html.Attributes exposing (class)
import Html.Events exposing (onClick)
import Browser.Events exposing (onKeyDown)

import Array exposing (Array)
import Json.Decode as Decode

import Time



--  MAIN

main : Program () Model Msg
main =
  Browser.document
    { init          = init
    , update        = update
    , view          = view
    , subscriptions = subscriptions }



--  MODEL

type State
  = Paused
  | Playing

type Direction
  = Up
  | Down
  | Left
  | Right

type alias Cell =
  { operator    : String
  , lastTrigger : Int
  }

type alias HeadState =
  { y : Int
  , x : Int
  , d : Direction
  , stack : List Int
  }

type alias Model =
  { state   : State
  , tempo   : Int
  , ticks   : Int
  , pointer : (Int, Int)
  , heads   : List HeadState
  , cells   : Array (Array Cell)
  }

init : () -> (Model, Cmd Msg)
init () =
  ( { state = Paused
    , tempo = 480
    , ticks = 0
    , pointer = (0, 0)
    , heads = []
    , cells =
      let defaultCell = { operator = ".", lastTrigger = -100 } in
      Array.repeat 20 (Array.repeat 30 defaultCell)
    }
  , Cmd.none
  )



--  SUBSCRIPTIONS

keyDecoder : Decode.Decoder Msg
keyDecoder =
  let
    allowedKeys =
      [ "v", "^", "<", ">", "!", ".", ":", "o", "x", "h",
        "a", "b", "c", "d", "e", "f", "g", "+", "-",
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
        "]", ")", "~", "/", "@", ";"
      ]
    decodeAction k =
      case k of
        "ArrowLeft" ->
          MovePointer 0 -1
        "ArrowRight" ->
          MovePointer 0 1
        "ArrowUp" ->
          MovePointer -1 0
        "ArrowDown" ->
          MovePointer 1 0
        other ->
          if List.any (\s -> s == other) allowedKeys then
            UpdateCell other
          else
            NoOp
  in
  Decode.field "key" Decode.string
    |> Decode.map decodeAction

subscriptions : Model -> Sub Msg
subscriptions model =
  case model.state of
    Playing ->
      Sub.batch
        [ onKeyDown keyDecoder
        , Time.every (60000 / toFloat model.tempo) Advance
        ]
    Paused ->
      onKeyDown keyDecoder



--  PORTS

port triggerSample : Int -> Cmd msg
port triggerNote   : Int -> Cmd msg



--  UPDATE

type Msg
  = Play
  | Pause
  | SetPointer Int Int
  | MovePointer Int Int
  | UpdateCell String
  | Advance Time.Posix
  | NoOp

updateCell : Array (Array Cell) -> Int -> Int -> Cell -> Array (Array Cell)
updateCell cells y x ch =
  case Array.get y cells of
    Just row ->
      case Array.get x row of
        Just _ ->
          let newRow = Array.set x ch row in
          Array.set y newRow cells
        Nothing -> cells
    Nothing -> cells

touchCell : Array (Array Cell) -> Int -> Int -> Int -> Array (Array Cell)
touchCell cells y x lt =
  case Array.get y cells of
    Just row ->
      case Array.get x row of
        Just cell ->
          let newRow = Array.set x { cell | lastTrigger = lt } row in
          Array.set y newRow cells
        Nothing -> cells
    Nothing -> cells

findHeads : Model -> List HeadState
findHeads model =
  let
    findSourcesInRow (idx, row) =
      Array.indexedMap (\i e -> (idx, i, e)) row
        |> Array.filter (\(_, _, s) -> s.operator == "!")
        |> Array.toList
        |> List.map (\(y, x, _) -> { y = y, x = x, d = Down, stack = [] })
    indexedRows =
      Array.indexedMap (\i e -> (i, e)) model.cells
        |> Array.toList
  in
    List.concatMap findSourcesInRow indexedRows

getCell : Array (Array Cell) -> Int -> Int -> Maybe Cell
getCell cells y x =
  Array.get y cells
    |> Maybe.andThen (Array.get x)

collectCommands : Model -> HeadState -> ((Cmd Msg, List (Int, Int)), HeadState)
collectCommands model start =
  let
    interpretEffect op state =
      case op of
        Just ")" ->
          case pop state.stack of
            Just (hd, _) -> [ triggerSample hd ]
            Nothing -> []
        Just "]" ->
          case pop state.stack of
            Just (hd, _) -> [ triggerNote hd ]
            Nothing -> []
        _ ->
          []

    move state =
      case state.d of
        Up    -> { state | y = state.y - 1 }
        Down  -> { state | y = state.y + 1 }
        Left  -> { state | x = state.x - 1 }
        Right -> { state | x = state.x + 1 }

    pop stack =
      case stack of
        hd :: tl -> Just (hd, tl)
        [] -> Nothing

    drop stack =
      case stack of
        _ :: tl -> tl
        [] -> []

    swap stack =
      let
        newStack =
          pop stack
          |> Maybe.andThen (\(a, tl_a) ->
            pop tl_a
            |> Maybe.andThen (\(b, tl_b) ->
              Just (b :: a :: tl_b)))
      in
        case newStack of
          Just s ->
            s
          Nothing ->
            stack

    interpret op acc t state =
      let
        pushAndMove n =
          let newState = move state in
          collect acc tt { newState | stack = n :: state.stack }

        tt =
          (state.y, state.x) :: t
      in
      case op of
        --  DROP
        Just ";" ->
          let
            newStack = drop state.stack
            newState = { state | stack = newStack }
          in
            collect acc tt (newState |> move)
        
        --  SWAP
        Just "@" ->
          let
            newStack = swap state.stack
            newState = { state | stack = newStack }
          in
            collect acc tt (newState |> move)

        --  COND
        Just "/" ->
          let
            newDir =
              case pop state.stack of
                Just (hd, _) ->
                  if hd == 0 then
                    case state.d of
                      Up    -> Right
                      Right -> Up
                      Down  -> Left
                      Left  -> Down
                  else
                    state.d
                Nothing ->
                  state.d

            newState = { state | d = newDir }
          in
            collect acc tt (newState |> move)

        --  REST
        Just ":" ->
          case pop state.stack of
            Just (hd, tl) ->
              if hd == 0 then
                let newState = move state in
                collect acc tt { newState | stack = tl }
              else
                (acc, tt, { state | stack = (hd - 1) :: tl })
            Nothing ->
              (acc, tt, move state)

        --  MOVEMENT
        Just ">" -> collect acc tt { state | x = state.x + 1, d = Right }
        Just "<" -> collect acc tt { state | x = state.x - 1, d = Left }
        Just "^" -> collect acc tt { state | y = state.y - 1, d = Up }
        Just "v" -> collect acc tt { state | y = state.y + 1, d = Down }

        --  LITERALS
        Just "0" -> pushAndMove 0
        Just "1" -> pushAndMove 1
        Just "2" -> pushAndMove 2
        Just "3" -> pushAndMove 3
        Just "4" -> pushAndMove 4
        Just "5" -> pushAndMove 5
        Just "6" -> pushAndMove 6
        Just "7" -> pushAndMove 7
        Just "8" -> pushAndMove 8
        Just "9" -> pushAndMove 9
        Just "a" -> pushAndMove 10
        Just "b" -> pushAndMove 11
        Just "c" -> pushAndMove 12

        Just "+" ->
          let
            result = 
              pop state.stack
                |> Maybe.andThen (\(a, tl_a) ->
                  pop tl_a
                    |> Maybe.andThen (\(b, tl) ->
                      Just (a + b, tl)))
            newState =
              case result of
                Just (sum, stack) ->
                  { state
                  | stack = sum :: stack
                  }

                Nothing ->
                  state
          in
            collect acc tt (newState |> move)

        Just "-" ->
          let
            result = 
              pop state.stack
                |> Maybe.andThen (\(a, tl_a) ->
                  pop tl_a
                    |> Maybe.andThen (\(b, tl) ->
                      Just (b - a, tl)))
            newState =
              case result of
                Just (dif, stack) ->
                  { state
                  | stack = dif :: stack
                  }

                Nothing ->
                  state
          in
            collect acc tt (newState |> move)

        Just _ ->
          let
            eff = interpretEffect op state
          in
          if List.isEmpty eff then
            collect acc tt (state |> move)
          else
            collect (List.concat [eff, acc]) tt ( state |> move)
        Nothing -> (acc, tt, state)

    collect : List (Cmd Msg) -> List (Int, Int) -> HeadState -> (List (Cmd Msg), List (Int, Int), HeadState)
    collect acc tt state =
      let
        op =
          getCell model.cells state.y state.x
          |> Maybe.map (\c -> c.operator)
      in
        if List.member (state.y, state.x) tt then
          (acc, tt, state)
        else
          interpret op acc tt state

    (effects, touched, end) = collect [] [] start
  in
    ( ( Cmd.batch effects
      , touched
      )
    , end
    )


advance : Model -> (Model, Cmd Msg)
advance model =
  let
    --(triggers, newHeads) = List.unzip (List.map (advanceHead model) model.heads)
    (effects, newHeads) = List.unzip (List.map (collectCommands model) model.heads)
    (triggers, touched) = List.unzip effects
    newCells = List.foldl (\(y, x) a -> touchCell a y x model.ticks) model.cells (List.foldr (++) [] touched)
  in
  ( { model
    | heads = newHeads
    , cells = newCells
    , ticks = model.ticks + 1
    }
  , Cmd.batch triggers
  )

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    Play ->
      ( { model
        | heads = findHeads model
        , state = Playing
        , ticks = 0
        }
      , Cmd.none
      )

    Pause ->
      ( { model
        | state = Paused
        }
      , Cmd.none
      )

    SetPointer y x ->
      ( { model
        | pointer = (y, x)
        }
      , Cmd.none
      )

    MovePointer dy dx ->
      ( { model
        | pointer =
          let
            (y, x) = model.pointer
          in
            (y + dy, x + dx)
        }
      , Cmd.none
      )

    UpdateCell ch ->
      ( { model
        | cells =
          let (y, x) = model.pointer in
          updateCell model.cells y x { operator = ch, lastTrigger = -100 }
        }
      , Cmd.none
      )

    Advance _ -> advance model

    NoOp ->
      ( model
      , Cmd.none
      )


-- VIEW

viewCell : Model -> Int -> Int -> Cell -> Html Msg
viewCell model y x cell =
  let
    handler = onClick (SetPointer y x)
    isUnderPointer =
      if model.pointer == (y, x) then
        [ class "selected" ]
      else
        []
    isUnderHead =
      if List.any (\h -> h.y == y && h.x == x) model.heads then
        [ class "head" ]
      else
        []
    isRecent =
      if model.ticks - cell.lastTrigger == 1 then
        [ class "triggered" ]
      else
        []
    isDimmed =
      if cell.operator == "." then
        [ class "dim" ]
      else
        []
    isMovement =
      if cell.operator == ">" || cell.operator == "<" || cell.operator == "^" || cell.operator == "v" then
        [ class "movement" ]
      else
        []
    classes =
      List.concat
        [ isUnderPointer
        , isUnderHead
        , isRecent
        , isDimmed
        , isMovement
        , [class "cell"]
        ]
  in
    div (handler :: classes) [ text cell.operator ]

viewRow : Model -> Int -> Array Cell -> Html Msg
viewRow model y row =
  let cells = Array.indexedMap (viewCell model y) row in
  div [ class "row"] (Array.toList cells)

viewPlayground : Model -> Html Msg
viewPlayground model =
  let rows = Array.indexedMap (viewRow model) model.cells in
  div [ class "playground" ] (Array.toList rows)

viewHeadStates : Model -> Html Msg
viewHeadStates model =
  let
    viewStackElement el =
      span [ class "stack-element" ] [ text (String.fromInt el) ]
    viewHeadState state =
      div [ class "state" ] (List.map viewStackElement state)
  in
    div [] (List.map (\h -> viewHeadState h.stack) model.heads)

view : Model -> Browser.Document Msg
view model =
  let
    title = "mu/ce/gai"
    body = [
      div []
        [ div [ class "row", class "title" ]
            [ span [] [ text "mu" ]
            , span [] [ text "/" ]
            , span [] [ text "ce" ]
            , span [] [ text "/" ]
            , span [] [ text "gai" ]
            ]
        , viewPlayground model
        , div [ class "row" ]
            [ button [ onClick Play ] [ text "play" ]
            , button [ onClick Pause ] [ text "stop" ]
            ]
        , viewHeadStates model
        ]
      ]
  in
    { title = title, body = body }