⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mainframe.java

📁 Java五子棋 支持本地游戏
💻 JAVA
字号:
import java.awt.*;
import java.awt.event.*;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;

import javax.swing.*;
import java.net.*;
import java.io.*;

/**
 * @author JiangLei
 * 
 * This class MainFrame initialize the main frame of the program
 * 
 *
 */


public class MainFrame extends JFrame
{
    private static final long serialVersionUID = 1L;
    //port for chess game
    public static final int chessPort = 5678;
    //port for chat between server and client
    public static final int chatPort = 6789;
    //the following parameter sets the layout of the frame
    public final int marginX = 30;
    public final int marginY = 30;
    public final int frameSizeX = 840;
    public final int frameSizeY = 630;
    //pointer to itself
    static public MainFrame mainFrame ;
    
    private JMenuBar myMenuBar;
    private JMenu fileMenu;
    //private JMenu optionMenu;
    //private JMenu helpMenu;
    private JMenuItem localGameMenu;
    private JMenuItem computerGameMenu;
    private JMenu netGameMenu;
    //private JMenuItem loadMenu;
    //private JMenuItem saveMenu;
    private JMenuItem exitMenu;
    //private JMenuItem aboutMenu;
    //private JMenuItem opMenu;
    private JMenuItem windowsMenu;
    public JButton startGameBn;

    //the chess game we are playing
    private ChessGame game;
    //dialog
    NetGameInitDialog dialog;

    /**
     * This method initializes myMenuBar
     *
     * @return javax.swing.JMenuBar
     */
    
    private JMenuBar getMyMenuBar() {
        if (myMenuBar == null) {
            myMenuBar = new JMenuBar();
            myMenuBar.add(getGameManageMenu());
            //myMenuBar.add(getOptionMenu());
            //myMenuBar.add(getHelpMenu());
        }
        return myMenuBar;
    }
    
    /**
     * This method initializes fileMenu
     *
     * @return javax.swing.JMenu
     */
    private JMenu getGameManageMenu() {
        if (fileMenu == null) {
            fileMenu = new JMenu();
            fileMenu.setText("游戏");
            fileMenu.setMnemonic(KeyEvent.VK_F);
            fileMenu.add(getLocalGameMenu());
            fileMenu.add(getComputerGameMenu());
            fileMenu.add(getNetGameMenu());
            //fileMenu.add(getLoadMenu());
            //fileMenu.add(getSaveMenu());
            fileMenu.add(getExitMenu());
        }
        return fileMenu;
    }
    

/*    private JMenu getOptionMenu() {
        if (optionMenu == null) {
            optionMenu = new JMenu();
            optionMenu.setText("选项");
            optionMenu.setMnemonic(KeyEvent.VK_O);
            optionMenu.add(getOpMenu());
        }
        return optionMenu;
    }*/
    
/*    private JMenu getHelpMenu() {
        if (helpMenu == null) {
            helpMenu = new JMenu("帮助");
            helpMenu.setMnemonic(KeyEvent.VK_H);
            helpMenu.add(getAboutMenu());
        }
        return helpMenu;
    }
*/  
    
    
    
    /**
     * 
     * this method sets the layout of the main frame
     *  
     * 
     */
    private void setMainPanel()
    {
    	localGameMenu.setEnabled(false);
    	computerGameMenu.setEnabled(false);
    	netGameMenu.setEnabled(false);
    	//add the renju board and set its location
		add(game.cpad);
		game.cpad.setLocation(marginX, marginY);
		
		//the the player status panel and set its location
		add(game.playerPanelA);
		add(game.playerPanelB);
		game.playerPanelA.setLocation(2 * marginX + game.cpad.sizeX, marginY);
		game.playerPanelB.setLocation(2 * marginX + game.cpad.sizeX, 2 * marginY + PlayerStatusPanel.height);
		
		//add the start game button
    	JPanel p = new JPanel();
    	startGameBn = new JButton("开始游戏");
		p.add(startGameBn);
		p.setSize(6 * marginX, 2 * marginY);
		
		//add its action listener
		startGameBn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				startGameBn.setEnabled(false);
				
				//if it's not a net game, start the game immediately
				if(game.gameType != GameType.NetGame)
					game.startGame();
				else
				{
					//else wait for the server and client to reach an agreement
					try{
						game.sock.getOutputStream().write(1);
						if(game.sock.getInputStream().read() == 1)
						{	
							game.startGame();
						}
					}
					catch(IOException ex)
					{
						System.out.println("Connection Error!");
					}
				}
			}
		});
		//p.setBackground(Color.white);
		p.setLocation(marginX, 3 * marginY / 2 + game.cpad.sizeY);
		add(p);
		
		
