3 people like it.

Times Table game

Simple times table console based game.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
(helper functions omitted)

let play times = 
    for message in ["Get Ready";"3";"2";"1";"Go"] do 
        printfn "%s" message
        wait 1000
    let begun = now ()
    [1..times] |> Seq.sumBy (fun i ->
        let a, b = rand.Next 13, rand.Next 13
        printf "%d x %d = " a b
        let entered = readln ()
        match tryParseInt entered with
        | true, answer when answer = a * b -> 
            using green (fun () -> printfn "Correct")
            1
        | _, _ ->
            beep ()
            using red (fun () -> printfn "%d x %d = %d" a b (a*b))
            0
    ) |> (fun score ->
        let taken = (now() - begun).ToString("c")
        printfn "%d correct out of %d in %s" score times taken
    )

while true do 
    play 20
    wait 5000
    printfn "Hit a key to play again?"
    readkey () |> ignore
open System
let readln () = Console.ReadLine()
let readkey () = Console.ReadKey()
let tryParseInt = Int32.TryParse
let using color f =
    Console.ForegroundColor <- color
    f ()
    Console.ResetColor ()
let red = ConsoleColor.Red
let green = ConsoleColor.Green
let beep () = Console.Beep ()
let wait (n:int) = Threading.Thread.Sleep n
let now () = DateTime.Now
let rand = Random()
val play : times:int -> unit

Full name: Script.play
val times : int
val message : string
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val wait : n:int -> unit

Full name: Script.wait
val begun : DateTime
val now : unit -> DateTime

Full name: Script.now
module Seq

from Microsoft.FSharp.Collections
val sumBy : projection:('T -> 'U) -> source:seq<'T> -> 'U (requires member ( + ) and member get_Zero)

Full name: Microsoft.FSharp.Collections.Seq.sumBy
val i : int
val a : int
val b : int
val rand : Random

Full name: Script.rand
Random.Next() : int
Random.Next(maxValue: int) : int
Random.Next(minValue: int, maxValue: int) : int
val printf : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printf
val entered : string
val readln : unit -> string

Full name: Script.readln
val tryParseInt : arg00:string -> bool * int

Full name: Script.tryParseInt
val answer : int
val using : color:ConsoleColor -> f:(unit -> unit) -> unit

Full name: Script.using
val green : ConsoleColor

Full name: Script.green
val beep : unit -> unit

Full name: Script.beep
val red : ConsoleColor

Full name: Script.red
val score : int
val taken : string
val readkey : unit -> ConsoleKeyInfo

Full name: Script.readkey
val ignore : value:'T -> unit

Full name: Microsoft.FSharp.Core.Operators.ignore

More information

Link:http://fssnip.net/8u
Posted:5 years ago
Author:Phillip Trelford
Tags: console , game