Python Mastermind Game Troubles
Solution 1:
You can solve your problem very elegantly with the Python function map(). (Not quite as elegantly as I originally thought, but still pretty nicely.)
guess = "1879"# or [ '1', '8', '7', '9' ]
answer = "1234"
map() works like this: you give it a function as its first argument, and one or more sequences as arguments following that. It then takes takes that function and applies it first to both the first elements, then to both the second elements, and so on. For instance:
>>>deff(a,b):>>>return a + b>>>map( f, [1,2,3,4], [ 10, 20, 30, 40 ] )
[ 11, 22, 33, 44 ]
Now, you have two sequence of characters, "guess" and "answer". You could write a function that returns X if they're equal and - otherwise like this:
>>>defmastermind_hint( a, b ):>>>return"X"if a == b else"-"
That's not quite enough, you also need to put in the 'O's. For this you need to use the entire "answer" sequence at once:
>>>defmastermind_hint( a, b ):>>>if a == b: return"X">>>if a in answer: return"O">>>return"-"
Using map, we can apply that to the sequences you have:
>>> map( mastermind_hint, guess, answer )
[ "X", "-", "-", "-" ]
Now, right now we're giving away more information than we're supposed to because the positions of our hints correspond to the positions of the guess characters. A simple way to hide this information is to sort the sequence. Python has a sorted() function which does this:
>>> sorted( map( mastermind_hint, guess, answer ) )
[ "-", "-", "-", "X" ]
All that remains is to join this into a single string:
>>> "".join( sorted( map( mastermind_hint, guess, answer ) ) )
"---X"
Solution 2:
Very interesting homework I must say. I wish I'd get homework like this one.
Normally I don't provide full answers to homework but I solved this one for fun and you have tried to solve this on your own so here you go:
import random
defmain():
print'>> New game started.\n>> Good luck!\n'
answer = generateAnswer()
whileTrue:
userGuess = getUserGuess()
if userGuess == answer:
print'>> Congratulations, you won!'returnprint'>> The answer you provided is incorrect.\n>> Perhaps this hint will help you: '
giveFeedback(answer, userGuess)
defgenerateAnswer():
digits = [str(x) for x inrange(10)]
answer = ''for i inrange(4):
digit = random.sample(digits, 1)[0]
digits.remove(digit)
answer += digit
return answer
defgetUserGuess():
whileTrue:
guess = raw_input('>> Please enter a 4-digit number: ').strip()
iflen(guess) != 4:
continue
guessIsValid = Truefor x in guess:
if guess.count(x) != 1orord(x) notinrange(48, 58):
guessIsValid = Falsebreakif guessIsValid:
return guess
defgiveFeedback(answer, guess):
for i inrange(4):
if guess[i] == answer[i]:
print'X',
continueif guess[i] in answer:
print'O',
continueprint'-',
print'\n'if __name__ == '__main__':
try:
main()
except Exception, e:
print'>> Fatal error: %s' % e
I hope you'll find your answer in this piece of code.
Solution 3:
Here is an example that uses some more advance python idioms to improve readability and succinctness. This also makes it easier to make a more general solution such as for n digit answers for m base.
import random
from itertools import permutations # for "lucky guess" Easter eggdefmain(base=10, size=4):
print'New game started.\nGood luck!\n'
answer, turn = list(genAnswer(range(base), size)), 1whileTrue:
hint = ['X'if a == g
else'0'if g in answer
else'-'for a, g inzip(answer, guess(base, size))]
ifset(hint) == set(['X']):
if turn == 1:
choices = len(list(permutations(range(base), size)))
print'You won, lucky guess out of %d possible choices' % choices
else:
print'Congratulations, you won in %d turns!' % turn
returnprint' Hint %d: %s' % (turn, ''.join(hint))
turn += 1defgenAnswer(digits, size):
'''Python generator function'''for i inrange(size):
choice = random.choice(digits)
yieldstr(choice)
digits.remove(choice)
defguess(base, size):
'''Uses duck typing for error detection'''whileTrue:
guess = raw_input('>> Guess: ').strip()
try:
ifint(guess, base) < base**size andlen(set(guess)) == size:
return guess
except ValueError:
passprint'Enter %d unique digits from 0 to %d' % (size, base -1)
>>> main(6, 4)
New game started.
Good luck!
>> Guess: 1234
Hint 1: 0-X-
>> Guess: 12345
Enter 4 unique digits from0 to 5
>> Guess: 01227
Enter 4 unique digits from0 to 5
>> Guess: 0123
Hint 2: XX-0
>> Guess: 0135
Congratulations, you won in3 turns!
Post a Comment for "Python Mastermind Game Troubles"