Skip to content
Snippets Groups Projects
Commit e345926f authored by Wade Fagen-Ulmschneider (waf)'s avatar Wade Fagen-Ulmschneider (waf)
Browse files

tictactoe day2

parent ea14e36f
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
## Tic-tac-toe
Using graphs, we will explore the state space of a game of tic-tac-toe!
%% Cell type:code id: tags:
``` python
import networkx as nx
```
%% Cell type:code id: tags:
``` python
def isWinningState(state):
winningIndexes = [
# Horz
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
# Vert
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
# Diag
[0, 4, 8],
[2, 4, 6]
]
for i in range(len(winningIndexes)):
win_index1 = winningIndex[i][0]
win_index2 = winningIndex[i][1]
win_index3 = winningIndex[i][2]
if state[win_index1] == state[win_index2] and \
state[win_index2] == state[win_index3]:
if state[win_index1] == "X":
# X is the winner
return "X"
elif state[win_index1] == "O":
# O is the winner
return "O"
return "-"
```
%% Cell type:code id: tags:
``` python
def getNextPlayer(state):
x_ct = 0
o_ct = 0
for i in range(len(state)):
if state[i] == "X":
x_ct += 1
if state[i] == "O":
o_ct += 1
if x_ct == o_ct:
return "X"
else:
return "O"
```
%% Cell type:code id: tags:
``` python
def getNextMoves(state):
nextStates = []
nextPlayer = getNextPlayer(state)
for i in range(len(state)):
if state[i] == "-":
nextState = list(state) # makes a copy of the list
nextState[i] = nextPlayer
nextStates.append(nextState)
return nextStates
```
%% Cell type:code id: tags:
``` python
G = nx.DiGraph()
initState = ["X", "X", "X", "O", "O", "-", "-", "O", "-"]
G.add_node(str(initState), state=initState)
nextMoves = getNextMoves(initState)
nextMoves
```
%% Output
[['X', 'X', 'X', 'O', 'O', 'X', '-', 'O', '-'],
['X', 'X', 'X', 'O', 'O', '-', 'X', 'O', '-'],
['X', 'X', 'X', 'O', 'O', '-', '-', 'O', 'X']]
%% Cell type:code id: tags:
``` python
import json
with open("../res/tree.json", "w") as f:
from networkx.readwrite import json_graph
data = json_graph.tree_data(G, root=1)
json.dump(data, f, indent=2)
```
%% Cell type:code id: tags:
``` python
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment