-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmastermindAI.py
More file actions
86 lines (68 loc) · 2.38 KB
/
mastermindAI.py
File metadata and controls
86 lines (68 loc) · 2.38 KB
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
from mastermind import Mastermind
import numpy as np
class MastermindAI():
def __init__(self):
self.board = Mastermind(size=4, min_value=1, max_value=3)
self.board_size = self.board.size
self.min = 1
self.max = 9
self.known = {}
self.existed = set()
self.cannot = {
i: set()
for i in range(self.board_size)
}
self.not_existed = set()
def set_board(self, board):
self.board = board
self.board_size = board.size
def make_guess(self):
"""
Make a guess based on current knowledge
"""
guess = [0] * self.board_size
for i in range(self.board_size):
possible_values = []
#If a position is known to be correct:
if i in self.known:
guess[i] = self.known[i]
#If not, check for other conditions
else:
for value in range(self.min, self.max + 1):
if value in self.cannot[i] or value in self.not_existed:
pass
else:
possible_values.append(value)
#Make a random choice from the possible values
guess[i] = np.random.choice(possible_values)
return guess
def solve(self):
turn = 0
guesses = []
print("The board: ", self.board.board)
done = False
while not done:
guess = self.make_guess()
guesses.append(guess)
print(f"The AI guesses: {guess}")
#Check for results
results = self.board.check(guess)
print(f"The results the AI gets: {results}")
if np.all(results == ([2] * self.board_size)):
done = True
pass
#Append new knowledge
for i, result in enumerate(results):
if result == 2:
self.known[i] = guess[i]
self.existed.add(guess[i])
elif result == 1:
self.existed.add(guess[i])
self.cannot[i].add(guess[i])
else:
self.not_existed.add(guess[i])
return guesses
if __name__ == "__main__":
board = Mastermind(size=4, min_value=1, max_value=4)
AI = MastermindAI(board)
AI.solve()