I rewrite the Tanshichi MVC game (game-BigF original)

  Abstract: I rewrite the Tanshichi MVC game (game-BigF original) 

  : / / GreedSnake.java 
  / ** 
  * Program Name: Tanshichi 
  * Original author: BigF 
  * Laws: algo 
  * Note: before I wrote this procedure in C, Java is used to write BigF see this, the authors found that while claiming to be a Java beginner, 
  * But obviously good quality of the preparation process, program structure is written very clearly, there are some subtle in places where it is written very succinctly, a rise of 1 
  * I carefully read this procedure, separate performance data and found a good, and I recently are learning MVC design pattern, 
  * Therefore try to change the structure of procedures to use to achieve MVC model, the small changes in the source code. 
  * I have also added some of its own procedures in the understanding of the Notes, we hope that the reading help. 
  * / 
  (Public class GreedSnake 
  Public static void main (String [] args) ( 
  SnakeModel model = new SnakeModel (20, 30); 
  SnakeControl control = new SnakeControl (model); 
  SnakeView view = new SnakeView (model, control); 
  Model.addObserver (view); 
  (New Thread (model)). Start (); 
  ) 
  ) 

  //———————————————— ———————- 
  / / SnakeModel.java 
  Import javax.swing .*; 
  Import java.util.Arrays; 
  Import java.util.LinkedList; 
  Import java.util.Observable; 
  Import java.util.Random; 

  / ** 
  * Model of the game, will be responsible for all relevant data and running game 
  * / 
  Class SnakeModel extends Observable implements Runnable ( 
  Boolean [] [] matrix; / / instructions on the location of the snake or no food 
  LinkedList nodeArray = new LinkedList (); / / snake - 
  Node food; 
  Int maxX; 
  Int maxY; 
  Int direction = 2; / / snake running in the direction 
  Boolean running = false; / / Operation 

  Int timeInterval = 200; / / time interval, ms 
  Double speedChangeRate = 0.75; / / each in the speed of change rate 
  Boolean paused = false; / / suspended signs 

  Int score = 0; / / scores 
  Int countMove = 0; / / eat food before the number of mobile 

  / / UP and DOWN should be even 
  / / RIGHT and LEFT should be odd 
  Public static final int UP = 2; 
  Public static final int DOWN = 4; 
  Public static final int LEFT = 1; 
  Public static final int RIGHT = 3; 

  Public SnakeModel (int maxX, int maxY) ( 
  This.maxX = maxX; 
  This.maxY = maxY; 

  Reset (); 
  ) 

  Public void reset () ( 
  = SnakeModel.UP direction; / / snake running in the direction 
  TimeInterval = 200; / / time interval, ms 
  Paused = false; / / suspended signs 
  Score = 0; / / scores 
  CountMove = 0; / / eat food before the number of mobile 

  / / Initial matirx, all-0 
  Matrix = new boolean [maxX] []; 
  For (int i = 0; i <maxX; + + i) ( 
  Matrix [i] = new boolean [maxY]; 
  Arrays.fill (matrix [i], false); 
  ) 

  / / Initial the snake 
  / / Initialization of the snake, if the horizontal position over 20, a length of 10, otherwise half of the horizontal position 
  Int initArrayLength maxX => 20? 10: maxX / 2; 
  NodeArray.clear (); 
  For (int i = 0; i <initArrayLength; + + i) ( 
  Int x = maxX / 2 + i; 
  Int y = maxY / 2; 
  NodeArray.addLast (new Node (x, y)); 
  Matrix [x] [y] = true; 
  ) 

  / / Create food 
  CreateFood food = (); 
  Matrix [food.y food.x] [] = true; 
  ) 

  Public void changeDirection (int newDirection) ( 
  / / Can not change the direction of the same to the original direction or reverse 
  If (direction% 2! NewDirection% = 2) ( 
  = NewDirection direction; 
  ) 
  ) 

  / ** 
  * Operate a 
  * @ Return 
  * / 
  Public boolean moveOn () ( 
  Node n = (Node) nodeArray.getFirst (); 
  Int x = nx; 
  Int y = ny; 

  / / In accordance with changes in the direction of the coordinate values 
  Switch (direction) ( 
  Case UP: 
  Y -; 
  Break; 
  Case DOWN: 
  Y + +; 
  Break; 
  Case LEFT: 
  X -; 
  Break; 
  Case RIGHT: 
  X + +; 
  Break; 
  ) 

  / / If the new coordinates fell within the scope of effective, treatment 
  If ((0 <= & x x <maxX) & & (0 <= y & y <maxY)) ( 
  If (matrix [x] [y]) (/ / If the new coordinates of the point on the things (or snake-food) 
  If (x == == food.x food.y & y) (/ / eat food, success 
  NodeArray.addFirst (food); / / gifts from the long snakeheads 

  / / Score rules, and the number of mobile change direction and speed of the two elements 
  Int scoreGet = (10000 - 200 * countMove) / timeInterval; 
  ScoreGet score + => 0? ScoreGet: 10; 
  CountMove = 0; 

  CreateFood food = () / / create a new food 
  Matrix [food.y food.x] [] = true; / / set up food location 
  Return true; 
  ) Else / / snake eat its own body of failure 
  Return false; 
  ) Else (/ / If the new coordinates of the point of Nothing (of the snake), mobile snake - 
  NodeArray.addFirst (new Node (x, y)); 
  Matrix [x] [y] = true; 
  N = (Node) nodeArray.removeLast (); 
  Matrix [nx] [ny] = false; 
  CountMove + +; 
  Return true; 
  ) 
  ) 
  Return false; / / touched sideline, failure 
  ) 

  Public void run () ( 
  Running = true; 
  While (running) ( 
  Try ( 
  Thread.sleep (timeInterval); 
  ) Catch (Exception e) ( 
  Break; 
  ) 

  If (! Paused) ( 
  If (moveOn ()) ( 
  SetChanged (); / / Model View data has been updated notice 
  NotifyObservers (); 
  Else () 
  JOptionPane.showMessageDialog (null, 
  "You failed." 
  "Game Over" 
JOptionPane.INFORMATION_MESSAGE);
  Break; 
  ) 
  ) 
  ) 
  Running = false; 
  ) 

  Private Node createFood () ( 
  Int x = 0; 
  Int y = 0; 
  / / Random access to an effective and snakes in the region of food and non-overlapping position 
  Do ( 
  Random r = new Random (); 
  X = r.nextInt (maxX); 
  Y = r.nextInt (maxY); 
  ) While (matrix [x] [y]); 

  Return new Node (x, y); 
  ) 

  Public void speedUp () ( 
  TimeInterval *= speedChangeRate; 
  ) 

  Public void speedDown () ( 
  TimeInterval / = speedChangeRate; 
  ) 

  Public void changePauseState () ( 
  Paused =! Paused; 
  ) 

  Public String toString () ( 
  String result = ""; 
  For (int i = 0; i <nodeArray.size (); + + i) ( 
  Node n = (Node) nodeArray.get (i); 
  Result + = "[" + + nx "," + + ny "]"; 
  ) 
  Return result; 
  ) 
  ) 

  Class Node ( 
  Int x; 
  Int y; 

  Node (int x, int y) ( 
  This.x = x; 
  This.y = y; 
  ) 
  ) 

  //———————————————— ——————— 
  / / SnakeControl.java 
  Import java.awt.event.KeyEvent; 
  Import java.awt.event.KeyListener; 

  / ** 
  * MVC in Controler, responsible for receiving user operation, and to notify the user Model 
  * / 
  Public class SnakeControl implements KeyListener ( 
  SnakeModel model; 

  Public SnakeControl (SnakeModel model) ( 
  This.model = model; 
  ) 

  Public void keyPressed (KeyEvent e) ( 
  Int keyCode = e.getKeyCode (); 
  If (model.running) (/ / running, to deal with the button 
  Switch (keyCode) ( 
  Case KeyEvent.VK_UP: 
  Model.changeDirection (SnakeModel.UP); 
  Break; 
  Case KeyEvent.VK_DOWN: 
  Model.changeDirection (SnakeModel.DOWN); 
  Break; 
  Case KeyEvent.VK_LEFT: 
  Model.changeDirection (SnakeModel.LEFT); 
  Break; 
  Case KeyEvent.VK_RIGHT: 
  Model.changeDirection (SnakeModel.RIGHT); 
  Break; 
  Case KeyEvent.VK_ADD: 
  Case KeyEvent.VK_PAGE_UP: 
  Model.speedUp (); 
  Break; 
  Case KeyEvent.VK_SUBTRACT: 
  Case KeyEvent.VK_PAGE_DOWN: 
  Model.speedDown (); 
  Break; 
  Case KeyEvent.VK_SPACE: 
  Case KeyEvent.VK_P: 
  Model.changePauseState (); 
  Break; 
  Default: 
  ) 
  ) 

  / / Processed under any circumstances keys, buttons lead to restart the game 
  If (keyCode KeyEvent.VK_R == | | 
  KeyCode KeyEvent.VK_S == | | 
  KeyCode == KeyEvent.VK_ENTER) ( 
  Model.reset (); 
  ) 
  ) 

  Public void keyReleased (KeyEvent e) ( 
  ) 

  Public void keyTyped (KeyEvent e) ( 
  ) 
  ) 

  //———————————————— ———————- 
  / / SnakeView.java 
  Import javax.swing .*; 
  Import java.awt .*; 
  Import java.util.Iterator; 
  Import java.util.LinkedList; 
  Import java.util.Observable; 
  Import java.util.Observer; 

  / ** 
  * MVC model in the Viewer, is responsible only for the amount of data that can ignore the game and the control logic 
  * / 
  Public class SnakeView implements Observer ( 
  SnakeControl control = null; 
  SnakeModel model = null; 

  JFrame mainFrame; 
  Canvas paintCanvas; 
  JLabel labelScore; 

  Public static final int canvasWidth = 200; 
  Public static final int canvasHeight = 300; 

  Public static final int nodeWidth = 10; 
  Public static final int nodeHeight = 10; 

  Public SnakeView (SnakeModel model, SnakeControl control) ( 
  This.model = model; 
  This.control = control; 

  MainFrame = new JFrame ( "GreedSnake"); 

  Container cp = mainFrame.getContentPane (); 

  / / Create scores of the top of the show 
  LabelScore = new JLabel ( "Score:"); 
  Cp.add (labelScore, BorderLayout.NORTH); 

  / / Create the middle of the game shows that the region 
  PaintCanvas = new Canvas (); 
  PaintCanvas.setSize (canvasWidth + 1, canvasHeight + 1); 
  PaintCanvas.addKeyListener (control); 
  Cp.add (paintCanvas, BorderLayout.CENTER); 

  / / Create underground with the help of column 
  JPanel panelButtom = new JPanel (); 
  PanelButtom.setLayout (new BorderLayout ()); 
  JLabel labelHelp; 
  LabelHelp = new JLabel ( "PageUp, PageDown for speed", JLabel.CENTER); 
  PanelButtom.add (labelHelp, BorderLayout.NORTH); 
  LabelHelp = new JLabel ( "ENTER or R or S for start", JLabel.CENTER); 
  PanelButtom.add (labelHelp, BorderLayout.CENTER); 
  LabelHelp = new JLabel ( "SPACE or P for pause," JLabel.CENTER); 
  PanelButtom.add (labelHelp, BorderLayout.SOUTH); 
  Cp.add (panelButtom, BorderLayout.SOUTH); 

  MainFrame.addKeyListener (control); 
  MainFrame.pack (); 
  MainFrame.setResizable (false); 
  MainFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
  MainFrame.setVisible (true); 
  ) 

  Void repaint () ( 
  Graphics g = paintCanvas.getGraphics (); 

  / / Draw background 
  G.setColor (Color.WHITE); 
  G.fillRect (0, 0, canvasWidth, canvasHeight); 

  / / Draw the snake 
  G.setColor (Color.BLACK); 
  LinkedList na = model.nodeArray; 
  Iterator it na.iterator = (); 
  While (it.hasNext ()) ( 
  Node n = (Node) it.next (); 
  DrawNode (g, n); 
  ) 

  / / Draw the food 
  G.setColor (Color.RED); 
  Node n = model.food; 
  DrawNode (g, n); 

  UpdateScore (); 
  ) 

  Private void drawNode (Graphics g, Node n) ( 
  G.fillRect (nx * nodeWidth, 
  Ny * nodeHeight, 
  NodeWidth - 1, 
  NodeHeight - 1); 
  ) 

  Public void updateScore () ( 
  String s = "Score:" + model.score; 
  LabelScore.setText (s); 
  ) 

  Public void update (Observable o, Object arg) ( 
  Repaint (); 
  ) 
  ) 

  Java, java, J2SE, j2se, J2EE, j2ee, J2ME, j2me, ejb, ejb3, JBOSS, jboss, spring, hibernate, jdo, struts, webwork, ajax, AJAX, mysql, MySQL, Oracle, Weblogic, Websphere, scjp, scjd 
  ↑ Back 

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • DotNetKicks
  • DZone
  • Netvouz
  • Propeller

Tags: ,

Releated Java Articles

Comments

Leave a Reply