Anonymous user
Knight's tour: Difference between revisions
m
Updated to Elm 0.19.1
m (Updated to Elm 0.19.1) |
|||
Line 2,522:
=={{header|Elm}}==
<lang elm>
import List exposing (concatMap, foldl, head,member,filter,length,minimum,concat,map,map2,tail)
import List.Extra exposing (minimumBy, andThen)
import String exposing (join)
import Html as H
import Html.Attributes as HA
import
▲import Time exposing (Time,every, second)
import Svg exposing (rect, line, svg, g)
import Svg.Events exposing (onClick)
Line 2,537 ⟶ 2,539:
rowCount=20
colCount=20
type alias Cell = (Int, Int)
type alias Model =
{ path : List Cell
, board : List Cell
}
type Msg
= NoOp
| Tick Time.Posix
| SetStart Cell
init : () -> (Model,Cmd Msg)
init
let board =
(List.range 0 (colCount-1))
|> andThen
(\c ->
[(r, c)]
)
)
path = []
in (Model path board, Cmd.none)
view : Model -> H.Html Msg
view model =
let
showChecker row col =
rect [ x <|
, y <|
, width "1"
, height "1"
, fill <| if modBy 2 (row + col)
, onClick <| SetStart (row, col)
]
[]
showMove (row0,col0) (row1,col1) =
line [ x1 <|
, y1 <|
, x2 <|
, y2 <|
, style "stroke:yellow;stroke-width:0.05"
]
[]
render
let checkers =
[showChecker r c]
)
moves = case List.tail mdl.path of
Nothing -> []
Just tl -> List.map2 showMove
in checkers ++ moves
unvisited = length model.board - length model.path
center = [ HA.style
in
H.div
[]
[ H.h2
, H.h2
, H.h2
, H.div
[ svg
[ version "1.1"
, width (
, height (
, viewBox (join " "
[
,
,
,
]
[ g [] <| render model]
]
]
nextMoves : Model -> Cell -> List Cell
nextMoves model (stRow,stCol) =
let c = [ 1, 2, -1, -2]
km = c
c
|> andThen
(\cCol ->
if abs(cRow) == abs(cCol) then [] else [(cRow,cCol)]
)
)
jumps = List.map (\(kmRow,kmCol) -> (kmRow + stRow, kmCol + stCol)) km
Line 2,625 ⟶ 2,644:
bestMove : Model -> Maybe Cell
bestMove model =
case List.head (model.path) of
Nothing -> Nothing
Line 2,633 ⟶ 2,652:
update msg model =
let mo = case msg of
SetStart start ->
{model | path = [start]}
Tick
case model.path of
[] -> model
Line 2,645 ⟶ 2,664:
subscriptions : Model -> Sub Msg
subscriptions _ =
Time.every
main =
element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
Link to live demo: http://dc25.github.io/knightsTourElm/
|