Recently, I have been experimenting with JavaFX in Clojure. Initially, in one of my experiments, I wanted to learn how to re-size a game-board interface as it’s containing window was re-sized. In the past I’ve had medical device interfaces that draw a representation of a physical device and these drawings must re-size as their window is re-sized. The initial experiment was with a simple interface for Tic-Tac-Toe. Since I had such a nice interface, I thought, why not program the complete game.
Well, it’s done. The code is here. It’s unbeatable. If you happen to win, it’s a bug.
The key to re-sizing is to watch the width and height properties of the window containing the board and attach change listeners to the properties. The relevant code from the program:
Every time the canvas is re-sized, the
redraw-board function is called. That function takes care of calculating the new size of the board and symbols, then draws them.
Another feature of JavaFX is the ability to style the interface elements. Since flat interfaces are all the rage now, I thought I would play with that too. This aspect of JavaFX still feels a little unfinished in that some styling can be accomplished programmatically while other styles can only be done with CSS. For example, note the “Reset” button in the screen capture above. You can set some of the style directly in the program. To get all of the behavior you want for the button, such as mouse-over handling, you have to use a CSS file. Here’s the file I used for the program.
One of the nice things about writing a program like this in Clojure is the way listener-type methods can be written. This program has a few. Some
ChangeListeners were shown above. There are also a couple of
EventListeners for button clicks. In fact, most of the game play occurs in the method that listens for player clicks on the game board.
This method still feels like there is some room for improvement, but it works for now.
The computer player is closely derived from the one described in Chapter 10 of “Simply Scheme” by Brian Harvey and Matthew Wright. The unit tests in the project consist mostly of the example function usage shown in that chapter. The book is available in several forms on-line. It is unbeatable. If you happen to beat the game, it is undoubtedly a program bug introduced in my translation.
If you are interested in the complete code for the project, it is on BitBucket here.