Example—rogue

This previous example is a very typical Expect fragment. It does not take much more to produce a useful script. As an example, the following script provides a small assist in playing the game of rogue. rogue is an adventure game which presents you with a player that has various physical attributes, such as strength. Most of the time, the strength rating is 16, but every so often— maybe one out of 20 games— you get an unusually good strength rating of 18. A lot of rogue players know this, but no one in their right mind restarts the game 20 times to find those really good configurations—it is too much typing. The following script does it automatically:

while 1 {
    spawn rogue
    expect {
        "Str: 18" break
        "Str: 16"
    }
    send "Q"
    expect "quit?"
    send "y"
    close
    wait
}
interact

Inside a loop, rogue is started and then the strength is checked to see if it is 18 or 16. If it is 16, the dialogue is terminated. Like telnet (see Chapter 4 (p. 103)), rogue does not watch for an eof either, so a simple close is not sufficient to end the dialogue. "Q" requests that rogue quit. The game asks "are you sure" to which the script replies "y“. At this point, both the script and rogue close the connection. Then the script executes wait. As I described in Chapter 4 (p. 105), wait tells the system that it can discard the final exit status of the rogue process.

Whenrogue exits, the loop is restarted and a new game of rogue is created to test. When a strength of 18 is found, the break action is executed. ...

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.