[ create a new paste ] login | about

Link: http://codepad.org/mzkVDiY6    [ raw code | fork | 2 comments ]

CodePlea - Tcl, pasted on Nov 17:
puts {Welcome to mastermind.}
puts {A four digit code has been selected.}
puts {Guess at the code, and you'll be given
a black token for each digit in the correct
place, and a white token for each digit that
the code does contain, but is in the wrong
place.}
puts {Enter your guesses like: "4 5 6 7".\n}

set code {}
for {set i 0} {$i < 4} {incr i} {
    lappend code [expr int(rand() * 10)]
}


set numGuesses 0

while {1} {
    puts -nonewline {Guess: }
    flush stdout
    gets stdin guess
    if {![string match {[0-9] [0-9] [0-9] [0-9]} $guess]} {
        puts {Please guess in the format: "0 1 2 3"}
        flush stdout
    } else {
        incr numGuesses
        set black 0
        set white 0

        for {set i 0} {$i < 4} {incr i} {
            set c [lindex $guess $i]
            if {[lindex $code $i] == $c} {
                incr black
            } elseif {[lsearch $code $c] != -1} {
                incr white
            }
        }

        for {set i 0} {$i < $black} {incr i} {puts -nonewline B}
        for {set i 0} {$i < $white} {incr i} {puts -nonewline W}
        for {set i 0} {$i < 4 - ($black + $white)} {incr i} {puts -nonewline .}
        puts {}
        flush stdout

        if {$black == 4} break
    }
}

puts "Congratulations, you guessed correctly in just $numGuesses guesses."


Create a new paste based on this one


Comments:
posted by CodePlea on Nov 17
reply
posted by CodePlea on Nov 17
Heh, guess I should test the code before pasting. The \n doesn't get substituted. Uh.
reply