Advertisement
Slyke

OOP Game Control

May 16th, 2014
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.71 KB | None | 0 0
  1. package Configs;
  2.  
  3. import java.io.FileNotFoundException;
  4. import java.io.FileWriter;
  5.  
  6. import javax.swing.JFileChooser;
  7. import javax.swing.JFrame;
  8. import javax.swing.filechooser.FileNameExtensionFilter;
  9.  
  10. import java.io.File;
  11. import java.util.List;
  12. import java.util.Scanner;
  13.  
  14. public class ExtHandle {
  15.  
  16.     private final String KV_KEY=":";        //Key that separates data name from data value.
  17.     private final String DELIMITER_KEY=";"; //Key that separates data entries
  18.     private final String SEPERATE_KEY=",";  //Key that separates array or listed data
  19.     private final String NEWLINE_KEY="\n";  //New line key (Not used, but kept just in case).
  20.    
  21.     //These are the keys used when saving a game, so that we can restore it.
  22.     private final String SAVE_DIM_X="dX";                       //Board horizontal cells key name.
  23.     private final String SAVE_DIM_Y="dY";                       //Board vertical cells key name.
  24.     private final String SAVE_PLAYERNAME="pName";               //Player name key name.
  25.     private final String SAVE_PLAYERHEALTH="pHealth";           //Player health key name.
  26.     private final String SAVE_PLAYERHEALTHTOTAL="totalhealth";  //Total health key name.
  27.     private final String SAVE_MINESTRENGTH="minestrenght";      //Maximum mine strength key name.
  28.     private final String SAVE_GAMETYPE="gType";                 //Game type key name.
  29.     private final String SAVE_GAMETIMELIMIT="timelimit";        //Time limit key name.
  30.     private final String SAVE_GAMETIMELEFT="timePassed";        //Time passed key name.
  31.     private final String SAVE_MINECOUNT="mines";                //Mine count key name.
  32.     private final String SAVE_MAPMATRIX="map";                  //Map key name.
  33.     private final String SAVE_MINESTRENGTHMAP="minestrengthmap"; //Mine strength map key name.
  34.     private final String SAVE_HISTORYMATRIX="history";          //Key name for history. Please note history is only saved, it is not restored.
  35.    
  36.     private final String FILE_MINESWEEPERMAP_EXT="msg"; // File extension (Stands for MineSweeperGame)
  37.    
  38.     private String currentGameBuffer; //Somewhere to store out loaded data, or data to be saved.
  39.    
  40.     private handler mainHNDLR; //Our communication line back to the execLoad class for the game handle.
  41.    
  42.     ExtHandle(handler mainHNDLR)
  43.     {
  44.         this.mainHNDLR=mainHNDLR;
  45.     }
  46.    
  47.     public String gameToString(int[] fieldMatrix, int[] fieldDimension, int mineCount, String playerName, int gameTime, int timePassed, int gameMode, int playerHealth, int totalHealth, int mineStrength, int[] mineMap)
  48.     /*
  49.      * Inputs:
  50.      *      fieldMatrix     -   Takes the current 1 dimensional field of the board.
  51.      *      fieldDimension  -   Takes the 1 dimensional, 2 index board dimensions.
  52.      *      mineCount       -   Takes the total mine count of the map.
  53.      *      playerName      -   Takes the current player name.
  54.      *      gameTime        -   Takes the starting amount of time allocated for the game.
  55.      *      timeLeft        -   Takes how much time has passed.
  56.      *      gameMode        -   What game mode is this?
  57.      *      playerHealth    -   Takes current player health
  58.      *      totalHealth     -   Takes the total health that was allocated at the start of the match.
  59.      *      mineStrength    -   Takes the maximum mine strength.
  60.      *      mineMap         -   Takes a 1 dimensional array of the mine strength map.
  61.      *
  62.      * Outputs:
  63.      *      Passes out what ever gameToString() passes out.
  64.      *
  65.      * Process:
  66.      *      This function will turn the current game to string. It overloads the other gameToString() function, which also takes the current game history as a parameter.
  67.      */
  68.     {
  69.         return gameToString(fieldMatrix, fieldDimension, mineCount, playerName, gameTime, timePassed, gameMode, playerHealth, totalHealth, mineStrength, mineMap, null);
  70.        
  71.     }
  72.    
  73.     public void updateSettingsFromLoad(String loadedGame)
  74.     /*
  75.      * Inputs:
  76.      *      loadedGame  -   Takes the string value of the game (usually from a file.)
  77.      *
  78.      * Outputs:
  79.      *      None, it updates the settings automatically.
  80.      *
  81.      * Process:
  82.      *      After loading the saved game string from a file (or memory), this function is run so that the game settings are updated.
  83.      */
  84.     {
  85.         this.mainHNDLR.settings.setGameColumns(Integer.parseInt(getDataString(SAVE_DIM_X, loadedGame)));
  86.         this.mainHNDLR.settings.setGameRows(Integer.parseInt(getDataString(SAVE_DIM_Y, loadedGame)));
  87.         this.mainHNDLR.settings.setMineCount(Integer.parseInt(getDataString(SAVE_MINECOUNT, loadedGame)));
  88.         this.mainHNDLR.settings.setTimeLimit(Integer.parseInt(getDataString(SAVE_GAMETIMELIMIT, loadedGame)));
  89.         this.mainHNDLR.settings.setMineStrength(Integer.parseInt(getDataString(SAVE_MINESTRENGTH, loadedGame)));
  90.         this.mainHNDLR.settings.setHealthLimit(Integer.parseInt(getDataString(SAVE_PLAYERHEALTHTOTAL, loadedGame)));
  91.         this.mainHNDLR.settings.setGameType(Integer.parseInt(getDataString(SAVE_GAMETYPE, loadedGame)));
  92.         this.mainHNDLR.settings.setPlayerName(getDataString(SAVE_PLAYERNAME, loadedGame));
  93.     }
  94.    
  95.     public void updateSettingsFromLoad()
  96.     /*
  97.      * Inputs:
  98.      *      None
  99.      *
  100.      * Outputs:
  101.      *      None
  102.      *
  103.      * Process:
  104.      *      If no string is specified for the updateSettingsFromLoad() function, then we'll use the current game string.
  105.      */
  106.     {
  107.         updateSettingsFromLoad(this.mainHNDLR.extHandle.getGameStringBuffer());
  108.     }
  109.    
  110.     public String gameToString(int[] fieldMatrix, int[] fieldDimension, int mineCount, String playerName, int gameTime, int timePassed, int gameMode, int playerHealth, int totalHealth, int mineStrength, int[] mineMap, List<int[]> gameHistory)
  111.     /*
  112.      * Inputs:
  113.      *      fieldMatrix     -   Takes the current 1 dimensional field of the board.
  114.      *      fieldDimension  -   Takes the 1 dimensional, 2 index board dimensions.
  115.      *      mineCount       -   Takes the total mine count of the map.
  116.      *      playerName      -   Takes the current player name.
  117.      *      gameTime        -   Takes the starting amount of time allocated for the game.
  118.      *      timeLeft        -   Takes how much time has passed.
  119.      *      gameMode        -   What game mode is this?
  120.      *      playerHealth    -   Takes current player health
  121.      *      totalHealth     -   Takes the total health that was allocated at the start of the match.
  122.      *      mineStrength    -   Takes the maximum mine strength.
  123.      *      mineMap         -   Takes a 1 dimensional array of the mine strength map.
  124.      *      gameHistory     -   A copy of the current game history in the form of a 2 dimensional array
  125.      *
  126.      * Outputs:
  127.      *      Passes out what ever gameToString() passes out.
  128.      *
  129.      * Process:
  130.      *      This function will turn the current game to string. Each of the parameters is placed into a string, according to its key name, separated by the key<>value delimiter key (a :), and finishes with the data field delimiter key (a ;). It also breaks upthe fieldMatrix[] array, the mineMap[] array and the gameHistory multi-dimensional array into comma separated values (CSV) for file storage.
  131.      */
  132.     {
  133.  
  134.         String theGame="";
  135.         theGame+=SAVE_DIM_X + KV_KEY + fieldDimension[0]+DELIMITER_KEY;
  136.         theGame+=SAVE_DIM_Y + KV_KEY + fieldDimension[1]+DELIMITER_KEY;
  137.         theGame+=SAVE_MINECOUNT + KV_KEY + mineCount+DELIMITER_KEY;
  138.         theGame+=SAVE_PLAYERNAME + KV_KEY + playerName + DELIMITER_KEY;
  139.         theGame+=SAVE_GAMETIMELIMIT + KV_KEY + gameTime + DELIMITER_KEY;
  140.         theGame+=SAVE_GAMETIMELEFT + KV_KEY + timePassed + DELIMITER_KEY;
  141.         theGame+=SAVE_PLAYERHEALTH + KV_KEY + playerHealth + DELIMITER_KEY;
  142.         theGame+=SAVE_PLAYERHEALTHTOTAL + KV_KEY + totalHealth + DELIMITER_KEY;
  143.         theGame+=SAVE_MINESTRENGTH + KV_KEY + mineStrength + DELIMITER_KEY;
  144.         theGame+=SAVE_GAMETYPE + KV_KEY + gameMode + DELIMITER_KEY;
  145.         theGame+=SAVE_MAPMATRIX + KV_KEY;
  146.        
  147.         for (int i=0;i<fieldMatrix.length-1;i++) //Field matrix array
  148.         {
  149.             theGame+=fieldMatrix[i] + SEPERATE_KEY;
  150.         }
  151.         theGame+=mineMap[mineMap.length-1]+DELIMITER_KEY;
  152.        
  153.         theGame+=SAVE_MINESTRENGTHMAP + KV_KEY;
  154.        
  155.         for (int i=0;i<mineMap.length-1;i++) //Mine strength array
  156.         {
  157.             theGame+=mineMap[i] + SEPERATE_KEY;
  158.         }
  159.         theGame+=mineMap[mineMap.length-1]+DELIMITER_KEY;
  160.        
  161.         if (gameHistory!=null) { //Game history matrix
  162.             for (int i=0;i<gameHistory.size();i++) {
  163.                 theGame+=SAVE_HISTORYMATRIX+"[" + i + "]" + KV_KEY;
  164.                
  165.                 for (int j=0; j < gameHistory.get(i).length - 1; j++)
  166.                 {
  167.                     theGame+=gameHistory.get(i)[j] + SEPERATE_KEY;
  168.                 }
  169.                 theGame+=gameHistory.get(i)[gameHistory.get(i).length-1]+DELIMITER_KEY;
  170.             }
  171.         }
  172.  
  173.         setGameStringBuffer(theGame);
  174.        
  175.         return theGame;
  176.     }
  177.    
  178.     public void setGameStringBuffer(String currentGameString)
  179.     /*
  180.      * Inputs:
  181.      *      currentGameString   -   The string you want to be set as the current game's string.
  182.      *
  183.      * Outputs:
  184.      *      None
  185.      *
  186.      * Process:
  187.      *      When saving a game, we want to pass the game's string from another class into this one, we do this by calling this function so that the game string is saved locally (to this class).
  188.      */
  189.     {
  190.         currentGameBuffer=currentGameString;
  191.         System.out.println("Game Saved String: ");
  192.         System.out.println(currentGameBuffer);
  193.     }
  194.    
  195.     public String getGameStringBuffer()
  196.     /*
  197.      * Inputs:
  198.      *      None
  199.      *
  200.      * Outputs:
  201.      *      The current game's string
  202.      *
  203.      * Process:
  204.      *      This is the function we use (an accessor) to pass the  current game's string to another class.
  205.      */
  206.     {
  207.         return currentGameBuffer;
  208.     }
  209.    
  210.     public String getDataString(String dataName, String searchString)
  211.     /*
  212.      * Inputs:
  213.      *      None
  214.      *
  215.      * Outputs:
  216.      *      The current game's string
  217.      *
  218.      * Process:
  219.      *      This is the function we use (an accessor) to pass the  current game's string to another class.
  220.      */
  221.     {
  222.         int startPoint=searchString.indexOf(dataName + KV_KEY);
  223.            
  224.         if (startPoint<=-1) { return ""; }
  225.  
  226.         startPoint += (dataName + SEPERATE_KEY).length();
  227.        
  228.         String[] theData=searchString.substring(startPoint).split(DELIMITER_KEY);
  229.            
  230.         return theData[0];
  231.       }
  232.    
  233.     public int[] getMapArr(String mapMatrix)
  234.     /*
  235.      * Inputs:
  236.      *      mapMatrix   -   The current game string, which includes the map matrix (or mineStrength CSV).
  237.      *
  238.      * Outputs:
  239.      *      An array of the mapMatrix (or mineStrength if that is what was passed in).
  240.      *
  241.      * Process:
  242.      *      Basically cuts data that is separated by SEPERATE_KEY (a ,) into an int array. Is normally used when loading a map.
  243.      */
  244.     {
  245.        
  246.         String [] cutMatrix=mapMatrix.split(SEPERATE_KEY);
  247.        
  248.         int matrixLegnth=cutMatrix.length;
  249.         int [] theReturn = new int[matrixLegnth];
  250.        
  251.         for (int i=0;i<matrixLegnth;i++)
  252.         {
  253.             theReturn[i]=Integer.parseInt(cutMatrix[i]);
  254.         }
  255.         return theReturn;
  256.     }
  257.    
  258.     public boolean saveGame(String fileName, String gameData)
  259.     /*
  260.      * Inputs:
  261.      *      fileName    -   Filename to save to, as a string.
  262.      *      gameData    -   The game data to write to the file.
  263.      *
  264.      * Outputs:
  265.      *      Returns saveGame(), see other saveGame() overloaded function.
  266.      *
  267.      * Process:
  268.      *      Overloads the saveGame function, to allow input of a string as the file name, instead of a file object. See the overloaded function for more details.
  269.      */
  270.     {
  271.         File saveFile = new File(fileName);
  272.         return saveGame(saveFile, gameData);
  273.     }
  274.    
  275.     public boolean saveGame(File fileName, String gameData)
  276.     /*
  277.      * Inputs:
  278.      *      fileName    -   Filename to save to, as a file object.
  279.      *      gameData    -   The game data to write to the file.
  280.      *
  281.      * Outputs:
  282.      *      Returns true if the save was successful, or false if the exception was triggered.
  283.      *
  284.      * Process:
  285.      *      Writes the data from gameData into a file.
  286.      */
  287.     {
  288.         try {
  289.             FileWriter objSaveFile = new FileWriter(fileName);
  290.             objSaveFile.write(gameData);
  291.             objSaveFile.close();
  292.         }
  293.         catch (Exception e) {
  294.             System.out.println("Couldn't save the game.");
  295.             return false;
  296.         }
  297.         return true;
  298.     }
  299.    
  300.     public boolean deleteAutosave()
  301.     /*
  302.      * Inputs:
  303.      *      None
  304.      *
  305.      * Outputs:
  306.      *      Returns true if the autosave file was successfully deleted, or false if the exception was triggered.
  307.      *
  308.      * Process:
  309.      *      Writes the data from gameData into a file.
  310.      */
  311.     {
  312.         File deleteFile = new File(mainHNDLR.settings.getAutoSavePath());
  313.         try {
  314.             deleteFile.delete();
  315.             System.out.println("Autosave file deleted.");
  316.         } catch (Exception e) {
  317.             System.out.println("Could not delete autosave file. It may not exist, or be read-only.");
  318.             return false;
  319.         }
  320.        
  321.         return true;
  322.     }
  323.    
  324.     public boolean loadGame(String fileName)
  325.     /*
  326.      * Inputs:
  327.      *      fileName    -   Filename, as a string to load. The overloaded function takes a file object.
  328.      *
  329.      * Outputs:
  330.      *      Returns true if the file was successfully loaded, or false if the exception was triggered.
  331.      *
  332.      * Process:
  333.      *      Reads data from the loadgame file, see the overloaded function for more details.
  334.      */
  335.     {
  336.         File openFile = new File(fileName);
  337.         return loadGame(openFile);
  338.     }
  339.    
  340.     public boolean loadGame(File fileName)
  341.     /*
  342.      * Inputs:
  343.      *      fileName    -   Filename, as a file object to load.
  344.      *
  345.      * Outputs:
  346.      *      Returns true if the file was successfully loaded, or false if the exception was triggered.
  347.      *
  348.      * Process:
  349.      *      Reads data from the loadgame file, and places it as the current game's string.
  350.      */
  351.     {
  352.         String theGame="";
  353.         try {
  354.             Scanner lineBuffer = new Scanner(fileName);
  355.             while (lineBuffer.hasNextLine()) {
  356.                 theGame = lineBuffer.nextLine();
  357.             }
  358.             lineBuffer.close();
  359.         }
  360.         catch (FileNotFoundException e) {
  361.             System.out.println("Couldn't load game.");
  362.             return false;
  363.         }
  364.         setGameStringBuffer(theGame);
  365.         updateSettingsFromLoad();
  366.         return true;
  367.     }
  368.    
  369.     public boolean showSaveDialog(String whatToSave, JFrame whatCalled)
  370.     /*
  371.      * Inputs:
  372.      *      whatToSave  -   The game data that we are saving.
  373.      *      whatCalled  -   The window object that called this function. We take this so that we can lock control of said window.
  374.      *
  375.      * Outputs:
  376.      *      Returns true if the file was successfully saved, or false if the exception was triggered.
  377.      *
  378.      * Process:
  379.      *      Gets the game data, then displays the save dialog box, so that the user can choose where they would like to save their game. It then calls the saveGame() function to save said data to said file.
  380.      */
  381.     {
  382.         JFileChooser saveDialog = new JFileChooser();
  383.         FileNameExtensionFilter fileFilter = new FileNameExtensionFilter("Minesweeper Game (*." + FILE_MINESWEEPERMAP_EXT + ")", FILE_MINESWEEPERMAP_EXT);
  384.         saveDialog.setFileFilter(fileFilter);
  385.         int dialogReturn = saveDialog.showSaveDialog(whatCalled);
  386.        
  387.         if (dialogReturn != JFileChooser.CANCEL_OPTION) {
  388.             File saveFile = saveDialog.getSelectedFile();
  389.             if(!saveFile.toString().toLowerCase().endsWith(FILE_MINESWEEPERMAP_EXT)) { saveFile = new File(saveFile + FILE_MINESWEEPERMAP_EXT); } //Our very own MineSweeperGame file extension.
  390.             return saveGame(saveFile, whatToSave);
  391.         }
  392.        
  393.         return true;
  394.     }
  395.    
  396.     public boolean showLoadDialog(JFrame whatCalled)
  397.     /*
  398.      * Inputs:
  399.      *      whatCalled  -   The window object that called this function. We take this so that we can lock control of said window.
  400.      *
  401.      * Outputs:
  402.      *      Returns true if the file was successfully loaded, or false if the exception was triggered.
  403.      *
  404.      * Process:
  405.      *      Displays the save dialog box, so that the user can choose where their game was saved. It then calls reads the data from the file and calls setGameStringBuffer(), while updating the current game's settings with updateSettingsFromLoad();
  406.      */
  407.     {
  408.         JFileChooser openDialog = new JFileChooser();
  409.         FileNameExtensionFilter fileFilter = new FileNameExtensionFilter("Minesweeper Game (*." + FILE_MINESWEEPERMAP_EXT + ")", FILE_MINESWEEPERMAP_EXT);
  410.         openDialog.setFileFilter(fileFilter);
  411.         int dialogReturn = openDialog.showOpenDialog(whatCalled);
  412.        
  413.         if (dialogReturn != JFileChooser.CANCEL_OPTION) {
  414.             String theGame="";
  415.             File openFile = openDialog.getSelectedFile();
  416.             try {
  417.                 Scanner lineBuffer = new Scanner(openFile);
  418.                 while (lineBuffer.hasNextLine()) {
  419.                     theGame = lineBuffer.nextLine();
  420.                 }
  421.                 lineBuffer.close();
  422.             }
  423.             catch (FileNotFoundException e) {
  424.                 System.out.println("Couldn't find file.");
  425.                 return false;
  426.             }
  427.             setGameStringBuffer(theGame);
  428.             updateSettingsFromLoad();
  429.         }
  430.         return true;
  431.     }
  432.    
  433.    
  434. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement