Sluggish beginner: trying to write blackjack

I do independent research at Elm, and it seems to me that I'm learning to program again and again! As a training project, I try to run a simple blackjack, but as soon as I started, I realized how much I still do not understand. I mean drawing cards from the deck and adding them to the list:

import Random
import Mouse
import Array

--Build the deck
faces = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
suits = ['H', 'D', 'C', 'S']

allCards faces suits =
  case suits of
    x :: xs -> family faces x ++ allCards faces xs
    _ -> []

family faces suit =
  case faces of
    x :: xs -> (,) x suit :: family xs suit
    _ -> []

deck = allCards faces suits

rand : Signal Int
rand = Random.range 0 (length deck-1) Mouse.clicks 

pickCard n = head <| drop n deck
nextCard = lift pickCard rand

yourHand = foldp (::) [] nextCard

main = lift asText yourHand

My questions are mainly about continuation. Looking at completed projects Elm helps a little, but many of them are difficult to figure out as a beginner. Any direction helps!

  • , , , , , , - dropCard deck card = filter (\card /= nextCard) deck, . Elm , , , , , , . foldp ?

  • ? , toHand . dropCard card?

  • /, , . fst (head deck), , , . - ?

, Elm !

+4
1

  • - , . . , . foldp , , , .
  • , , . , .
  • fst (head deck) . , lift main, ?

-- This first part is your code:
import Random
import Mouse
import Array

--Build the deck
faces = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
suits = ['H', 'D', 'C', 'S']

allCards faces suits =
  case suits of
    x :: xs -> family faces x ++ allCards faces xs
    _ -> []

family faces suit =
  case faces of
    x :: xs -> (,) x suit :: family xs suit
    _ -> []

-- Here come my additions/changes:
-- Naming some types for clarity
type Card = (Int,Char)
type ProgramState = { deck : [Card], hand : [Card] }

getFromList : Int -> [a] -> (a,[a])
getFromList index list =
  let prefix = take index list
      (item :: postfix) = drop index list
  in (item, prefix ++ postfix)

startState : ProgramState
startState = { deck = allCards faces suits, hand = [] }

rand : Signal Float
rand = Random.float Mouse.clicks 

rFloatToInt : Float -> Int -> Int -> Int
rFloatToInt rnd lo hi = round ((rnd + toFloat lo) * toFloat hi)

pickCard : Float -> ProgramState -> ProgramState
pickCard rnd {deck,hand} = 
  let index = rFloatToInt rnd 0 (length deck - 1)
      (item, newDeck) = getFromList index deck
  in { deck = newDeck, hand = item :: hand }

programState : Signal ProgramState
programState = foldp pickCard startState rand

main : Signal Element
main = lift asText programState

- , .

+7

All Articles