-
Notifications
You must be signed in to change notification settings - Fork 0
/
mastermind.py
79 lines (55 loc) · 1.85 KB
/
mastermind.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
import random
COLORS = ['R', 'G', 'B', 'Y', 'W', 'O']
TRIES = 10
CODE_LENGTH = 4
def generate_code():
code = []
for _ in range(CODE_LENGTH):
color = random.choice(COLORS)
code.append(color)
return code
def guess_code():
while True:
guess = input('Guess: ').upper().split(' ')
if len(guess) != CODE_LENGTH:
print(f'You must guess {CODE_LENGTH} colors.')
continue
for color in guess:
if color not in COLORS:
print(f'Invalid color: {color}. Try again.')
break
else:
break
return guess
def check_code(guess, real_code):
color_counts = {}
correct_pos = 0
incorrect_pos = 0
for color in real_code:
if color not in color_counts:
color_counts[color] = 0
color_counts[color] += 1
for guess_color, real_color in zip(guess, real_code):
if guess_color == real_color:
correct_pos += 1
color_counts[guess] -= 1
for guess_color, real_color in zip(guess, real_code):
if guess_color in color_counts and color_counts[guess_color] > 0:
incorrect_pos += 1
color_counts[guess_color] -= 1
return correct_pos, incorrect_pos
def game():
print(f'Welcome to Mastermind,you have {TRIES} to guess the code.')
print('The valid colors are', *COLORS)
code = generate_code()
for attempts in range(1, TRIES + 1):
guess = guess_code()
correct_pos, incorrect_pos = check_code(guess, code)
if correct_pos == CODE_LENGTH:
print(f'You guessed the code in {attempts} trials!')
break
print(f'Correct Positions: {correct_pos} | Incorrect Position: {incorrect_pos}')
else:
print('You ran out of tries,the code was', *code)
if __name__ == '__main__':
game()