repl.it
@ThomasS1/

Mastermind

Python

An implementation of Knuth's mastermind algorithm https://en.wikipedia.org/wiki/Mastermind_(board_game)#Five-guess_algorithm

fork
loading
Files
  • main.py
  • archive
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
from os import system as s
from sys import stdout
from itertools import product
from random import choice
from time import time
import webbrowser

#############
# VARIABLES #
#############

END = '\033[0m'

highlights = {
    "red": '\033[41m',
    "green": '\033[42m',
    "orange": '\033[43m',
    "blue": '\033[44m',
    "purple": '\033[45m',
    "cyan": '\033[46m',
    "white": '\033[47m',
    "grey": '\033[40m',
}

colours = {
    "red": '\033[91m',
    "green": '\033[92m',
    "yellow": '\033[93m',
    "blue": '\033[94m',
    "purple": '\033[95m',
    "cyan": '\033[96m',
    "grey": '\033[97m',
    "white": '\033[98m',
}

# answer: "0012"
examples = [
    "3545",
    "0435",
    "0002",
    "0021",
    "2011",
    "1134",
    "0012",
]

#############
# FUNCTIONS #
#############


class Unbuffered(object):
    def __init__(self, stream):
        self.stream = stream

    def write(self, data):
        self.stream.write(data)
        self.stream.flush()

    def writelines(self, datas):
        self.stream.writelines(datas)
        self.stream.flush()

    def __getattr__(self, attr):
        return getattr(self.stream, attr)


stdout = Unbuffered(stdout)


def awards(guess, answer):
    ''' Calculates the number of black and white pegs awarded for a given `guess` and `answer`. Returns a list: `[black, white]` '''

    black = 0
    white = 0
    guess = list(guess)
    answer = list(answer)
    remainingGuess = guess[:]  # the guessed colours that were not given a black peg
    remainingAnswer = answer[:]  # the answer colours that were not correctly guessed

    for n in range(len(guess)):
        if answer[n] == guess[n]:
            black += 1
            remainingGuess.remove(guess[n])
            remainingAnswer.remove(answer[n])

    for colour in remainingGuess:
        if colour in remainingAnswer:
            white += 1
            remainingAnswer.remove(colour)

    return [black, white]


def printableGuess(guess):
    ''' Returns a printable version of a set of colours from a string of numbers. '''
    printable = ""
    for colour in guess:
        printable += f"{list(highlights.values())[int(colour)]}  {END}  "
    return printable


#########
# SETUP #
#########

s('clear')
print(f'''{highlights["red"]}                         
  WELCOME TO MASTERMIND  
                         {END}

An implementation of Knuth's mastermind algorithm in Python by @ThomasS1

How many colours do you want to play with? (3-8){colours["blue"]}''')

# Loops until valid answer
while True:
    try:
        nColours = int(input())
        if 8 >= nColours >= 3:
            break
        else:
            raise ValueError()  # goes to except
    except:
        stdout.write("\033[{0};{1}f".format(7, 44))
        stdout.write(f'{colours["red"]}(3-8){END}')
        stdout.write("\033[{0};{1}f".format(8, 0))
        stdout.write("\033[K")
        stdout.write(colours["blue"])

stdout.write(f'''{END}
These are your {nColours} colours:
''')

print(printableGuess('01234567' [:nColours]))

print(f'''
How many spaces? (3-6){colours["blue"]}''')

# Loops until valid answer
while True:
    try:
        nSpaces = int(input())
        if 6 >= nSpaces >= 3:
            break
        else:
            raise ValueError()  # goes to except
    except:
        stdout.write("\033[{0};{1}f".format(13, 18))
        stdout.write(f'{colours["red"]}(3-6){END}')
        stdout.write("\033[{0};{1}f".format(14, 0))
        stdout.write("\033[K")
        stdout.write(colours["blue"])

stdout.write(f'''{END}
Now write down a code with {nSpaces} of the colours.
You can use each of them once, more than once, or not at all.
If you don't have coloured pencils, assign them a number,
but make sure you know what it represents!
The order is important.
When you are finished, press enter.
''')

S = list(product('01234567' [:nColours], repeat=nSpaces))
fullS = S[:]  # doesn't change

input()  # waits until done

# Chooses intelligence level
s('clear')

print(f'''{highlights["red"]}                         
  WELCOME TO MASTERMIND  
                         {END}

How intelligent should the computer be? 
With a higher intelligence level, the computer will 'think' for longer,
but will take less guesses to find the answer.
If you have chosen more than 6 colours or 5 spaces,
maximum of level 2 is recommended.
Otherwise, level 3 should be fine.
So, how intelligent should the computer be? (1-3){colours["blue"]}''')

# Loops until valid answer
while True:
    try:
        intelligence = int(input())
        if 3 >= intelligence >= 1:
            break
        else:
            raise ValueError()  # goes to except
    except:
        stdout.write("\033[{0};{1}f".format(11, 45))
        stdout.write(f'{colours["red"]}(1-3){END}')
        stdout.write("\033[{0};{1}f".format(12, 0))
        stdout.write("\033[K")
        stdout.write(colours["blue"])

#########
# RULES #
#########

s('clear')

print(f'''{END}{highlights["red"]}                         
  WELCOME TO MASTERMIND  
                         {END}

I am now going to give you a series of guesses of your code.
You must rate my guesses with the following system:
For every correct colour in the correct position, award me a black peg.
For every correct colour in the wrong position, award me a white peg.
If there are multiple of the same colour in my guess, 
only award me pegs for how many there are in the answer.

Confused? (Y/N){colours["blue"]}''')

# Loops until valid answer
while True:
    confused = input().upper()
    if not (confused == 'Y' or confused == 'N'):
        stdout.write("\033[{0};{1}f".format(12, 11))
        stdout.write(f'{colours["red"]}(Y/N){END}')
        stdout.write("\033[{0};{1}f".format(13, 0))
        stdout.write("\033[K")
        stdout.write(colours["blue"])
    else:
        break

while confused == 'Y':
    s('clear')
    print(f'''{END}{highlights["red"]}                         
  WELCOME TO MASTERMIND  
                         {END}

HELP PAGE

Read more detailed rules online  (type R)
Look at some examples            (type E)
Go back                          (type G)

Choose wisely, but don't worry - you can come back later (R/E/G){colours["blue"]}'''
          )

    # Loops until valid answer
    while True:
        helpChoice = input().upper()
        if not (helpChoice in ['R', 'E', 'G']):
            stdout.write("\033[{0};{1}f".format(11, 58))
            stdout.write(f'{colours["red"]}(R/E/G){END}')
            stdout.write("\033[{0};{1}f".format(12, 0))
            stdout.write("\033[K")
            stdout.write(colours["blue"])
        else:
            break

    if helpChoice == 'R':
        if webbrowser.open(
                "http://www.boardgamecapital.com/game_rules/mastermind.pdf"
        ) == False:
            s('clear')
            print(f'''{END}{highlights["red"]}                         
  WELCOME TO MASTERMIND  
                         {END}

Sorry - tried to open the rules automagically but failed.
You will have to manually copy this link into a new tab!
http://www.boardgamecapital.com/game_rules/mastermind.pdf

Press enter to return to the help page.''')

            input()

    elif helpChoice == 'E':
        answer = '0012'

        s('clear')
        print(f'''{END}{highlights["red"]}                         
  WELCOME TO MASTERMIND  
                         {END}

These examples are for 6 colours and 4 spaces,
but the same rules always apply.
They tell you the number of white and black pegs that would
be awarded for the given guess if this were the answer code:

Answer: ''' + printableGuess(answer))

        for guess in examples:
            print('\nGuess:  ' + printableGuess(guess))
            black, white = awards(guess, answer)
            print('Black:  ' + str(black))
            print('White:  ' + str(white))

        print('''
Press enter to return to the help page.''')

        input()

    else:
        confused = 'N'

s('clear')
print(f'''{END}{highlights["red"]}                         
  WELCOME TO MASTERMIND  
                         {END}

Remember to follow the rules when scoring my guesses.
If you don't, the algorithm won't work!

Press enter when ready to continue.''')

input()

########
# GAME #
########

go = 0
playing = True
guess = '001122' [:nSpaces]

while playing:

    s('clear')
    print(
        f'''{END}{highlights["red"]}                         
  WELCOME TO MASTERMIND  
                         {END}

Current number of possibilities: {len(S)}

Guess {go+1}:  ''',
        end='')
    print(printableGuess(guess))

    # Gets number of black pegs
    print(f'''
How many black pegs - correct colour and in the correct space? (0-{nSpaces}){colours["blue"]}''')
    while True:
        try:
            awardedBlack = int(input())
            if nSpaces >= awardedBlack >= 0:
                break
            else:
                raise ValueError()  # goes to except
        except:
            stdout.write("\033[{0};{1}f".format(9, 64))
            stdout.write(f'{colours["red"]}(0-{nSpaces}){END}')
            stdout.write("\033[{0};{1}f".format(10, 0))
            stdout.write("\033[K")
            stdout.write(colours["blue"])

    if awardedBlack == nSpaces:
        break

    elif awardedBlack != nSpaces - 1:
        maxW = nSpaces - awardedBlack

        # Gets number of white pegs
        print(f'''{END}
How many white pegs - correct colour but in the wrong space? (0-{maxW}){colours["blue"]}''')

        while True:
            try:
                awardedWhite = int(input())
                if maxW >= awardedWhite >= 0:
                    break
                else:
                    raise ValueError()  # goes to except
            except:
                stdout.write("\033[{0};{1}f".format(12, 62))
                stdout.write(f'{colours["red"]}(0-{maxW}){END}')
                stdout.write("\033[{0};{1}f".format(13, 0))
                stdout.write("\033[K")
                stdout.write(colours["blue"])

    else:
        awardedWhite = 0

    print(f'''{END}
Calculating next guess...

Estimating time remaining...
''')

    # Eliminates all possibles that would not award the same result if they were the answer
    passed = []
    for pos in S:
        if awards(guess, pos) == [awardedBlack, awardedWhite]:
            passed.append(pos)
    S = passed[:]

    # End if no possibilities left
    if len(S) == 0:
        s('clear')
        print(f'''{END}{highlights["red"]}                         
  WELCOME TO MASTERMIND  
                         {END}

Current number of possibilities: {colours["red"]}0{END}

Oh dear, there aren't any possibilities left!
Not meaning to be cocky, but you must have gone wrong!
Please restart the program to try again.''')
        quit()

    # End if only one possibility left
    elif len(S) == 1:
        s('clear')
        print(f'''{END}{highlights["red"]}                         
  WELCOME TO MASTERMIND  
                         {END}

Current number of possibilities: {colours["green"]}1{END}

Answer:   {printableGuess(S[0])}

Correct? (Y/N){colours["blue"]}''')
        while True:
            try:
                correct = input().upper()
                if correct == 'Y' or correct == 'N':
                    break
                else:
                    raise ValueError()  # goes to except
            except:
                stdout.write("\033[{0};{1}f".format(9, 10))
                stdout.write(f'{colours["red"]}(Y/N){END}')
                stdout.write("\033[{0};{1}f".format(10, 0))
                stdout.write("\033[K")
                stdout.write(colours["blue"])

        if correct == 'N':
            s('clear')
            print(f'''{END}{highlights["red"]}                         
  WELCOME TO MASTERMIND  
                         {END}

DOH! Sorry to disappoint...
If you're sure you entered all the right black/white peg numbers,
send a comment [here], giving the number of colours and spaces
as well as the answer code, and I'll look into it. Thanks!''')
        else:
            break

        quit()

    # The complicated bit
    # Chooses the best next guess

    if (len(S) < 1000 and intelligence != 1) or intelligence == 3:
        scores = {}
        displayP = -1
        startTime = time()
        prevEstimate = 99999999999999999
        length = len(S)
        for posGuess in S:
            responses = {}
            for posAns in S:
                response = tuple(awards(posGuess,
                                        posAns))  # can't use lists as indexes
                try:
                    responses[response] += 1
                except:
                    responses[response] = 1
            scores[posGuess] = max(responses.values())

            # Updates % on screen
            currentP = round((S.index(posGuess) / length) * 100)
            if currentP > displayP:
                displayP = currentP
                stdout.write("\033[{0};{1}f".format(15, 27))
                stdout.write(f'{displayP}%')
                stdout.write("\033[{0};{1}f".format(19, 0))

            # Updates estimated time remaining on screen
            howFarThrough = S.index(posGuess)
            try:
                estimatedRemaining = round(
                    (((time() - startTime) / howFarThrough) *
                     (length - howFarThrough)))
                if estimatedRemaining < prevEstimate:
                    stdout.write("\033[{0};{1}f".format(17, 0))
                    stdout.write("\033[K")
                    stdout.write(
                        f'Estimated {estimatedRemaining} seconds remaining ')
                    stdout.write("\033[{0};{1}f".format(19, 0))
                    prevEstimate = estimatedRemaining
            except ZeroDivisionError:  # doesn't happen first time
                pass

        try:
            best = min(scores.values())
            guess = choice([
                posGuess for posGuess in scores.keys()
                if scores[posGuess] == best
            ])
        except ValueError:
            continue
    else:
        guess = choice(S)

    go += 1

#############
# POST-GAME #
#############

s('clear')
print(f'''{END}{highlights["red"]}                         
  WELCOME TO MASTERMIND  
                         {END}

Woo hoo! Got it right in just {go+1} guesses!
To play again, simply restart the program (reload the page).
Want to know how it works? Go here:
https://en.wikipedia.org/wiki/Mastermind_(board_game)#Five-guess_algorithm''')
?