/*		JButton evaluationBn = new JButton("Evaluation");
		p.add(evaluationBn);
		evaluationBn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				Evaluation eval = new Evaluation(game.mapSize);
				boolean t = (game.activePlayer.chessMan == ChessMan.White)?true:false;
				
				eval.analysisBoard(game.chessMap);
				
				int score = eval.evaluate(game.chessMap, t);
				System.out.println(score);
				
				System.out.println();
				for(int i = 0; i < 8; i++)
					System.out.print(eval.blackTypeCount[i] + " ");
				
				System.out.println();
				for(int i = 0; i < 8; i++)
					System.out.print(eval.whiteTypeCount[i] + " ");
			}
		});*/

		//if it's a net game, add chat panel on the frame
		if(game.gameType == GameType.NetGame)
		{
			ChatPanel p1 = new ChatPanel(game);
			p1.setLocation(2 * marginX + game.cpad.sizeX, 3 * marginY + 2 * PlayerStatusPanel.height);
			add(p1);
		}
		
		//refresh the main frame
		setVisible(true);
    }
   
    /**
     * This method initializes local game menu
     *
     * @return javax.swing.JMenuItem
     */
    private JMenuItem getLocalGameMenu() {
        //add menu item
    	localGameMenu = new JMenuItem("单机游戏");
        //add its action listener
        localGameMenu.addActionListener(new ActionListener() {
       		public void actionPerformed(ActionEvent e){
				 //set up the local game
       			 LocalGameInitDialog dialog = new LocalGameInitDialog(mainFrame, 270, 140);
				 dialog.setLocation(400, 300);
				 dialog.setVisible(true);
				 if(dialog.dialogResult == false)
					 return;
				 //initialize player information
				 Player playerA = new Player(dialog.tf1.getText(), ChessMan.Black);
				 Player playerB = new Player(dialog.tf2.getText(), ChessMan.White);
				 //initialize the game
				 game = new ChessGame(playerA, playerB, playerA, dialog.totalSeconds, GameType.LocalGame);
				 //set main frame layout
				 setMainPanel();
    		}
        });
        return localGameMenu;
    }
 
    /**
     * This method initializes local game menu
     *
     * @return javax.swing.JMenuItem
     */
    private JMenuItem getComputerGameMenu() {
        if (computerGameMenu == null) {
        	//add menu item
        	computerGameMenu = new JMenuItem("人机对战");
        	
        	//add action listener
        	computerGameMenu.addActionListener(new ActionListener() {
	       		public void actionPerformed(ActionEvent e){
	       			//initialize the setting dialog
	       			ComputerGameDialog dialog = new ComputerGameDialog(mainFrame, 250, 180);
	       			dialog.setVisible(true);
        			if(dialog.dialogResult == false)
        				return;
        			
        			//initialize the player information and game
        			Player localPlayer = new Player(dialog.nameTf.getText(), dialog.chessMan);
        			if(dialog.chessMan == ChessMan.Black)
        			{
    					Player computerPlayer = new Player("Light Blue", ChessMan.White);
    					game = new ChessGame(localPlayer, computerPlayer, localPlayer, dialog.totalSeconds, GameType.ComputerGame);
        			}
        			else
        			{
    					Player computerPlayer = new Player("Light Blue", ChessMan.Black);
    					game = new ChessGame(computerPlayer, localPlayer, localPlayer, dialog.totalSeconds, GameType.ComputerGame);
        			}

        			//set main frame layout
        			setMainPanel();
	        	}
         	});
        }
        return computerGameMenu;
    }    
    
    /**
     * This method initializes net game menu
     *
     * @return javax.swing.JMenuItem
     */
    private JMenu getNetGameMenu() {
        if (netGameMenu == null) {
        	netGameMenu = new JMenu("网络对战");
        	//create the menu items for net game
        	JMenuItem createGameMenuItem = new JMenuItem("创建游戏");
        	JMenuItem joinGameMenuItem = new JMenuItem("加入游戏");
        	
        	//set up the create game action listener
        	createGameMenuItem.addActionListener(new ActionListener() {
        		public void actionPerformed(ActionEvent e){
        			//set up the game
        			dialog = new NetGameInitDialog(mainFrame, 220, 180);
					//System.out.println("Waiting for client to join game!");
        			dialog.setVisible(true);
        			if(dialog.dialogResult == false)
        				return;

        			//show the waiting dialog
        			WaitingDialog dialog1 = new WaitingDialog(mainFrame, 220, 120, dialog);
        			dialog1.setVisible(true);
        			if(dialog1.dialogResult == false)
        				return;
        			
        			//initialize the game and the player
        			Player localPlayer = new Player(dialog.tf1.getText(), dialog.chessMan);
        			if(dialog.chessMan == ChessMan.Black)
        			{
    					Player netPlayer = new Player(dialog.p2Name, ChessMan.White);
    					game = new ChessGame(localPlayer, netPlayer, localPlayer, dialog.totalSeconds, GameType.NetGame);
        			}
        			else
        			{
    					Player netPlayer = new Player(dialog.p2Name, ChessMan.Black);
    					game = new ChessGame(netPlayer, localPlayer, localPlayer, dialog.totalSeconds, GameType.NetGame);
        			}
        			//add socket to the game
        			game.sock = dialog1.sock;
					game.chatSock = dialog1.chatSock;
					//set the main frame layout
					setMainPanel();
        		}
        	});
        	
        	//set up the join game action listener
        	joinGameMenuItem.addActionListener(new ActionListener(){
        		public void actionPerformed(ActionEvent e){
        			//connect to the server
        			NetGameClientDialog dialog = new NetGameClientDialog(mainFrame, 220, 140);
        			dialog.setVisible(true);
        			if(dialog.dialogResult == false)
        				return;	   	   			 
 					//System.out.println("joining game!");
         			
        			//initialize the game 
        			Player localPlayer = new Player(dialog.tf.getText(), dialog.chessMan);
        			if(dialog.chessMan == ChessMan.Black)
        			{
    					Player netPlayer = new Player(dialog.p2Name, ChessMan.White);
    					game = new ChessGame(localPlayer, netPlayer, localPlayer, dialog.totalSeconds, GameType.NetGame);
        			}
        			else
        			{
    					Player netPlayer = new Player(dialog.p2Name, ChessMan.Black);
    					game = new ChessGame(netPlayer, localPlayer, localPlayer, dialog.totalSeconds, GameType.NetGame);
        			}
        			
        			//add sock to the game
					game.sock = dialog.sock;
					game.chatSock = dialog.chatSock;
					
					//set main panel layout
					setMainPanel();
        		}
        	});
        	
        	//add menu item to menu
           	netGameMenu.add(createGameMenuItem);
        	netGameMenu.add(joinGameMenuItem);
        }
        return netGameMenu;
    }
    
