Skip to content

Instantly share code, notes, and snippets.

@mistercam
Created April 29, 2012 17:57
Show Gist options
  • Save mistercam/2552265 to your computer and use it in GitHub Desktop.
Save mistercam/2552265 to your computer and use it in GitHub Desktop.
Swing JPanel for our Reversi Game
(defn popup [frame msg]
"Displays a popup containing the specified message."
(JOptionPane/showMessageDialog frame msg))
(defn announce-winner [frame board]
"Displays a popup containing the winner of the game."
(let [p (winner board)]
(cond
(= p :w) (popup frame "White Wins!")
(= p :b) (popup frame "Black Wins!")
:else
(popup frame "It's a tie!"))))
(defn reversi-panel [frame board piece]
"Builds a JPanel to represent our Reversi game board. The panel accepts
mouse events to place pieces on the board.
board and piece should both be atoms."
(let [game-over (atom false)]
(proxy [JPanel MouseListener] []
(paintComponent [g] ; overriding JPanel's paintComponent method
(proxy-super paintComponent g) ; call paintComponent on the JPanel
(draw-board g @board @piece)) ; draw our board
(getPreferredSize [] ; defines the size of our game board
(Dimension. board-size (+ board-size footer-height)))
(mouseClicked [e] ; when the user clicks the mouse
(let [rc (parse-mouse-pos (.getX e) (.getY e))] ; converts the mouse position into row-column coords
(if (not (move-valid? @board @piece rc))
(popup frame "Invalid move") ; the user clicked outside the main playing area or on a square with a piece
(do ; the user clicked in an empty square
(swap! board #(place-piece % @piece rc)) ; play the piece and update the board
(.repaint this)
(cond
(game-over? @board) (do
(announce-winner frame @board)
(reset! game-over true))
(empty? (take 1 (valid-moves @board (opposite-piece @piece)))) (popup frame "Still your turn!")
:else (do
(swap! piece opposite-piece)
(.repaint this))))))) ;; we've switched players, so let's redraw to update the active player text
(mouseReleased [e]) ; we're not doing anything for this event
(mousePressed [e]) ; we're not doing anything for this event
(mouseEntered [e]) ; we're not doing anything for this event
(mouseExited [e])))) ; we're not doing anything for this event
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment