Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions aima/games.py
Original file line number Diff line number Diff line change
Expand Up @@ -466,8 +466,8 @@ def terminal_test(self, state):
def display(self, state):
"""Print the board as a grid, with empty squares shown as dots."""
board = state.board
for x in range(1, self.h + 1):
for y in range(1, self.v + 1):
for y in range(1, self.v + 1):
for x in range(1, self.h + 1):
print(board.get((x, y), '.'), end=' ')
print()

Expand Down Expand Up @@ -508,7 +508,8 @@ def __init__(self, h=7, v=6, k=4):
def actions(self, state):
"""Return legal moves: bottom-row squares or squares directly above an occupied one."""
return [(x, y) for (x, y) in state.moves
if x == self.h or (x + 1 , y ) in state.board]
if y == self.v or (x, y + 1) in state.board]


class Gomoku(TicTacToe):
"""Also known as Five in a row."""
Expand Down
22 changes: 22 additions & 0 deletions tests/test_games.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,5 +92,27 @@ def test_random_tests():
assert ttt.play_game(alpha_beta_player, random_player) >= 0


def test_ttt_display_dimensions():
"""display prints v rows of h squares, for square and rectangular boards."""
import io
from contextlib import redirect_stdout

dimensions = {TicTacToe(): (3, 3),
TicTacToe(h=7, v=5): (7, 5),
TicTacToe(h=5, v=7): (5, 7),
ConnectFour(): (7, 6)}
for game, (h, v) in dimensions.items():
output = io.StringIO()
with redirect_stdout(output):
game.display(game.initial)
assert output.getvalue() == ('. ' * h + '\n') * v
# Connect Four drops pieces from the top: the first legal moves are the
# 7 squares of the bottom row, and a piece there opens the square above it
c4 = ConnectFour()
assert sorted(c4.actions(c4.initial)) == [(x, 6) for x in range(1, 8)]
state = c4.result(c4.initial, (4, 6))
assert (4, 5) in c4.actions(state) and (4, 4) not in c4.actions(state)


if __name__ == "__main__":
pytest.main()