Reputation: 49
I have an assignment for a programming unit that asks this:
create the function enclosing(board, player, pos, direct), that represents the rules of Reversi according to the following specifications.
A board position is represented by a pair (r, c) where r and c are each integers from the range range(8) representing a row index and a column index, respectively. For instance, the position \b3" is represented by (2, 1). The row and column order of the \b3" style and the specication of position is reversed. This is because it is natural to constuct lists of lists in such a way that the outer lists correspond to rows, and the inner list positions corerspond to column positions, so we reference them with row rst, then column. This row, column convention is quite common across maths and computer science.
A direction is represented by a pair (dr, dc) where dr and dc are each integers from the set f-1, 0, 1g. For instance, \horizontal to the left" is described by (0, -1), \diagonal to the right and down" is described by (1, 1), and so on).
The function enclosing(board, player, pos, dir) represents whether putting a player's stone on a given position would enclose a straight line of opponent's stones in a given direction:
Input: A board conguration board, an integer player from the set f1, 2g, a board position pos and a direction dir.
Output: True if board contains a stone of player in direction dir from position pos and all positions on the straight line between that stone and pos contain stones of the other player, and there is at least one stone belonging to the other player on the straight line; False otherwise.
This is what I have:
def enclosing(board, player, pos, direct):
if player == 1:
a = direct[0]
b = direct[1]
i = 1
while i < 8:
newpos = (pos[0] + i*a , pos[1] + i*b)
if board[newpos[0]][newpos[1]] == 1:
return True
elif board[newpos[0]][newpos[1]] == 2:
i = i + 1
else:
return False
Also keep in mind this is a beginners course and I have about a months experience on python.
Upvotes: 0
Views: 299
Reputation: 2497
The code in your edit looks good, and is what I was getting at. Good luck with the rest of the project!
A couple edge cases:
board[newpos[0]][newpos[1]]
will go out of boundsXOOOOX
, which is not a capture by Othello rules (not sure if your assignment defines it differentlyI strongly recommend writing a couple simple tests just to make sure your code works. They don't need to cover the full range of cases, and doesn't need to be the full board. It's usually not required, but makes it easier to evaluate: just hit "run" instead of trying to reason through your code.
Here's an example:
def test():
assert enclosing([[0, 0, 0], [0,0,0],[0,1,2]], 1, (0,2), (1,1)) == True
Upvotes: 0