|
1 | 1 | defmodule Connect do |
2 | 2 | @doc """ |
3 | 3 | Calculates the winner (if any) of a board |
4 | | - using "O" as the white player |
5 | | - and "X" as the black player |
6 | 4 | """ |
7 | | - @spec result_for([String.t()]) :: :none | :black | :white |
| 5 | + @spec result_for([String.t()]) :: :none | :X | :O |
8 | 6 | def result_for(board) do |
9 | 7 | cond do |
10 | | - black_wins?(board) -> :black |
11 | | - white_wins?(board) -> :white |
| 8 | + x_wins?(board) -> :X |
| 9 | + o_wins?(board) -> :O |
12 | 10 | true -> :none |
13 | 11 | end |
14 | 12 | end |
15 | 13 |
|
16 | | - defp black_wins?(board) do |
| 14 | + defp x_wins?(board) do |
17 | 15 | board |
18 | 16 | |> Enum.with_index() |
19 | 17 | |> Enum.any?(fn {row, index} -> |
20 | | - String.first(row) == "X" && black_wins?(board, [{index, 0}]) |
| 18 | + String.first(row) == "X" && x_wins?(board, [{index, 0}]) |
21 | 19 | end) |
22 | 20 | end |
23 | 21 |
|
24 | | - defp black_wins?(board, [{_, y} | _]) when y + 1 == byte_size(hd(board)), do: true |
| 22 | + defp x_wins?(board, [{_, y} | _]) when y + 1 == byte_size(hd(board)), do: true |
25 | 23 |
|
26 | | - defp black_wins?(board, history = [last_loc | _]) do |
| 24 | + defp x_wins?(board, history = [last_loc | _]) do |
27 | 25 | last_loc |
28 | 26 | |> locs_next_to(history) |
29 | 27 | |> Enum.filter(&(get_loc(board, &1) == "X")) |
30 | | - |> Enum.any?(&black_wins?(board, [&1 | history])) |
| 28 | + |> Enum.any?(&x_wins?(board, [&1 | history])) |
31 | 29 | end |
32 | 30 |
|
33 | | - defp white_wins?(board) do |
| 31 | + defp o_wins?(board) do |
34 | 32 | board |
35 | 33 | |> hd |
36 | 34 | |> String.graphemes() |
37 | 35 | |> Enum.with_index() |
38 | 36 | |> Enum.any?(fn {spot, index} -> |
39 | | - spot == "O" && white_wins?(board, [{0, index}]) |
| 37 | + spot == "O" && o_wins?(board, [{0, index}]) |
40 | 38 | end) |
41 | 39 | end |
42 | 40 |
|
43 | | - defp white_wins?(board, [{x, _} | _]) when x + 1 == length(board), do: true |
| 41 | + defp o_wins?(board, [{x, _} | _]) when x + 1 == length(board), do: true |
44 | 42 |
|
45 | | - defp white_wins?(board, history = [last_loc | _]) do |
| 43 | + defp o_wins?(board, history = [last_loc | _]) do |
46 | 44 | last_loc |
47 | 45 | |> locs_next_to(history) |
48 | 46 | |> Enum.filter(&(get_loc(board, &1) == "O")) |
49 | | - |> Enum.any?(&white_wins?(board, [&1 | history])) |
| 47 | + |> Enum.any?(&o_wins?(board, [&1 | history])) |
50 | 48 | end |
51 | 49 |
|
52 | 50 | defp locs_next_to({x, y}, history) do |
|
0 commit comments