1 package khumpangame; 2 3 import javax.swing.*; 4 import javax.swing.event.*; 5 import java.awt.*; 6 import java.awt.event.*; 7 import java.awt.geom.*; 8 9 11 public class MoveView extends JPanel 12 { 13 final private Model model; 14 public int blocSize = 50; 15 16 private int clickedPiece = -1; 17 private int clickedX = -1; 18 private int clickedY = -1; 19 20 public MoveView(final Model model, final int blocSize, boolean withController) 21 { 22 this.model = model; 23 this.blocSize = blocSize; 24 this.setPreferredSize( new Dimension(blocSize*model.getNumberOfColumns(), blocSize*model.getNumberOfLines())); 25 26 if(withController) 29 { 30 this.addMouseListener(new MouseAdapter() 31 { 32 @Override public void mousePressed(MouseEvent me) 33 { 34 clickedX = me.getX()/blocSize; 35 clickedY = me.getY()/blocSize; 36 clickedPiece = model.getPieceAt( clickedX, clickedY ); 37 update(); 38 } 39 }); 40 this.addMouseMotionListener(new MouseMotionAdapter() 41 { 42 @Override public void mouseDragged(MouseEvent me) 43 { 44 int destX2 = me.getX()/blocSize; 45 int destY2 = me.getY()/blocSize; 46 47 if(clickedPiece>0 && Math.abs(destX2-clickedX)==1 && model.canMoveX(clickedPiece, destX2-clickedX)) 48 { 49 model.moveX(clickedPiece, destX2-clickedX); 50 clickedX = destX2; 51 } 52 if(clickedPiece>0 && Math.abs(destY2-clickedY)==1 && model.canMoveY(clickedPiece, destY2-clickedY)) 53 { 54 model.moveY(clickedPiece, destY2-clickedY); 55 clickedY = destY2; 56 } 57 58 update(); 59 } 60 }); 61 } 62 } 64 public void update() 65 { 66 repaint(); 67 68 if(model.hasReachEndPosition()) 69 { 70 JOptionPane.showMessageDialog(this, "Congratulations, you solved the problem in "+model.numberOfMoves+" moves."); 71 } 72 } 73 74 76 public void paintComponent(Graphics g) 77 { 78 super.paintComponent(g); 80 81 for(int i=0; i<model.getNumberOfLines(); i++) { 83 for(int j=0; j<model.getNumberOfColumns(); j++) { 85 int piece = model.getPieceAt(j,i); 86 if(piece>0) 87 { 88 if(piece == clickedPiece) { 90 g.setColor( model.getColorForPiece( piece ).darker() ); 91 } 92 else 93 { 94 g.setColor( model.getColorForPiece( piece ) ); 95 } 96 97 int borderLeft = (model.getPieceAt(j-1,i)!=piece ? 1 : 0); 98 int borderRight = (model.getPieceAt(j+1,i)!=piece ? 1 : 0); 99 100 int borderTop = (model.getPieceAt(j,i-1)!=piece ? 1 : 0); 101 int borderBelow = (model.getPieceAt(j,i+1)!=piece ? 1 : 0); 102 103 104 g.fillRect( j*blocSize+borderLeft, i*blocSize+borderTop, blocSize-borderLeft-borderRight, blocSize-borderTop-borderBelow); 105 } 106 } 107 } 108 } 109 110 111 } | Popular Tags |