Updated 2016-02-08 00:48:20 by HJG

Summary edit

[thr] 2016-02-06: The following line of code lets you play a text-based Hangman game. It's basically a port of this Python code: Hangman implemented in 3 lines of Python (2). Pay attention to the word file. As I'm on Windows, I simply used this file: [1].

Code edit

try {foreach {chosenWord guesses scaffold man guessesLeft} [list [split [lindex [set words [lmap word [split [read [open linuxwords r]] \n] {string toupper $word}]] \
        [expr {int(rand() * [llength $words])}]] {}] {} "|======\n|   |\n| %4\$s %1\$s %6\$s\n|  %3\$s%2\$s%5\$s\n|  %7\$s %8\$s\n|  %9\$s %10\$s\n|" {O T - \\ - / / \\ | |} 10] \
        {while {([lsort -uniq $chosenWord] != [lsort -uniq $guesses]) && $guessesLeft > 0} {set guessesLeft [expr {10 - [llength [lmap guess [lappend guesses \
        [puts -nonewline [format "\n%s (%s guesses left)\n%s\n%s: " [join $guesses ","] $guessesLeft [format $scaffold {*}[concat [lrange $man 0 9-$guessesLeft] [lrepeat $guessesLeft " "]]] \
        [lmap letter $chosenWord {expr {$letter in $guesses ? $letter : "_"}}]]][expr {[set nextGuess [string toupper [gets stdin]]] ni $guesses ? $nextGuess : [continue]}]] \
        {expr {$guess ni $chosenWord ? $guess : [continue]}}]]}]}}} finally {puts "You [expr {$guessesLeft == 0 ? "lose!\n[format $scaffold {*}$man]" : "win!"}]\nWord was [join $chosenWord ""]"}

Comments edit

...

See also: The Gallows game