Skip to content

Instantly share code, notes, and snippets.

@gylaz
Created May 17, 2014 02:11
Show Gist options
  • Save gylaz/d0a4545209e6d9c175be to your computer and use it in GitHub Desktop.
Save gylaz/d0a4545209e6d9c175be to your computer and use it in GitHub Desktop.
Tic Tac Toe game in Elixirc
defmodule TicTacToe do
require Integer
defmodule X do end
defmodule Y do end
defmodule Grid do
defstruct turns: 0, cells: Enum.map(1..9, fn(_) -> nil end)
end
def place(%Grid{turns: turns}, X, _) when Integer.odd?(turns) do
{:error, "out of turn token"}
end
def place(grid, token, position) do
if nil?(Enum.fetch!(grid.cells, position)) do
grid = %Grid{
grid | turns: + 1, cells: List.replace_at(grid.cells, position, token)
}
{:ok, grid}
else
{:error, "cell is occupied"}
end
end
def winner(grid) do
rows = Enum.chunk(grid.cells, 3)
columns = Enum.map(0..2,
fn(i) -> Enum.slice(grid.cells, i+3, 1) end
)
IO.inspect columns
diagonals = []
winner_in_cells(rows) || winner_in_cells(columns) || winner_in_cells(diagonals)
end
def winner_in_cells(cell_groups) do
match = Enum.find(
cell_groups,
fn(cells) ->
result = Enum.uniq(cells)
Enum.count(result) == 1 && List.first(result) != nil
end
)
if match do
List.first(match)
else
nil
end
end
end
defmodule TicTacToe do
require Integer
defmodule X do end
defmodule Y do end
defmodule Grid do
defstruct turns: 0, cells: Enum.map(1..9, fn(_) -> nil end)
end
def place(%Grid{turns: turns}, X, _) when Integer.odd?(turns) do
{:error, "out of turn token"}
end
def place(grid, token, position) do
if nil?(Enum.fetch!(grid.cells, position)) do
grid = %Grid{
grid | turns: + 1, cells: List.replace_at(grid.cells, position, token)
}
{:ok, grid}
else
{:error, "cell is occupied"}
end
end
def winner(grid) do
rows = Enum.chunk(grid.cells, 3)
columns = Enum.map(0..2,
fn(i) -> Enum.slice(grid.cells, i+3, 1) end
)
IO.inspect columns
diagonals = []
winner_in_cells(rows) || winner_in_cells(columns) || winner_in_cells(diagonals)
end
def winner_in_cells(cell_groups) do
match = Enum.find(
cell_groups,
fn(cells) ->
result = Enum.uniq(cells)
Enum.count(result) == 1 && List.first(result) != nil
end
)
if match do
List.first(match)
else
nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment