HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Gameboard checking stones in all directions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stonesallcheckinggameboarddirections

Problem

I am creating a game called Othello, the objective of the game is to close in your opponent's stones either horizontally, vertically or diagonally. All the stones that get closed in are then turned to your color. Win the game by having the most stones of your color.

Small example:

b = black
w = white
0 = empty space

0 0 b w
0 b w 0
0 w b 0
0 0 0 0


Placing a white stone (.w) will turn the 2 black stones to white.

0 .w w w
0 w w 0
0 w b 0
0 0 0 0


I have made a big mess while trying to find all the stones that need to be turned in a way that I made a method for every direction to find the stones.
All found stones that are considered closed in are then added to a single ArrayList and then turned over by another method. Besides a few small details like coordinate difference and the counter that makes the coordinates move, the code is pretty alike. But I'm struggling to find a good way to refactor it in a decent structure.

```
private void checkLeft(Bord bord) {
boolean lineIsClosedIn = false;
ArrayList squaresLeft = new ArrayList<>();
for (int i = this.getPositie().getPosX() - 1; i >= 0; i--) {
Coordinate co = new Coordinate(i, this.getPositie().getPosY());
Square sq = bord.getSquareAtLoction(co);
if (sq.isTaken()) {
if (sq.getStone().getColor() == this.getStone().getColor()) {
lineIsClosedIn = true;
} else {
squaresLeft.add(co);
}

}

}
if (lineIsClosedIn) {
squaresToTurn.addAll(squaresLeft);
}
}

private void checkRight(Bord bord) {
boolean lineIsClosedIn = false;
ArrayList squaresLeft = new ArrayList<>();
for (int i = (this.getPositie().getPosX() + 1); i squaresLeft = new ArrayList<>();
for (int i = this.getPositie().getPosY() - 1; i >= 0; i--) {
Coordinate co = new Coordinate(this.getPositie().getP

Solution

-
Correctness. The loop may turn too many stones. You should break the loop as soon as it encounters a square not taken by the other color. Otherwise, in the positions like

W.b.w; Wwb; etc


(W is the last move) the black stone gets reversed.

-
Refactoring. Make a helper

private void checkInDirecton(Bord bord, int dx, int dy)


It looks exactly like your check functions, except that loop variables are incremented as

x += dx, y += dy


Now call it as

checkLeft(Board bord) {
    checkInDirection(bord, -1, 0);
}


etc.

Code Snippets

W.b.w; Wwb; etc
private void checkInDirecton(Bord bord, int dx, int dy)
x += dx, y += dy
checkLeft(Board bord) {
    checkInDirection(bord, -1, 0);
}

Context

StackExchange Code Review Q#85243, answer score: 5

Revisions (0)

No revisions yet.