Attachment 'konrad_todd_tdd_dojo.py'
Download
Toggle line numbers
1 from nose.tools import assert_equals
2
3 def legal_moves(board, player):
4 """
5 Given a board encoded as a list of strings and a player char
6 returns pairs identifying positions of legal moves for given player
7 and given situation on the board.
8 """
9 all_directions = [(-1, -1), (-1, 0), (-1, 1),
10 (0, -1), (0, 1),
11 (1, -1), (1, 0), (1, 1)]
12 moves = []
13 for pos in find_pieces(board, player):
14 for direction in all_directions:
15 new_move = check_direction(board, pos, direction)
16 if new_move is not None:
17 moves.append(new_move)
18 return moves
19
20 def find_pieces(board, player):
21 """ find all coords for the player piece. """
22 coords = []
23 for i in range(len(board)):
24 for j in range(len(board)):
25 if board[i][j] == player:
26 coords.append((i, j))
27 return coords
28
29 def check_direction(board, start, direction):
30 enemy = {"b": "w", "w": "b"}
31 row, col = start
32 delta_r, delta_c = direction
33 found_enemy = False
34 player = board[start[0]][start[1]]
35 while True:
36 row, col = row + delta_r, col + delta_c
37 if row >= len(board) or col >= len(board[0]):
38 return None
39 if board[row][col] == enemy[player]:
40 found_enemy = True
41 if board[row][col] == '.' and found_enemy:
42 return (row, col)
43 if board[row][col] == '.' and not found_enemy:
44 return None
45 if board[row][col] == player:
46 return None
47
48 TEST_BOARD = ["....",
49 ".bw.",
50 ".wb.",
51 "...."]
52
53 def test_simple():
54 assert_equals(legal_moves(TEST_BOARD, 'w'), [(1, 0), (3, 2), (0, 1), (2, 3)])
55
56 def test_find_pieces():
57 assert_equals(find_pieces(TEST_BOARD, 'b'), [(1, 1), (2, 2)],
58 find_pieces(TEST_BOARD, 'b'))
59
60 def test_check_direction():
61 assert_equals(check_direction(TEST_BOARD, (1, 1), (0, 1)), (1, 3))
62 assert_equals(check_direction(TEST_BOARD, (1, 1), (-1, 0)), None)
63 assert_equals(check_direction(TEST_BOARD, (1, 1), (0, 0)), None)
64
65 TEST_BOARD2 = ['bww']
66
67 def test_check_border():
68 assert_equals(check_direction(TEST_BOARD2, (0,0), (0, 1)), None)
Attached Files
To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.You are not allowed to attach a file to this page.