Working Hangman, but: NO max guess; NO ASCII gallow
[fp1415.git] / fp2 / week1 / camil / Galgje.icl
1 module Galgje
2
3 import StdEnv, SimpleFileIO, RandomGetallen
4
5 lexicon_file = "lexicon.txt"
6
7 // From the slides
8 skip_nl :: String -> String
9 skip_nl str = if (size str > 0 && str.[size str-1] == '\n') (str%(0,size str-2)) str
10
11 // From a String and a List of guesses (Chars), return a String that shows dots for letters that were not guessed yet
12 stripUnknown :: String [Char] -> String
13 stripUnknown s g = toString [if (isMember c g) c '.' \\ c <- (fromString s)]
14
15 // Get a random word from the lexicon file
16 randomWord :: *env -> (Maybe String, *env) | FileSystem env
17 randomWord env
18 # (ss,env) = readLines lexicon_file env
19 | ss == Nothing = (Nothing, env)
20 # (seed,env) = getNewRandomSeed env
21 | otherwise = (Just (skip_nl ((shuffle (fromJust ss) seed)!!0)), env)
22
23 // word, guesses, stdio -> (win, new guesses, stdio)
24 round :: String [Char] *File -> (Bool, [Char], *File)
25 round w g io
26 # io = io <<< stripUnknown w g <<< '\n'
27 | stripUnknown w g == w = (True, g, io)
28 # io = io <<< "Guess: "
29 # (ok,g`,io) = freadc io
30 # (_,io) = freadline io // to read until the next \n
31 | not ok = abort "Couldn't get guessed letter"
32 | otherwise = round w [g`:g] io
33
34 Start :: *World -> *World
35 Start world
36 # (word,world) = randomWord world
37 | word == Nothing = abort "Couldn't get random word"
38 # word = fromJust word
39 # (io,world) = stdio world
40 # (win,g,io) = round word [] io
41 # io = if win (io <<< "You win!\n") io
42 # (ok,world) = fclose io world
43 | not ok = abort "Couldn't close stdio"
44 | otherwise = world