Attempted Java solution from newbie
From Beautifulcode
Revision as of 17:45, 12 August 2007; view current revision
←Older revision | Newer revision→
←Older revision | Newer revision→
(a) Why you believe your solution works ? I've tried my best to synchronize the parent-thread communication
(b) What makes it beautiful ? Not sure about this one :) Will leave it for others to judge.
public abstract class IPlayScrabble extends Thread{
volatile boolean takeNewTile = false;
volatile boolean addingWord = false;
int MAX_TILES;
int[][] board;
char[] tiles;
int lastOpenTile, initialOpenCount;
Object[] wordPos; //data structure for current word and its position
Object parent;
//Subclasses should implement this method. keep checking takeNewTile regularly
abstract protected Object[] findWordAndPosition(int[][] board, char[] tiles);
public void takeTile(){
takeNewTile = true;
openNextTile();
takeNewTile = false;
}
IPlayScrabble(int[][] board, char[] tiles, int initialOpenCount, int maxTiles, Object parent){
this.board = board;
this.tiles = tiles;
this.MAX_TILES = maxTiles;
this.lastOpenTile = initialOpenCount;
this.initialOpenCount = initialOpenCount;
this.parent = parent;
}
public void run(){
while(MAX_TILES - lastOpenTile > 0){
if(!takeNewTile){
Object[] wordPos = calculateWords();
synchronized(this){
if(wordPos != null){
if(lastOpenTile >= initialOpenCount){
parent.notify();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
private Object[] calculateWords(){
char[] copy = new char[lastOpenTile];
System.arraycopy(tiles, 0, copy, 0, lastOpenTile);
if(!takeNewTile){
wordPos = findWordAndPosition(board, copy);
}
addingWord = true;
addWord();
if(takeNewTile){
undoAddWord();
wordPos = null;
synchronized(this){
lastOpenTile--;
}
}else{
openNextTile();
}
addingWord = false;
return wordPos;
}
private void openNextTile(){
synchronized(this){
lastOpenTile++;
}
}
private void addWord(){
//update the board with the new word
}
private void undoAddWord(){
//remove the last added word from the board
}
}
