Assignment 4: Mastermind

In this assignment, you will write a Scheme program for the game of Mastermind.

You will write a system in which the computer randomly invents a pattern and then judges your guesses. Your system will include a function try which returns a list of the number of black pegs and the number of white pegs received. In the example session below, the computer has the pattern (yellow red black blue) in mind.

> (try '(red red red red))
(1 0)
> (try '(red yellow yellow yellow))
(0 2)
> (try '(yellow red green green))
(2 0)
> (try '(yellow red blue blue))
(3 0)
> (try '(yellow red blue white))
(2 1)
> (try '(yellow red black blue))
(4 0)
I suggest the following steps:
  1. Write a function random-color which takes no arguments and returns one of the six sequence colors at random. You will need the random function given in assignment 1.
  2. Write a function random-sequence which takes one argument (a number) and returns a list of that many random colors.
  3. Write a function find-blacks which takes a guess and a pattern and returns the number of positions where both lists have the same value.
  4. Write a function find-whites which takes a guess and a pattern and returns the number of times a color in the guess appears in the pattern. It is easiest to make this function add a white peg even in case of an exact match, and then subtract the number of black pegs in the next function.

    Note that

    (find-whites '(red yellow red blue) '(green red green green))
    
    should return 1, not 2.
  5. Write a curried function judge which takes a pattern and returns a function which takes a guess and returns a list of the numbers of black and white pegs. This function must adjust for the fact that, for each exact match, both a black and a white peg are generated, but only the black peg should be shown.
  6. (define try (judge (random-sequence 4)))
Note that the random function provided produces the same sequence of random numbers every time your file is loaded. This is beneficial for debugging, but makes the game less entertaining. Once your program is working, go to the Languages menu in DrScheme and choose PLT/"Textual (MzScheme, includes R5RS)" to enable a built-in random function which produces a different sequence of numbers each time your file is loaded. Unfortunately, this dialect does not include the trace feature, so you probably don't want to do this until your program is working properly.
Last modified: Mon Feb 23 10:04:53 PST 2004