HolonJ Forth
Using HolonJ
Clock
Tic Tac Toe

Java
Forth

Tic Tac Toe Applet

This applet is distributed with Sun's JDK 1.1 Java development kit. I have reprogrammed the applet in HolonJ for a comparison of Java and Forth source text.

Java version HolonJ version
Java source Forth source

Calculating the computer's move in Java.

     /**
     * Compute the best move for white.
     * @return the square to take
     */
    int bestMove(int white, int black) {
	int bestmove = -1;
	
      loop:
	for (int i = 0 ; i < 9 ; i++) {
	    int mw = moves[i];
	    if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) {
		int pw = white | (1 << mw);
		if (won[pw]) {
		    // white wins, take it!
		    return mw;
		}
		for (int mb = 0 ; mb < 9 ; mb++) {
		    if (((pw & (1 << mb)) == 0) && ((black & (1 << mb)) == 0)) {
			int pb = black | (1 << mb);
			if (won[pb]) {
			    // black wins, take another
			    continue loop;
			}
		    }
		}
		// Neither white nor black can win in one move, this will do.
		if (bestmove == -1) {
		    bestmove = mw;
		}
	    }
	}
	if (bestmove != -1) {
	    return bestmove;
	}

	// No move is totally satisfactory, try the first one that is open
	for (int i = 0 ; i < 9 ; i++) {
	    int mw = moves[i];
	    if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) {
		return mw;
	    }
	}

	// No more moves
	return -1;
    }     

Calculating the computer's move in HolonJForth.

: bitpos   ( int b -- int )
     1 b <<  ; 
i: isFree   ( int m -- boolean )
     m bitpos white and 0 = m bitpos black and 0 = and  ; 


\ Returns true if move m makes white win. 
i: whiteWins   ( int m -- boolean )
     m bitpos white or won  ; 


\ Returns true if move m gives black a chance to win. 
i: blackWins   ( int m -- boolean )
     int pw  m bitpos white or =: pw
     9 0 do 
          i bitpos pw and 0 = i bitpos black and 0 = and 
          if  i bitpos black or won if true return then  then
     loop 
     false  ; 


\ Computes the best move for white. If there is no winning move, and if
\ all moves let black win, returns the first free move. 
i: bestMove   ( -- int )
     9 0 do i isFree i whiteWins and if i return then 
     loop  
     9 0 do i moves isFree i moves blackWins not and
            if i moves return then  
     loop  
     9 0 do i moves isFree if i moves return then 
     loop  
     DONE  ;