Attachment 'todd_gijs_reversi.py'
Download
Toggle line numbers
1 directions = [(-1, -1), (-1, 0), (-1, 1),
2 (0, -1), (0, 1),
3 (1, -1 ), (1, 0), (1, 1)]
4
5 switch = { 'b': 'w', 'w': 'b'}
6
7
8 def legal_moves(board, player):
9 stones = find_pieces(board, player)
10 moves = []
11 for stone in stones:
12 moves += (find_valid_paths(board, stone))
13 return set(moves)
14
15
16 def find_pieces(board, colour):
17 l = []
18 for (i, col) in enumerate(board):
19 for (j, row) in enumerate(col):
20 if row == colour:
21 l.append((i,j))
22 return set(l)
23
24
25 def check_direction(board, start, direction):
26 (row, col) = start
27 me = board[row][col]
28
29 if me == ".":
30 return
31
32 other = switch[me]
33 between = False
34
35 while True:
36 row += direction[0]
37 col += direction[1]
38
39 if row < 0 or col < 0 or row > len(board)-1 or col > len(board[0])-1:
40 break
41
42 checked = board[row][col]
43
44 if checked == other:
45 between = True
46 continue
47 elif checked == "." and between:
48 return (row, col)
49 else:
50 return
51
52
53 def find_valid_paths(board, position):
54 coords = []
55 for direction in directions:
56 result = check_direction(board, position, direction)
57 if result:
58 coords.append(result)
59 return set(coords)
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.