Anonymous user
Knight's tour: Difference between revisions
Undo revision 310917 by Dmcbane (talk)
Line 2,522:
=={{header|Elm}}==
<lang elm>
import Browser exposing (element)▼
import List.Extra exposing (minimumBy, andThen)
import String exposing (join)
import Html as H
import Html.Attributes as HA
import
import Svg exposing (rect, line, svg, g)
import Svg.Events exposing (onClick)
Line 2,539 ⟶ 2,537:
rowCount=20
colCount=20
dt = 0.03
type alias Cell = (Int, Int)
type alias Model =
{ path : List Cell
, board : List Cell
}
type Msg = NoOp | Tick Time | SetStart Cell
init :
init
let board =
[0..colCount-1] `andThen` \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
, 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
moves = case List.tail model.path
Nothing -> []
Just tl -> List.map2 showMove
in checkers ++ moves
unvisited = length model.board - length model.path
center =
in
H.div
[]
[ H.h2 [center] [H.text "Knight's Tour"]
, H.h2 [center] [H.text <| "Unvisited count : " ++
, H.h2 [center] [H.text "(pick a square)"]
, H.div
[center]
[ 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 `andThen` \cRow ->
c
if abs(cRow) == abs(cCol) then [] else [(
jumps = List.map (\(kmRow,kmCol) -> (kmRow + stRow, kmCol + stCol)) km
Line 2,644 ⟶ 2,625:
bestMove : Model -> Maybe Cell
bestMove model =
case List.head (model.path) of
Nothing -> Nothing
Line 2,652 ⟶ 2,633:
update msg model =
let mo = case msg of
SetStart start ->
{model | path = [start]}
Tick
case model.path of
[] -> model
Line 2,664 ⟶ 2,645:
subscriptions : Model -> Sub Msg
subscriptions _ =
Time.every
main =
program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}</lang>
Link to live demo: http://dc25.github.io/knightsTourElm/
|