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