visidor/src/main/java/cz/xelfi/quoridor/visidor/Viewer.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 05 Sep 2010 22:34:43 +0200
changeset 255 9ecd02d694cd
parent 254 1273bfb0e2e7
child 264 d60370059c3c
permissions -rw-r--r--
Official API for BoardPane with listener to react to user gestures.
     1 /*
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * The contents of this file are subject to the terms of either the GNU
     5  * General Public License Version 2 only ("GPL") or the Common
     6  * Development and Distribution License("CDDL") (collectively, the
     7  * "License"). You may not use this file except in compliance with the
     8  * License. You can obtain a copy of the License at
     9  * http://www.netbeans.org/cddl-gplv2.html
    10  * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
    11  * specific language governing permissions and limitations under the
    12  * License.  When distributing the software, include this License Header
    13  * Notice in each file and include the License file at
    14  * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
    15  * particular file as subject to the "Classpath" exception as provided
    16  * by Sun in the GPL Version 2 section of the License file that
    17  * accompanied this code. If applicable, add the following below the
    18  * License Header, with the fields enclosed by brackets [] replaced by
    19  * your own identifying information:
    20  * "Portions Copyrighted [year] [name of copyright owner]"
    21  *
    22  * Contributor(s):
    23  *
    24  * Portions Copyrighted 2009 Jaroslav Tulach
    25  */
    26 package cz.xelfi.quoridor.visidor;
    27 
    28 import cz.xelfi.quoridor.Board;
    29 import cz.xelfi.quoridor.Fence;
    30 import cz.xelfi.quoridor.Fence.Orientation;
    31 import cz.xelfi.quoridor.IllegalPositionException;
    32 import cz.xelfi.quoridor.Move;
    33 import cz.xelfi.quoridor.Player;
    34 import java.awt.Color;
    35 import java.awt.Dimension;
    36 import java.awt.EventQueue;
    37 import java.awt.Font;
    38 import java.awt.Graphics;
    39 import java.awt.Graphics2D;
    40 import java.awt.Rectangle;
    41 import java.awt.event.MouseEvent;
    42 import java.awt.event.MouseListener;
    43 import java.awt.event.MouseMotionListener;
    44 import java.awt.image.BufferedImage;
    45 import javax.swing.JFrame;
    46 import javax.swing.JPanel;
    47 
    48 /**
    49  *
    50  * @author Jaroslav Tulach <jtulach@netbeans.org>
    51  */
    52 final class Viewer extends JPanel implements MouseMotionListener, MouseListener {
    53     private Board board;
    54     private int fieldSize;
    55     private int xdelta;
    56     private int ydelta;
    57     private Orientation lastOrientation;
    58     private BoardPane pane;
    59 
    60     public Viewer() {
    61         this(Board.empty());
    62     }
    63 
    64     private Viewer(Board b) {
    65         this.board = b;
    66     }
    67 
    68 
    69     /**
    70      * @param args the command line arguments
    71      */
    72     public static void main(String[] args) throws IllegalPositionException {
    73         JFrame f = new JFrame();
    74         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    75         final BoardPane bp = new BoardPane();
    76         class ApplyMove implements BoardListener {
    77             public void boardChanged(BoardEvent ev) {
    78                 Move m = ev.getMove();
    79                 if (m != null) {
    80                     try {
    81                         bp.setBoard(bp.getBoard().apply(m));
    82                     } catch (IllegalPositionException ex) {
    83                         // no new move
    84                     }
    85                 }
    86             }
    87         }
    88         bp.addBoardListener(new ApplyMove());
    89         bp.setEditable(true);
    90         f.add(bp);
    91         f.pack();
    92         f.setVisible(true);
    93     }
    94 
    95     @Override
    96     public Dimension getPreferredSize() {
    97         return new Dimension(450, 450);
    98     }
    99 
   100     @Override
   101     protected void paintComponent(Graphics gg) {
   102         assert EventQueue.isDispatchThread();
   103         
   104         fieldSize = Math.min(getSize().width, getSize().height) / 9;
   105         int fifth = fieldSize / 10;
   106         Graphics2D g = (Graphics2D) gg;
   107         
   108         xdelta = (getSize().width - fieldSize * 9) / 2;
   109         ydelta = (getSize().height - fieldSize * 9) / 2;
   110         
   111         g.translate(xdelta, ydelta);
   112 
   113         g.setColor(Color.lightGray);
   114         for (int i = 0; i < 9; i++) {
   115             for (int j = 0; j < 9; j++) {
   116                 final Rectangle r = new Rectangle(i * fieldSize, j * fieldSize, fieldSize, fieldSize);
   117                 g.fillRect(r.x + fifth, r.y + fifth, r.width - fifth * 2, r.height - fifth * 2);
   118             }
   119         }
   120 
   121 
   122         g.setColor(Color.BLACK);
   123         for (Fence f : board.getFences()) {
   124             int column = (f.getColumn() - 'A') + 1;
   125             int row = 9 - f.getRow();
   126             Orientation orient = f.getOrientation();
   127             drawFence(orient, column, row, g, true);
   128         }
   129 
   130         int cnt = 0;
   131         Color[] colors = { Color.WHITE, Color.BLACK, Color.ORANGE, Color.MAGENTA };
   132         for (Player p : board.getPlayers()) {
   133             int column = p.getColumn();
   134             int row = 8 - p.getRow();
   135             final boolean isCurrent = p == board.getCurrentPlayer();
   136             final Color currentColor = colors[cnt];
   137             drawPlayer(g, column, row, currentColor, isCurrent, false);
   138             cnt++;
   139         }
   140 
   141         g.setColor(Color.BLACK);
   142         final Font f = new Font("Monospace", Font.BOLD, fifth * 2);
   143         g.setFont(f);
   144         for (int i = 0; i < 8; i++) {
   145             final char ch = (char) ('A' + i);
   146             g.drawString(Character.toString(ch), i * fieldSize + fieldSize - fifth, fifth + f.getSize() - f.getBaselineFor(ch));
   147         }
   148         for (int i = 0; i < 8; i++) {
   149             String s = "" + (8 - i);
   150             g.drawString(s, fifth, i * fieldSize + fieldSize - fifth + f.getSize() - f.getBaselineFor(s.charAt(0)));
   151         }
   152     }
   153 
   154     private void drawPlayer(Graphics2D g, int column, int row, final Color currentColor, final boolean isCurrent, boolean allowedMove) {
   155         int fifth = fieldSize / 10;
   156         int diametr = fieldSize - fifth * 4;
   157         final Rectangle r = new Rectangle(
   158             column * fieldSize + 2 * fifth,
   159             row * fieldSize + 2 * fifth,
   160             diametr,
   161             diametr
   162         );
   163         if (currentColor == null) {
   164             if (allowedMove) {
   165                 g.setColor(Color.BLACK);
   166                 g.drawOval(r.x, r.y, r.width, r.height);
   167             } else {
   168                 g.drawLine(r.x, r.y, r.x + r.width, r.y + r.height);
   169                 g.drawLine(r.x, r.y + r.height, r.x + r.width, r.y);
   170             }
   171         } else {
   172             g.setColor(currentColor);
   173             g.fillOval(r.x, r.y, r.width, r.height);
   174             if (isCurrent) {
   175                 g.setColor(Color.lightGray);
   176                 g.fillOval(r.x + r.width / 3, r.y + r.height / 3, r.width / 3, r.height / 3);
   177             }
   178         }
   179     }
   180     
   181     private void drawFence(Orientation orient, int column, int row, Graphics2D g, boolean fill) throws IllegalStateException {
   182         int fifth = fieldSize / 10;
   183         int w, h;
   184         switch (orient) {
   185             case HORIZONTAL: w = fieldSize - fifth; h = fifth; break;
   186             case VERTICAL: w = fifth; h = fieldSize - fifth; break;
   187             default: throw new IllegalStateException();
   188         }
   189         Rectangle r = new Rectangle(
   190             column * fieldSize - w,
   191             row * fieldSize - h,
   192             2 * w,
   193             2 * h
   194         );
   195         if (fill) {
   196             g.fill(r);
   197         } else {
   198             g.draw(r);
   199         }
   200     }
   201 
   202     public void mouseDragged(MouseEvent e) {
   203     }
   204 
   205     public void mouseMoved(MouseEvent e) {
   206         redrawCurrentMove(e);
   207     }
   208     
   209     private Move redrawCurrentMove(MouseEvent e) {
   210         int x = Math.round(((float)(e.getX() - xdelta)) / fieldSize);
   211         int y = Math.round(((float)(e.getY() - ydelta)) / fieldSize);
   212         if (x <= 0 || x >= 9) {
   213             return null;
   214         }
   215         if (y <= 0 || y >= 9) {
   216             return null;
   217         }
   218 
   219         BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
   220         final Graphics2D d2 = img.createGraphics();
   221         d2.setBackground(getBackground());
   222         d2.clearRect(0, 0, getWidth(), getHeight());
   223         paintComponent(d2);
   224         
   225         
   226         int dx = (e.getX() - xdelta) % fieldSize;
   227         int dy = (e.getY() - ydelta) % fieldSize;
   228         
   229         int fifth = fieldSize / 10;
   230         boolean outOfX = dx > fifth && dx < fieldSize - fifth;
   231         boolean outOfY = dy > fifth && dy < fieldSize - fifth;
   232         if (outOfX && outOfY) {
   233             x = (e.getX() - xdelta) / fieldSize;
   234             y = (e.getY() - ydelta) / fieldSize;
   235             Move m = board.findMove(board.getCurrentPlayer(), x, 8 - y);
   236             if (m == null) {
   237                 drawPlayer(d2, x, y, null, false, false);
   238             } else {
   239                 drawPlayer(d2, x, y, null, false, true);
   240             }
   241             getGraphics().drawImage(img, 0, 0, null);
   242             return m;
   243         }
   244         if (!outOfX && !outOfY) {
   245             if (lastOrientation == null) {
   246                 return null;
   247             }
   248         } else {
   249             if (outOfX) {
   250                 lastOrientation = Orientation.HORIZONTAL;
   251             } else {
   252                 lastOrientation = Orientation.VERTICAL;
   253             }
   254         }
   255         
   256         Move m;
   257         try {
   258             m = Move.fence((char)('A' + x - 1), 9 - y, lastOrientation);
   259             Board newBoard = board.apply(m);
   260             drawFence(lastOrientation, x, y, d2, true);
   261         } catch (IllegalPositionException ex) {
   262             // can't place fence
   263             drawFence(lastOrientation, x, y, d2, false);
   264             m = null;
   265         }
   266         getGraphics().drawImage(img, 0, 0, null);
   267         return m;
   268     }
   269 
   270     public void mouseClicked(MouseEvent e) {
   271     }
   272 
   273     public void mousePressed(MouseEvent e) {
   274         Move m = redrawCurrentMove(e);
   275         BoardPane bp = pane;
   276         if (bp != null) {
   277             bp.moveHappened(m);
   278         }
   279     }
   280 
   281     public void mouseReleased(MouseEvent e) {
   282     }
   283 
   284     public void mouseEntered(MouseEvent e) {
   285     }
   286 
   287     public void mouseExited(MouseEvent e) {
   288     }
   289 
   290     final void setBoard(Board b) {
   291         board = b;
   292         if (isShowing()) {
   293             repaint();
   294         }
   295     }
   296 
   297     final Board getBoard() {
   298         return board;
   299     }
   300 
   301     final void enableListeners(boolean editable) {
   302         if (editable) {
   303             addMouseMotionListener(this);
   304             addMouseListener(this);
   305         } else {
   306             removeMouseListener(this);
   307             removeMouseMotionListener(this);
   308         }
   309     }
   310 
   311     final void moveListener(BoardPane pane) {
   312         this.pane = pane;
   313     }
   314 
   315 }