Operation Manual
Experiments in Python
86
Notes:
Lesson 3.2: MasterPy
We’ve had a warm up, so let’s see if we can create a game using Python. Have you
ever played the Mastermind game, where you have to guess the hidden colours?
We can do the same here, but with letters rather than coloured pegs. It will also
give us the chance to work with some text in and text out commands.
Here’s the code that we’re going to use:
import string
import random
# create a list of 4 characters
secret = [ra ndo m.choic e('ABCDEF') for ite m in range(4)]
# tell the player what is going on
print("I've selected a 4-character secret code from the letters
A,B,C,D,E and F.")
print("I may have repeated some.")
print("Now, try and guess what I chose.")
yourguess = []
while list(yourguess) != secret:
yourguess = input("Enter a 4-letter guess: e.g. ABCD : ").u p p e r( )
if len(yourguess) != 4:
continue
# turn the guess into a list, like the secret
print("You guessed ", yourguess)
# create a list of tuples comparing the secret with the guess
comparingList = zip(secret, yourguess)
# create a list of the letters that match
# (this will be 4 when the lists match exactly)
correctList = [speg for speg, gpeg in comparingList if speg
== g peg]
# count each of the letters in the secret and the guess
# and make a note of the fewest in each
fewestLetters = [min(secret.cou nt(j), yourg uess.count(j)) for
j in 'ABCDEF']
print("Number of correct letter is ", len(c o r r e c t L i s t))
print("Number of unused letters is ", sum(fewestLetters) -
len(c o r r e c t L i s t ))
print("YOU GOT THE ANSWER : ", secret)
Can you guess the number sequence set by the computer? The computer selects
a sequence of four letters from a set of six. You enter a sequence of four letters
that you think the computer selected and it will report how many were exactly
right, and how many are in the sequence but are in the wrong position.
Tip...
Here, again, you
can see lines of
code that don’t
fit on one line.
Don’t press
Return to start a
new line, just let
it word wrap and
Python will work
it out for you.