/*    *//**
     * This method initializes loadMenu
     *
     * @return javax.swing.JMenuItem
     *//*
    private JMenuItem getLoadMenu() {
        if (loadMenu == null) {
            loadMenu = new JMenuItem();
        }
        loadMenu.setText("载入");
        loadMenu.setEnabled(false);
        return loadMenu;
    }
    
    *//**
     * This method initializes saveMenu
     *
     * @return javax.swing.JMenuItem
     *//*
    private JMenuItem getSaveMenu() {
        if (saveMenu == null) {
            saveMenu = new JMenuItem();
        }
        saveMenu.setText("保存");
        saveMenu.setEnabled(false);
        return saveMenu;
    }*/
    
    /**
     * This method initializes exitMenu
     *
     * @return javax.swing.JMenuItem
     */
    private JMenuItem getExitMenu() {
        if (exitMenu == null) {
            exitMenu = new JMenuItem();
        }
        fileMenu.addSeparator();
        exitMenu.setText("退出");
        exitMenu.addActionListener(new ActionListener(){
    		public void actionPerformed(ActionEvent e){
    			System.exit(0);
    		}
    	});
        return exitMenu;
    }
    
/*    *//**
     * This method initializes aboutMenu
     *
     * @return javax.swing.JMenuItem
     *//*
    private JMenuItem getAboutMenu() {
        if (aboutMenu == null) {
            aboutMenu = new JMenuItem();
        }
        aboutMenu.setText("关于");
        aboutMenu.addActionListener(new ActionListener(){
    		public void actionPerformed(ActionEvent e){
    			//about
    		}
    	});
        return aboutMenu;
    }
    
    *//**
     * This method initializes opMenu
     *
     * @return javax.swing.JMenuItem
     *//*
    private JMenuItem getOpMenu() {
        if (opMenu == null) {
            opMenu = new JMenuItem();
        }
        opMenu.setText("选项");
        opMenu.addActionListener(new ActionListener(){
    		public void actionPerformed(ActionEvent e){
    			
    		}
    	});
        return opMenu;
    }*/
    

    public void setWindowsMenu(boolean isEnable){
        windowsMenu.setEnabled(isEnable);
    }
    
    public MainFrame()
	{
    	super();
    	MainFrame.mainFrame = this;
        this.setTitle("五子棋");
		this.setSize(frameSizeX, frameSizeY);
        this.setLayout(null);
        this.setJMenuBar(getMyMenuBar());
        this.setJMenuBar(getMyMenuBar());
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLocation(200, 100);

		addWindowListener(new WindowAdapter()
        {public void windowClosing(WindowEvent e)
             {System.exit(0);}
             });
		this.setVisible(true);
		
		//System.out.println("Constructor finished!");
	}
	
	public static void main(String [] args)
	{
		MainFrame mainForm = new MainFrame();
		//mainForm.setVisible(true);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -