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

tictactoe3

parent c6474aa3
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 = winningIndexes[i][0]
win_index2 = winningIndexes[i][1]
win_index3 = winningIndexes[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 = []
if isWinningState(state) == "X" or isWinningState(state) == "O":
return 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
def makeNextMoves(state, nodeId):
global nextId
nextMoves = getNextMoves(state)
for nextMove in nextMoves:
nextId += 1
G.add_node(nextId, state = nextMove)
G.add_edge(nodeId, nextId)
makeNextMoves(nextMove, nextId)
```
%% Cell type:code id: tags:
``` python
G = nx.DiGraph()
nextId = 1
initState = ["X", "-", "-", "-", "O", "-", "-", "-", "-"]
G.add_node(nextId, state = initState)
makeNextMoves(initState, nextId)
```
%% 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