////// One line of the high-score table.///pubtypealiasEntry = {name = String, score = Int32, level = Int32}////// The high-score table.////// Everything in this module that decides *what* the table contains is pure and needs no/// handler at all -- parsing, rendering, ordering and qualification are ordinary functions/// with ordinary tests. Only `load` and `save` touch a filesystem, and they are called from/// `main` alone.///mod Scores {/// How many places the table keeps.pubdefplaces(): Int32 = 12/// How many characters an entry's name may have.pubdefnameLength(): Int32 = 3defseparator(): String = "|"/// An empty high score table with no entries.pubdefempty(): List[Entry] = Nil////// Reads one line of the stored format, `NAME|SCORE|LEVEL`.////// A line that does not parse is dropped rather than fatal: a truncated or/// hand-edited file should cost you the table, not the game.///pubdefparseLine(line: String): Option[Entry] = {letparts = String.splitOn(substr = separator(), line);matchparts {casename :: score :: level :: Nil =>letsOpt = Int32.fromString(String.trim(score));letlOpt = Int32.fromString(String.trim(level));match (sOpt, lOpt) {case (Some(s), Some(l)) =>letcleanedName = clean(String.trim(name)); Some({name = cleanedName, score = s, level = l})case_ => None }case_ => None } }/// Parses a list of lines from disk into a ranked high score table.pubdefparse(lines: List[String]): List[Entry] = lines |> List.filterMap(parseLine) |> ranked/// Renders a list of high score entries into serializable line strings.pubdefrender(entries: List[Entry]): List[String] = {letsep = separator();letrenderEntry = e -> {"${e#name}${sep}${e#score}${sep}${e#level}" };List.map(renderEntry, entries) }////// Sorted best first and capped at `places`.///pubdefranked(entries: List[Entry]): List[Entry] =entries |> List.sortBy(e -> -e#score) |> List.take(places())////// Whether `score` earns a place.////// A zero never qualifies, however empty the table -- there is no dignity in immortalising/// a game you did not play.///pubdefqualifies(score: Int32, entries: List[Entry]): Bool =if (score<=0)falseelseif (List.length(entries) <places())trueelseList.exists(e -> score>e#score, entries)/// Inserts a new high score entry into the table and returns the re-ranked list.pubdefinsert(entry: Entry, entries: List[Entry]): List[Entry] = ranked(entry :: entries)/// Returns the highest score value currently in the high score table, or 0 if empty.pubdefbest(entries: List[Entry]): Int32 =List.foldLeft((top, e) -> Int32.max(top, e#score), 0, entries)/// Cleans a score-table name using the same rules as interactive initials entry.pubdefclean(input: String): String = sanitize(input)////// Cleans a typed string: forces uppercase, strips anything outside `A-Z` and `0-9`, and/// caps the length at `nameLength()`.////// Used when the player enters initials. `Scores.load` relies on this to ensure bad lines/// in the file cannot break the cabinet view.///pubdefsanitize(input: String): String = {letchars = String.toList(String.toUpperCase(input));letvalid = List.filter(allowed, chars);letkept = List.take(nameLength(), valid);List.foldLeft((acc, c) -> acc+"${c}", "", kept) }defallowed(c: Char): Bool = (c>='A'andc<='Z') or (c>='0'andc<='9')/// Pads a name out to the full width so the table lines up.pubdefpadded(name: String): String = {letlen = String.length(name);letmissing = nameLength() -len;if (missing<=0)nameelse {letpadSpace = (acc, _) -> acc+" ";letspaces = List.foldLeft(padSpace, "", List.range(0, missing));name+spaces } }// -- where the table lives ------------------------------------------------------------//// Everything above this line is arithmetic on data. Everything below touches a real// filesystem, and is called from `main` alone.deffolder(): String = "flix-invaders"deffileName(): String = "scores.txt"////// Where the table is kept: the file, and the directory that must exist to hold it.////// Both, rather than just the file, because saving has to create the directory on a first/// run. Carrying the directory alongside is honest about what was built; recovering it by/// hunting for the last separator in the path would be guesswork about a string we/// assembled ourselves.///pubtypealiasLocation = {dir = String, file = String}////// Where the table lives, by the XDG convention.////// `$XDG_CONFIG_HOME/flix-invaders` when that is set, otherwise/// `~/.config/flix-invaders`. `None` on a machine with neither -- there is nowhere/// sensible to put it, and inventing somewhere is worse than going without.///pubdeflocation(): Option[Location] \ Sys.Env = {letseparator = Sys.Env.getFileSeparator();letconfigured =Sys.Env.getVar("XDG_CONFIG_HOME") |> Option.filter(dir -> notString.isEmpty(dir));letfallback =Sys.Env.getUserHomeDirectory() |> Option.map(home -> "${home}${separator}.config");Option.withDefault(default = fallback, configured) |> Option.map(base -> {letdir = "${base}${separator}${folder()}"; {dir = dir, file = "${dir}${separator}${fileName()}"} }) }////// Reads the table, or an empty one if there is not a file yet.////// A missing file is the ordinary first run and yields `Ok(Nil)`. Every other error is/// returned rather than swallowed: a table you have no permission to read is not the same/// as no scores, and quietly treating it as one would let the next save overwrite/// somebody's table with nothing.///pubdefload(at: Location): Result[IoError, List[Entry]] \ Fs.FileRead =matchFs.FileRead.readLines(at#file) {case Ok(lines) => Ok(parse(lines))case Err(IoError.IoError(IoError.ErrorKind.NotFound, _)) => Ok(Nil)case Err(other) => Err(other) }////// Writes the table, creating the directory if this is the first run.////// `mkDirs` is content when the directory already exists, so there is no existence check/// here -- one would be redundant, and racy besides.///pubdefsave(at: Location, entries: List[Entry]): Result[IoError, Unit] \ Fs.FileWrite = {letlines = render(ranked(entries));Fs.FileWrite.mkDirs(at#dir) |> Result.flatMap(_ -> Fs.FileWrite.writeLines(lines = lines, at#file)) }}