|
| 1 | +-module( langton ). |
| 2 | +-include_lib( "eunit/include/eunit.hrl" ). |
| 3 | +-export( [ step/2 ] ). |
| 4 | + |
| 5 | +%% Install erlang from http://www.erlang.org/ (or use your package manager) |
| 6 | + |
| 7 | +%% In order to run tests use: |
| 8 | +%% $ erlc langton.erl && erl -noshell -eval "eunit:test(langton, [verbose])" -s init stop |
| 9 | + |
| 10 | +flip( white ) -> black; |
| 11 | +flip( black ) -> white. |
| 12 | + |
| 13 | +rotate( black, east ) -> north; |
| 14 | +rotate( black, south ) -> east; |
| 15 | +rotate( black, west ) -> south; |
| 16 | +rotate( black, north ) -> west; |
| 17 | + |
| 18 | +rotate( white, north ) -> east; |
| 19 | +rotate( white, east ) -> south; |
| 20 | +rotate( white, south ) -> west; |
| 21 | +rotate( white, west ) -> north. |
| 22 | + |
| 23 | +move( { X, Y }, north ) -> { X, Y + 1 }; |
| 24 | +move( { X, Y }, east ) -> { X + 1, Y }; |
| 25 | +move( { X, Y }, south ) -> { X, Y - 1 }; |
| 26 | +move( { X, Y }, west ) -> { X - 1, Y }. |
| 27 | + |
| 28 | + |
| 29 | +flip_test() -> |
| 30 | + ?assertMatch( white, flip( black ) ), |
| 31 | + ?assertMatch( black, flip( white ) ). |
| 32 | + |
| 33 | +rotates_left_on_black_test() -> |
| 34 | + ?assertMatch( north, rotate( black, east ) ), |
| 35 | + ?assertMatch( east, rotate( black, south ) ), |
| 36 | + ?assertMatch( south, rotate( black, west ) ), |
| 37 | + ?assertMatch( west, rotate( black, north ) ). |
| 38 | + |
| 39 | +rotates_right_on_white_test() -> |
| 40 | + ?assertMatch( east, rotate( white, north ) ), |
| 41 | + ?assertMatch( south, rotate( white, east ) ), |
| 42 | + ?assertMatch( west, rotate( white, south ) ), |
| 43 | + ?assertMatch( north, rotate( white, west ) ). |
| 44 | + |
| 45 | +moves_in_direction_test() -> |
| 46 | + ?assertMatch( { 1, 1 }, move( { 1, 0 }, north ) ), |
| 47 | + ?assertMatch( { 1, 0 }, move( { 0, 0 }, east ) ), |
| 48 | + ?assertMatch( { 0, 0 }, move( { 0, 1 }, south ) ), |
| 49 | + ?assertMatch( { 0, 0 }, move( { 1, 0 }, west ) ), |
| 50 | + ?assertMatch( { 1, 1 }, move( { 2, 1 }, west ) ). |
| 51 | + |
| 52 | +%% At a white square, turn 90° right, flip the color of the square, move forward one unit |
| 53 | +%% At a black square, turn 90° left, flip the color of the square, move forward one unit |
| 54 | + |
| 55 | +step( Color, { Position, Orientation } ) -> |
| 56 | + NewOrientation = rotate( Color, Orientation ), |
| 57 | + { flip( Color ), { move( Position, NewOrientation ), NewOrientation } }. |
| 58 | + |
| 59 | + |
| 60 | +ant_obeys_rules_test() -> |
| 61 | + ?assertMatch( |
| 62 | + { _Color = white, _Ant = { { 0, 0 }, north } }, |
| 63 | + step( black, { { 0, -1 }, east } ) ), |
| 64 | + ?assertMatch( |
| 65 | + { black, { { 0, 0 }, south } }, |
| 66 | + step( white, { { 0, 1 }, east } ) ). |
0 commit comments