17
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Elmでマス目を描画する2

Last updated at Posted at 2019-03-14

Elm本をchapter3の冒頭まで読み、ソースコードがほぼ読めるようになりました。
なんか作れる気がしてきたので、前回半端になっていたマスを描画するページをゼロから作ってみました。

作ったもの

Elm guideにあるカウンターアプリの改造みたいなもので、マスの数と大きさを動的に変更できるようにしました。
JavaScriptだけでやろうとするとなかなか面倒があると思うのですが、Elmで書くと比較的簡単。関心事に注力して書けるのを実感しました。

IMG_20190314_200632.jpg

IMG_20190314_200716.jpg

IMG_20190314_200547.jpg

ソースコード

ソースコード
module Main exposing (Model, Msg(..), init, main, update, view)

import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick)


main =
    Browser.sandbox
        { init = init
        , update = update
        , view = view
        }



-- MODEL


type alias Model =
    { size : Int
    , length : Int
    }


init : Model
init =
    Model 1 1



-- UPDATE


type Msg
    = Size Int
    | Length Int


update : Msg -> Model -> Model
update msg model =
    case msg of
        Size val ->
            { model | size = model.size + val }

        Length val ->
            { model | length = model.length + val }



-- VIEW


view : Model -> Html Msg
view model =
    div []
        [ div []
            [ text "length"
            , button [ onClick (Length -1) ] [ text "-" ]
            , text (String.fromInt model.length)
            , button [ onClick (Length 1) ] [ text "+" ]
            ]
        , div []
            [ text "size"
            , button [ onClick (Size -1) ] [ text "-" ]
            , text (String.fromInt model.size)
            , button [ onClick (Size 1) ] [ text "+" ]
            ]
        , td [ style "border" "solid thin", style "width" (String.fromInt model.size ++ "px") ] []
            |> List.repeat model.length
            |> tr [ style "height" (String.fromInt model.size ++ "px") ]
            |> List.repeat model.length
            |> table [ style "border" "solid thin", style "border-collapse" "collapse" ]
        ]
17
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?