Java战舰问题

时间:2012-03-21 20:06:35

标签: java swing

我必须为星期五设计一个蝙蝠侠游戏,但我正在做的课程似乎已经跳过了一些事情,因为虽然我管理了所有其他任务,但最后的项目令人难以置信地高于我的掌握,但我必须做点什么。

我有以下GUI代码,它给了我我的播放网格,但我绝对不知道如何做以下事情

  1. 将船舶分配给某些单元格 - 并将这些单元格着色以反映此
  2. 如何进行实际击中,未命中,沉没和更新网格
  3. 我认为如果我至少可以做这些我可以复制cpu的代码,但我sooooooo卡住所以任何帮助真的很感激,请大家工作一些魔术:)

    /**
     * BattleGui: 
     * 
     */
    
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    
    public class BattleGui implements ActionListener 
    {
        // Default filename to use for saving and loading files
        // Possible improvement: replace with a FileChooser
        private final static String DEFAULT_FILENAME = "battlegui.txt";
        private int GRID_SIZE = 8;
        private JButton [] buttonArray; 
    
        public JMenuBar createMenu() 
        {
            JMenuBar menuBar  = new JMenuBar();;
            JMenu menu = new JMenu("Battle Menu");
            JMenuItem menuItem;
    
            menuBar.add(menu);
    
            // A group of JMenuItems. You can create other menu items here if desired
            menuItem = new JMenuItem("New Game");
            menuItem.addActionListener(this);
            menu.add(menuItem);
    
            menuItem = new JMenuItem("Load Game");
            menuItem.addActionListener(this);
            menu.add(menuItem);
    
            menuItem = new JMenuItem("Save Game");
            menuItem.addActionListener(this);
            menu.add(menuItem);
    
            menuItem = new JMenuItem("Quit");
            menuItem.addActionListener(this);
            menu.add(menuItem);        
    
            //a submenu
            menu.addSeparator();
            return menuBar;
        }
    
        public  Container createContentPaneCPU() 
        {
            int numButtons = GRID_SIZE * GRID_SIZE;
            JPanel grid = new JPanel(new GridLayout(GRID_SIZE,GRID_SIZE));
            buttonArray = new JButton[numButtons];
    
    
            for (int i=0; i<numButtons; i++)
            {
                buttonArray[i] = new JButton(" ");
    
                // This label is used to identify which button was clicked in the action listener
                buttonArray[i].setActionCommand("" + i); // String "0", "1" etc.
                buttonArray[i].addActionListener(this);
                grid.add(buttonArray[i]);
    
            }
            return grid;
        }
    
        public  Container createContentPane() 
        {
            int numButtons = GRID_SIZE * GRID_SIZE;
            JPanel grid = new JPanel(new GridLayout(GRID_SIZE,GRID_SIZE));
            buttonArray = new JButton[numButtons];
    
            for (int i=0; i<numButtons; i++)
            {
                buttonArray[i] = new JButton(" ");
    
                // This label is used to identify which button was clicked in the action listener
                //buttonArray[i].setActionCommand("" + i); // String "0", "1" etc.
               // buttonArray[i].addActionListener(this);
                grid.add(buttonArray[i]);
            }
            return grid;
        }    
    
        /**
         * This method handles events from the Menu and the board.
         *
         */
        public void actionPerformed(ActionEvent e) 
        {
            String classname = getClassName(e.getSource());
            JComponent component = (JComponent)(e.getSource());
    
            if (classname.equals("JMenuItem"))
            {
                JMenuItem menusource = (JMenuItem)(e.getSource());
                String menutext  = menusource.getText();
    
                // Determine which menu option was chosen
                if (menutext.equals("Load Game"))
                {
                    /* BATTLEGUI    Add your code here to handle Load Game **********/
                    LoadGame();
                }
                else if (menutext.equals("Save Game"))
                {
                    /* BATTLEGUI    Add your code here to handle Save Game **********/
                    SaveGame();
                }
                else if (menutext.equals("New Game"))
                {
                    /* BATTLEGUI    Add your code here to handle Save Game **********/
                    NewGame();
                }
            }
            // Handle the event from the user clicking on a command button
            else if (classname.equals("JButton"))
            {
                JButton button = (JButton)(e.getSource());
                int bnum = Integer.parseInt(button.getActionCommand());
                int row = bnum / GRID_SIZE;
                int col = bnum % GRID_SIZE;
                System.out.println(e.getSource());
    
                /* BATTLEGUI    Add your code here to handle user clicking on the grid ***********/
                button.setBackground(Color.GREEN);
                fireShot(row, col);
            }  
        }
    
    
    
        /**
         *  Returns the class name
         */
        protected String getClassName(Object o) 
        {
            String classString = o.getClass().getName();
            int dotIndex = classString.lastIndexOf(".");
            return classString.substring(dotIndex+1);
        }
    
        /**
         * Create the GUI and show it.
         * For thread safety, this method should be invoked from the event-dispatching thread.
         */
        private static void createAndShowGUI() 
        {
            // Create and set up the window.
            JFrame frame = new JFrame("Battleships");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            int maxGap = 20;
            int ButtonWidth = 20;
            int ButtonHeight = 1;
    
    
            BattleGui battlegui = new BattleGui();
            frame.setJMenuBar(battlegui.createMenu());
            JPanel gui = new JPanel(new GridLayout(2,2,20,5));
            gui.setBorder(new EmptyBorder(5,5,5,5));
            //Set up components preferred size
            JButton b = new JButton("Just fake button");
            Dimension buttonSize = b.getPreferredSize();
    
            gui.add(new JButton("Player"));
            gui.add(new JButton("CPU"));
             b.setPreferredSize(new Dimension(ButtonWidth, ButtonHeight));
            gui.add(battlegui.createContentPane());
            gui.add(battlegui.createContentPaneCPU());
            frame.setContentPane(gui);
            // Create and set up the content pane.
            /*
            BattleGui battlegui = new BattleGui();
            frame.setJMenuBar(battlegui.createMenu());
            frame.setContentPane(battlegui.createContentPane());
            */
    
            // Display the window, setting the size
            frame.setSize(800, 600);
            frame.setVisible(true);
        }
    
        /**
         * Sets a Gui grid square at row, col to display a character
         */
        public boolean setGuiSquare(int row, int col, char c)
        {
            int bnum = row * GRID_SIZE + col;
            if (bnum >= (GRID_SIZE*GRID_SIZE))
            {
                return false;
            }
            else
            {
                buttonArray[bnum].setText(Character.toString(c));
            }
            return true;
        }
    
        /**
         * This is a standard main function for a Java GUI
         */
        public static void main(String[] args) 
        {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() 
            {
                public void run() 
                {
    
                    createAndShowGUI();
                    //Deploy();
                }
            });
        }
    
        //************************************************************************
        //*** BATTLEGUI: Modify the methods below to respond to Menu and Mouse click events
    
        /**
         * This method is called from the Menu event: New Game.
         * BATTLEGUI
         */
        public void NewGame()
        {
             System.out.println("New game selected");
    
        }
    
    
        /**
         * This method is called from the Menu event: Load Game.
         * BATTLEGUI
         */
        public void LoadGame()
        {
              System.out.println("Load game selected");
        }
    
    
        /**
         * This method is called from the Menu event: Save Game.
         * BATTLEGUI
         */
        public void SaveGame()
        {
              System.out.println("Save game selected");
        }
    
        /**
         * This method is called from the Mouse Click event.
         * BATTLEGUI
         */
        public void fireShot(int row, int col)
        {
              System.out.println("Fire shot selected: at (" + row + ", " + col + ")");
        }
    
    
    
    }
    

1 个答案:

答案 0 :(得分:4)

我建议,退一步思考问题领域。

你有一个BattleScene,其中包含BattleSquares。每个battleSquare可以有最多1艘船,并且可以有颜色。您还有Ship对象(可以属于特定的玩​​家,表明它是否已损坏)......

BattleSquare需要确定它是Hit还是Miss,因为它拥有所有信息。它知道它有没有船。

/**true if had a ship, false if it was a miss
    */
public class BattleSquare{     
        public boolean processHit(){
             if (hasShip()){
                ship.setState(DESTROYED);
               return true;
             }
            return false;
        }
        public void setShip(Ship ship){ .... }
        public boolean hasShip() { ... } }   ... methods for color too

如果您将代码隔离到可管理的代码段中,某些类代表模型,您将能够更好地管理事物。你似乎把所有东西混合在一个类中,因此感到迷茫。

同样,您的BattleScene将包含List BattleSquares。一旦你开火,你可以单独寻找一个特定的BattleSquare并告诉它自己处理。如果是点击,则更新状态。

想法是你的模型类只负责管理状态。您的控制器类可以触发视图拦截的事件,更新模型并自行刷新。

希望它有所帮助。