Repository navigation
Expand file tree
/
Copy pathplayer.py
More file actions
84 lines (67 loc) · 2.49 KB
/
Copy pathplayer.py
File metadata and controls
84 lines (67 loc) · 2.49 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
# player for tic-tac-toe game
import math
import random
class Player():
def __init__(self, letter):
self.letter = letter # letter is x or o
#all players get their next move
def get_move(self, game):
pass
class RandomComputerPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def get_move(self, game):
square = random.choice(game.available_moves())
return square
class HumanPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def get_move(self, game):
valid_square = False
val = None
while not valid_square:
square = input(self.letter + "'s turn. Input move (0-8): ")
try:
val = int(square)
if val not in game.available_moves():
raise ValueError
valid_square = True
except ValueError:
print("Invalid Square. Try Again.")
return val
class GeniusComputerPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def get_move(self, game):
if len(game.available_moves()) == 9:
square = random.choice(game.available_moves())
else:
square = self.minimax(game, self.letter)["position"]
return square
def minimax(self, state, player):
max_player = self.letter
other_player = "O" if player == "X" else "X"
if state.current_winner == other_player:
return {"position": None,
"score": 1 * (state.num_empty_squares() + 1) if other_player == max_player else -1 * (
state.num_empty_squares() + 1)
}
elif not state.empty_squares():
return {"position": None, "score": 0}
if player == max_player:
best = {"position": None, "score": -math.inf}
else:
best = {"position": None, "score": math.inf}
for possible_move in state.available_moves():
state.make_move(possible_move, player)
sim_score = self.minimax(state, other_player)
state.board[possible_move] = " "
state.current_winner = None
sim_score["position"] = possible_move
if player == max_player:
if sim_score["score"] > best["score"]:
best = sim_score
else:
if sim_score["score"] < best["score"]:
best = sim_score
return best