Java TicTacToe

TicTacToeServer.java

Sample Screen-shots

   

 

See Client


TicTacToeServer.java

// Fig. 28.11: TicTacToeServer.java
// Server side of client/server Tic-Tac-Toe program.
import java.awt.BorderLayout;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class TicTacToeServer extends JFrame 
{
   private String[] board = new String[9]; // tic-tac-toe board
   private JTextArea outputArea; // for outputting moves
   private Player[] players; // array of Players
   private ServerSocket server; // server socket to connect with clients
   private int currentPlayer; // keeps track of player with current move
   private final static int PLAYER_X = 0; // constant for first player
   private final static int PLAYER_O = 1; // constant for second player
   private final static String[] MARKS = {"X", "O"}; // array of marks
   private ExecutorService runGame; // will run players
   private Lock gameLock; // to lock game for synchronization
   private Condition otherPlayerConnected; // to wait for other player
   private Condition otherPlayerTurn; // to wait for other player's turn

   // set up tic-tac-toe server and GUI that displays messages
   public TicTacToeServer()
   {
      super("Tic-Tac-Toe Server"); // set title of window

      // create ExecutorService with a thread for each player
      runGame = Executors.newFixedThreadPool(2);
      gameLock = new ReentrantLock(); // create lock for game

      // condition variable for both players being connected
      otherPlayerConnected = gameLock.newCondition();

      // condition variable for the other player's turn
      otherPlayerTurn = gameLock.newCondition();      

      for (int i = 0; i < 9; i++)
         board[i] = new String(""); // create tic-tac-toe board
      players = new Player[2]; // create array of players
      currentPlayer = PLAYER_X; // set current player to first player
 
      try
      {
         server = new ServerSocket(12345, 2); // set up ServerSocket
      } 
      catch (IOException ioException) 
      {
         ioException.printStackTrace();
         System.exit(1);
      } 

      outputArea = new JTextArea(); // create JTextArea for output
      add(outputArea, BorderLayout.CENTER);
      outputArea.setText("Server awaiting connections\n");

      setSize(300, 300); // set size of window
      setVisible(true); // show window
   }

   // wait for two connections so game can be played
   public void execute()
   {
      // wait for each client to connect
      for (int i = 0; i < players.length; i++) 
      {
         try // wait for connection, create Player, start runnable
         {
            players[i] = new Player(server.accept(), i);
            runGame.execute(players[i]); // execute player runnable
         } 
         catch (IOException ioException) 
         {
            ioException.printStackTrace();
            System.exit(1);
         } 
      }

      gameLock.lock(); // lock game to signal player X's thread

      try
      {
         players[PLAYER_X].setSuspended(false); // resume player X
         otherPlayerConnected.signal(); // wake up player X's thread
      } 
      finally
      {
         gameLock.unlock(); // unlock game after signalling player X
      } 
   }

   // display message in outputArea
   private void displayMessage(final String messageToDisplay)
   {
      // display message from event-dispatch thread of execution
      SwingUtilities.invokeLater(
         new Runnable() 
         {
            public void run() // updates outputArea
            {
               outputArea.append(messageToDisplay); // add message
            } 
         } 
      ); 
   } 

   // determine if move is valid
   public boolean validateAndMove(int location, int player)
   {
      // while not current player, must wait for turn
      while (player != currentPlayer) 
      {
         gameLock.lock(); // lock game to wait for other player to go

         try 
         {
            otherPlayerTurn.await(); // wait for player's turn
         } 
         catch (InterruptedException exception)
         {
            exception.printStackTrace();
         } 
         finally
         {
            gameLock.unlock(); // unlock game after waiting
         } 
      } 

      // if location not occupied, make move
      if (!isOccupied(location))
      {
         board[location] = MARKS[currentPlayer]; // set move on board
         currentPlayer = (currentPlayer + 1) % 2; // change player

         // let new current player know that move occurred
         players[currentPlayer].otherPlayerMoved(location);

         gameLock.lock(); // lock game to signal other player to go

         try 
         {
            otherPlayerTurn.signal(); // signal other player to continue
         } 
         finally
         {
            gameLock.unlock(); // unlock game after signaling
         } 

         return true; // notify player that move was valid
      } 
      else // move was not valid
         return false; // notify player that move was invalid
   }

   // determine whether location is occupied
   public boolean isOccupied(int location)
   {
      if (board[location].equals(MARKS[PLAYER_X]) || 
         board [location].equals(MARKS[PLAYER_O]))
         return true; // location is occupied
      else
         return false; // location is not occupied
   }

   // place code in this method to determine whether game over 
   public boolean isGameOver()
   {
      return false; // this is left as an exercise
   }

   // private inner class Player manages each Player as a runnable
   private class Player implements Runnable 
   {
      private Socket connection; // connection to client
      private Scanner input; // input from client
      private Formatter output; // output to client
      private int playerNumber; // tracks which player this is
      private String mark; // mark for this player
      private boolean suspended = true; // whether thread is suspended

      // set up Player thread
      public Player(Socket socket, int number)
      {
         playerNumber = number; // store this player's number
         mark = MARKS[playerNumber]; // specify player's mark
         connection = socket; // store socket for client
         
         try // obtain streams from Socket
         {
            input = new Scanner(connection.getInputStream());
            output = new Formatter(connection.getOutputStream());
         } 
         catch (IOException ioException) 
         {
            ioException.printStackTrace();
            System.exit(1);
         } 
      }

      // send message that other player moved
      public void otherPlayerMoved(int location)
      {
         output.format("Opponent moved\n");
         output.format("%d\n", location); // send location of move
         output.flush(); // flush output
      }

      // control thread's execution
      public void run()
      {
         // send client its mark (X or O), process messages from client
         try 
         {
            displayMessage("Player " + mark + " connected\n");
            output.format("%s\n", mark); // send player's mark
            output.flush(); // flush output

            // if player X, wait for another player to arrive
            if (playerNumber == PLAYER_X) 
            {
               output.format("%s\n%s", "Player X connected",
                  "Waiting for another player\n");
               output.flush(); // flush output

               gameLock.lock(); // lock game to  wait for second player

               try 
               {
                  while(suspended)
                  {
                     otherPlayerConnected.await(); // wait for player O
                  } 
               }  
               catch (InterruptedException exception) 
               {
                  exception.printStackTrace();
               } 
               finally
               {
                  gameLock.unlock(); // unlock game after second player
               } 

               // send message that other player connected
               output.format("Other player connected. Your move.\n");
               output.flush(); // flush output
            } 
            else
            {
               output.format("Player O connected, please wait\n");
               output.flush(); // flush output
            } 

            // while game not over
            while (!isGameOver()) 
            {
               int location = 0; // initialize move location

               if (input.hasNext())
                  location = input.nextInt(); // get move location

               // check for valid move
               if (validateAndMove(location, playerNumber)) 
               {
                  displayMessage("\nlocation: " + location);
                  output.format("Valid move.\n"); // notify client
                  output.flush(); // flush output
               } 
               else // move was invalid
               {
                  output.format("Invalid move, try again\n");
                  output.flush(); // flush output
               } 
            } 
         } 
         finally
         {
            try
            {
               connection.close(); // close connection to client
            } 
            catch (IOException ioException) 
            {
               ioException.printStackTrace();
               System.exit(1);
            } 
         } 
      }

      // set whether or not thread is suspended
      public void setSuspended(boolean status)
      {
         suspended = status; // set value of suspended
      }
   }

   public static void main(String[] args)
   {
      TicTacToeServer application = new TicTacToeServer();
      application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      application.execute();
   } 
}

TicTacToeClient.java

Sample screen-shots

   

See Server


TicTacToeClient.java

// Fig. 28.13: TicTacToeClient.java
// Client side of client/server Tic-Tac-Toe program.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.Socket;
import java.net.InetAddress;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

public class TicTacToeClient extends JFrame implements Runnable 
{
   private JTextField idField; // textfield to display player's mark
   private JTextArea displayArea; // JTextArea to display output
   private JPanel boardPanel; // panel for tic-tac-toe board
   private JPanel panel2; // panel to hold board
   private Square[][] board; // tic-tac-toe board
   private Square currentSquare; // current square
   private Socket connection; // connection to server
   private Scanner input; // input from server
   private Formatter output; // output to server
   private String ticTacToeHost; // host name for server
   private String myMark; // this client's mark
   private boolean myTurn; // determines which client's turn it is
   private final String X_MARK = "X"; // mark for first client
   private final String O_MARK = "O"; // mark for second client

   // set up user-interface and board
   public TicTacToeClient(String host)
   { 
      ticTacToeHost = host; // set name of server
      displayArea = new JTextArea(4, 30); // set up JTextArea
      displayArea.setEditable(false);
      add(new JScrollPane(displayArea), BorderLayout.SOUTH);

      boardPanel = new JPanel(); // set up panel for squares in board
      boardPanel.setLayout(new GridLayout(3, 3, 0, 0));

      board = new Square[3][3]; // create board

      // loop over the rows in the board
      for (int row = 0; row < board.length; row++) 
      {
         // loop over the columns in the board
         for (int column = 0; column < board[row].length; column++) 
         {
            // create square
            board[row][column] = new Square(" ", row * 3 + column);
            boardPanel.add(board[row][column]); // add square       
         }
      } 

      idField = new JTextField(); // set up textfield
      idField.setEditable(false);
      add(idField, BorderLayout.NORTH);
      
      panel2 = new JPanel(); // set up panel to contain boardPanel
      panel2.add(boardPanel, BorderLayout.CENTER); // add board panel
      add(panel2, BorderLayout.CENTER); // add container panel

      setSize(300, 225); // set size of window
      setVisible(true); // show window

      startClient();
   }

   // start the client thread
   public void startClient()
   {
      try // connect to server and get streams
      {
         // make connection to server
         connection = new Socket(
            InetAddress.getByName(ticTacToeHost), 12345);

         // get streams for input and output
         input = new Scanner(connection.getInputStream());
         output = new Formatter(connection.getOutputStream());
      } 
      catch (IOException ioException)
      {
         ioException.printStackTrace();         
      } 

      // create and start worker thread for this client
      ExecutorService worker = Executors.newFixedThreadPool(1);
      worker.execute(this); // execute client
   }

   // control thread that allows continuous update of displayArea
   public void run()
   {
      myMark = input.nextLine(); // get player's mark (X or O)

      SwingUtilities.invokeLater(
         new Runnable() 
         {         
            public void run()
            {
               // display player's mark
               idField.setText("You are player \"" + myMark + "\"");
            } 
         } 
      ); 
            
      myTurn = (myMark.equals(X_MARK)); // determine if client's turn

      // receive messages sent to client and output them
      while (true)
      {
         if (input.hasNextLine())
            processMessage(input.nextLine());
      } 
   }

   // process messages received by client
   private void processMessage(String message)
   {
      // valid move occurred
      if (message.equals("Valid move.")) 
      {
         displayMessage("Valid move, please wait.\n");
         setMark(currentSquare, myMark); // set mark in square
      } 
      else if (message.equals("Invalid move, try again")) 
      {
         displayMessage(message + "\n"); // display invalid move
         myTurn = true; // still this client's turn
      }  
      else if (message.equals("Opponent moved")) 
      {
         int location = input.nextInt(); // get move location
         input.nextLine(); // skip newline after int location
         int row = location / 3; // calculate row
         int column = location % 3; // calculate column

         setMark(board[row][column], 
            (myMark.equals(X_MARK) ? O_MARK : X_MARK)); // mark move                
         displayMessage("Opponent moved. Your turn.\n");
         myTurn = true; // now this client's turn
      }  
      else
         displayMessage(message + "\n"); // display the message
   }

   // manipulate displayArea in event-dispatch thread
   private void displayMessage(final String messageToDisplay)
   {
      SwingUtilities.invokeLater(
         new Runnable() 
         {
            public void run() 
            {
               displayArea.append(messageToDisplay); // updates output
            } 
         } 
      ); 
   } 

   // utility method to set mark on board in event-dispatch thread
   private void setMark(final Square squareToMark, final String mark)
   {
      SwingUtilities.invokeLater(
         new Runnable() 
         {
            public void run()
            {
               squareToMark.setMark(mark); // set mark in square
            } 
         } 
      ); 
   } 

   // send message to server indicating clicked square
   public void sendClickedSquare(int location)
   {
      // if it is my turn
      if (myTurn) 
      {
         output.format("%d\n", location); // send location to server
         output.flush();
         myTurn = false; // not my turn any more
      } 
   }

   // set current Square
   public void setCurrentSquare(Square square)
   {
      currentSquare = square; // set current square to argument
   }

   // private inner class for the squares on the board
   private class Square extends JPanel 
   {
      private String mark; // mark to be drawn in this square
      private int location; // location of square
   
      public Square(String squareMark, int squareLocation)
      {
         mark = squareMark; // set mark for this square
         location = squareLocation; // set location of this square

         addMouseListener(
            new MouseAdapter() 
            {
               public void mouseReleased(MouseEvent e)
               {
                  setCurrentSquare(Square.this); // set current square

                  // send location of this square
                  sendClickedSquare(getSquareLocation());
               } 
            } 
         ); 
      } 

      // return preferred size of Square
      public Dimension getPreferredSize() 
      { 
         return new Dimension(30, 30); // return preferred size
      }

      // return minimum size of Square
      public Dimension getMinimumSize() 
      {
         return getPreferredSize(); // return preferred size
      }

      // set mark for Square
      public void setMark(String newMark) 
      { 
         mark = newMark; // set mark of square
         repaint(); // repaint square
      }

      // return Square location
      public int getSquareLocation() 
      {
         return location; // return location of square
      }

      // draw Square
      public void paintComponent(Graphics g)
      {
         super.paintComponent(g);

         g.drawRect(0, 0, 29, 29); // draw square
         g.drawString(mark, 11, 20); // draw mark   
      } 
   }

   public static void main(String[] args)
   {
      TicTacToeClient application; // declare client application

      // if no command line args
      if (args.length == 0)
         application = new TicTacToeClient("127.0.0.1"); // localhost
      else
         application = new TicTacToeClient(args[0]); // use args

      application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   } 

}


Maintained by John Loomis, updated Sun Apr 09 17:09:04 2017


Maintained by John Loomis, updated Sun Apr 09 17:08:54 2017

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.*; class clientThread extends Thread { chessClient chessclient; clientThread(chessClient chessclient) { this.chessclient=chessclient; } public void acceptMessage(String recMessage) { if(recMessage.startsWith("/userlist ")) { StringTokenizer userToken=new StringTokenizer(recMessage," "); int userNumber=0; chessclient.userpad.userList.removeAll(); chessclient.inputpad.userChoice.removeAll(); chessclient.inputpad.userChoice.addItem("所有人"); while(userToken.hasMoreTokens()) { String user=(String)userToken.nextToken(" "); if(userNumber>0 && !user.startsWith("[inchess]")) { chessclient.userpad.userList.add(user); chessclient.inputpad.userChoice.addItem(user); } userNumber++; } chessclient.inputpad.userChoice.select("所有人"); } else if(recMessage.startsWith("/yourname ")) { chessclient.chessClientName=recMessage.substring(10); chessclient.setTitle("Java五子棋客户端 "+"用户名:"+chessclient.chessClientName); } else if(recMessage.equals("/reject")) { try { chessclient.chesspad.statusText.setText("不能加入游戏"); chessclient.controlpad.cancelGameButton.setEnabled(false); chessclient.controlpad.joinGameButton.setEnabled(true); chessclient.controlpad.creatGameButton.setEnabled(true); } catch(Exception ef) { chessclient.chatpad.chatLineArea.setText("chessclient.chesspad.chessSocket.close无法关闭"); } chessclient.controlpad.joinGameButton.setEnabled(true); } else if(recMessage.startsWith("/peer ")) { chessclient.chesspad.chessPeerName=recMessage.substring(6); if(chessclient.isServer) { chessclient.chesspad.chessColor=1; chessclient.chesspad.isMouseEnabled=true; chessclient.chesspad.statusText.setText("请黑棋下子"); } else if(chessclient.isClient) { chessclient.chesspad.chessColor=-1; chessclient.chesspad.statusText.setText("已加入游戏,等待对方下子..."); } } else if(recMessage.equals("/youwin")) { chessclient.isOnChess=false; chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor); chessclient.chesspad.statusText.setText("对方退出,请点放弃游戏退出连接"); chessclient.chesspad.isMouseEnabled=false; } else if(recMessage.equals("/OK")) { chessclient.chesspad.statusText.setText("创建游戏成功,等待别人加入..."); } else if(recMessage.equals("/error")) { chessclient.chatpad.chatLineArea.append("传输错误:请退出程序,重新加入 \n"); } else { chessclient.chatpad.chatLineArea.append(recMessage+"\n"); chessclient.chatpad.chatLineArea.setCaretPosition( chessclient.chatpad.chatLineArea.getText().length()); } } public void run() { String message=""; try { while(true) { message=chessclient.in.readUTF(); acceptMessage(message); } } catch(IOException es) { } } } public class chessClient extends Frame implements ActionListener,KeyListener { userPad userpad=new userPad(); chatPad chatpad=new chatPad(); controlPad controlpad=new controlPad(); chessPad chesspad=new chessPad(); inputPad inputpad=new inputPad(); Socket chatSocket; DataInputStream in; DataOutputStream out; String chessClientName=null; String host=null; int port=4331; boolean isOnChat=false; //在聊天? boolean isOnChess=false; //在下棋? boolean isGameConnected=false; //下棋的客户端连接? boolean isServer=false; //如果是下棋的主机 boolean isClient=false; //如果是下棋的客户端 Panel southPanel=new Panel(); Panel northPanel=new Panel(); Panel centerPanel=new Panel(); Panel westPanel=new Panel(); Panel eastPanel=new Panel(); chessClient() { super("Java五子棋客户端"); setLayout(new BorderLayout()); host=controlpad.inputIP.getText(); westPanel.setLayout(new BorderLayout()); westPanel.add(userpad,BorderLayout.NORTH); westPanel.add(chatpad,BorderLayout.CENTER); westPanel.setBackground(Color.pink); inputpad.inputWords.addKeyListener(this); chesspad.host=controlpad.inputIP.getText(); centerPanel.add(chesspad,BorderLayout.CENTER); centerPanel.add(inputpad,BorderLayout.SOUTH); centerPanel.setBackground(Color.pink); controlpad.connectButton.addActionListener(this); controlpad.creatGameButton.addActionListener(this); controlpad.joinGameButton.addActionListener(this); controlpad.cancelGameButton.addActionListener(this); controlpad.exitGameButton.addActionListener(this); controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(false); southPanel.add(controlpad,BorderLayout.CENTER); southPanel.setBackground(Color.pink); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { if(isOnChat) { try { chatSocket.close(); } catch(Exception ed) { } } if(isOnChess || isGameConnected) { try { chesspad.chessSocket.close(); } catch(Exception ee) { } } System.exit(0); } public void windowActivated(WindowEvent ea) { } }); add(westPanel,BorderLayout.WEST); add(centerPanel,BorderLayout.CENTER); add(southPanel,BorderLayout.SOUTH); pack(); setSize(670,548); setVisible(true); setResizable(false); validate(); } public boolean connectServer(String serverIP,int serverPort) throws Exception { try { chatSocket=new Socket(serverIP,serverPort); in=new DataInputStream(chatSocket.getInputStream()); out=new DataOutputStream(chatSocket.getOutputStream()); clientThread clientthread=new clientThread(this); clientthread.start(); isOnChat=true; return true; } catch(IOException ex) { chatpad.chatLineArea.setText("chessClient:connectServer:无法连接,建议重新启动程序 \n"); } return false; } public void actionPerformed(ActionEvent e) { if(e.getSource()==controlpad.connectButton) { host=chesspad.host=controlpad.inputIP.getText(); try { if(connectServer(host,port)) { chatpad.chatLineArea.setText(""); controlpad.connectButton.setEnabled(false); controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); chesspad.statusText.setText("连接成功,请创建游戏或加入游戏"); } } catch(Exception ei) { chatpad.chatLineArea.setText("controlpad.connectButton:无法连接,建议重新启动程序 \n"); } } if(e.getSource()==controlpad.exitGameButton) { if(isOnChat) { try { chatSocket.close(); } catch(Exception ed) { } } if(isOnChess || isGameConnected) { try { chesspad.chessSocket.close(); } catch(Exception ee) { } } System.exit(0); } if(e.getSource()==controlpad.joinGameButton) { String selectedUser=userpad.userList.getSelectedItem(); if(selectedUser==null || selectedUser.startsWith("[inchess]") || selectedUser.equals(chessClientName)) { chesspad.statusText.setText("必须先选定一个有效用户"); } else { try { if(!isGameConnected) { if(chesspad.connectServer(chesspad.host,chesspad.port)) { isGameConnected=true; isOnChess=true; isClient=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName); } } else { isOnChess=true; isClient=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName); } } catch(Exception ee) { isGameConnected=false; isOnChess=false; isClient=false; controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); controlpad.cancelGameButton.setEnabled(false); chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"+ee); } } } if(e.getSource()==controlpad.creatGameButton) { try { if(!isGameConnected) { if(chesspad.connectServer(chesspad.host,chesspad.port)) { isGameConnected=true; isOnChess=true; isServer=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName); } } else { isOnChess=true; isServer=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName); } } catch(Exception ec) { isGameConnected=false; isOnChess=false; isServer=false; controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); controlpad.cancelGameButton.setEnabled(false); ec.printStackTrace(); chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"+ec); } } if(e.getSource()==controlpad.cancelGameButton) { if(isOnChess) { chesspad.chessthread.sendMessage("/giveup "+chessClientName); chesspad.chessVictory(-1*chesspad.chessColor); controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); controlpad.cancelGameButton.setEnabled(false); chesspad.statusText.setText("请建立游戏或者加入游戏"); } if(!isOnChess) { controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); controlpad.cancelGameButton.setEnabled(false); chesspad.statusText.setText("请建立游戏或者加入游戏"); } isClient=isServer=false; } } public void keyPressed(KeyEvent e) { TextField inputWords=(TextField)e.getSource(); if(e.getKeyCode()==KeyEvent.VK_ENTER) { if(inputpad.userChoice.getSelectedItem().equals("所有人")) { try { out.writeUTF(inputWords.getText()); inputWords.setText(""); } catch(Exception ea) { chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n"); userpad.userList.removeAll(); inputpad.userChoice.removeAll(); inputWords.setText(""); controlpad.connectButton.setEnabled(true); } } else { try { out.writeUTF("/"+inputpad.userChoice.getSelectedItem()+" "+inputWords.getText()); inputWords.setText(""); } catch(Exception ea) { chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n"); userpad.userList.removeAll(); inputpad.userChoice.removeAll(); inputWords.setText(""); controlpad.connectButton.setEnabled(true); } } } } public void keyTyped(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public static void main(String args[]) { chessClient chessClient=new chessClient(); } } /****************************************************************************************** 下面是:chessInteface.java ******************************************************************************************/ import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; class userPad extends Panel { List userList=new List(10); userPad() { setLayout(new BorderLayout()); for(int i=0;i<50;i++) { userList.add(i+"."+"没有用户"); } add(userList,BorderLayout.CENTER); } } class chatPad extends Panel { TextArea chatLineArea=new TextArea("",18,30,TextArea.SCROLLBARS_VERTICAL_ONLY); chatPad() { setLayout(new BorderLayout()); add(chatLineArea,BorderLayout.CENTER); } } class controlPad extends Panel { Label IPlabel=new Label("IP",Label.LEFT); TextField inputIP=new TextField("localhost",10); Button connectButton=new Button("连接主机"); Button creatGameButton=new Button("建立游戏"); Button joinGameButton=new Button("加入游戏"); Button cancelGameButton=new Button("放弃游戏"); Button exitGameButton=new Button("关闭程序"); controlPad() { setLayout(new FlowLayout(FlowLayout.LEFT)); setBackground(Color.pink); add(IPlabel); add(inputIP); add(connectButton); add(creatGameButton); add(joinGameButton); add(cancelGameButton); add(exitGameButton); } } class inputPad extends Panel { TextField inputWords=new TextField("",40); Choice userChoice=new Choice(); inputPad() { setLayout(new FlowLayout(FlowLayout.LEFT)); for(int i=0;i<50;i++) { userChoice.addItem(i+"."+"没有用户"); } userChoice.setSize(60,24); add(userChoice); add(inputWords); } } /********************************************************************************************** 下面是:chessPad.java **********************************************************************************************/ import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.*; class chessThread extends Thread { chessPad chesspad; chessThread(chessPad chesspad) { this.chesspad=chesspad; } public void sendMessage(String sndMessage) { try { chesspad.outData.writeUTF(sndMessage); } catch(Exception ea) { System.out.println("chessThread.sendMessage:"+ea); } } public void acceptMessage(String recMessage) { if(recMessage.startsWith("/chess ")) { StringTokenizer userToken=new StringTokenizer(recMessage," "); String chessToken; String[] chessOpt={"-1","-1","0"}; int chessOptNum=0; while(userToken.hasMoreTokens()) { chessToken=(String)userToken.nextToken(" "); if(chessOptNum>=1 && chessOptNum<=3) { chessOpt[chessOptNum-1]=chessToken; } chessOptNum++; } chesspad.netChessPaint(Integer.parseInt(chessOpt[0]),Integer.parseInt(chessOpt[1]),Integer.parseInt(chessOpt[2])); } else if(recMessage.startsWith("/yourname ")) { chesspad.chessSelfName=recMessage.substring(10); } else if(recMessage.equals("/error")) { chesspad.statusText.setText("错误:没有这个用户,请退出程序,重新加入"); } else { //System.out.println(recMessage); } } public void run() { String message=""; try { while(true) { message=chesspad.inData.readUTF(); acceptMessage(message); } } catch(IOException es) { } } } class chessPad extends Panel implements MouseListener,ActionListener { int chessPoint_x=-1,chessPoint_y=-1,chessColor=1; int chessBlack_x[]=new int[200]; int chessBlack_y[]=new int[200]; int chessWhite_x[]=new int[200]; int chessWhite_y[]=new int[200]; int chessBlackCount=0,chessWhiteCount=0; int chessBlackWin=0,chessWhiteWin=0; boolean isMouseEnabled=false,isWin=false,isInGame=false; TextField statusText=new TextField("请先连接服务器"); Socket chessSocket; DataInputStream inData; DataOutputStream outData; String chessSelfName=null; String chessPeerName=null; String host=null; int port=4331; chessThread chessthread=new chessThread(this); chessPad() { setSize(440,440); setLayout(null); setBackground(Color.pink); addMouseListener(this); add(statusText); statusText.setBounds(40,5,360,24); statusText.setEditable(false); } public boolean connectServer(String ServerIP,int ServerPort) throws Exception { try { chessSocket=new Socket(ServerIP,ServerPort); inData=new DataInputStream(chessSocket.getInputStream()); outData=new DataOutputStream(chessSocket.getOutputStream()); chessthread.start(); return true; } catch(IOException ex) { statusText.setText("chessPad:connectServer:无法连接 \n"); } return false; } public void chessVictory(int chessColorWin) { this.removeAll(); for(int i=0;i<=chessBlackCount;i++) { chessBlack_x[i]=0; chessBlack_y[i]=0; } for(int i=0;i<=chessWhiteCount;i++) { chessWhite_x[i]=0; chessWhite_y[i]=0; } chessBlackCount=0; chessWhiteCount=0; add(statusText); statusText.setBounds(40,5,360,24); if(chessColorWin==1) { chessBlackWin++; statusText.setText("黑棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待白棋下子..."); } else if(chessColorWin==-1) { chessWhiteWin++; statusText.setText("白棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待黑棋下子..."); } } public void getLocation(int a,int b,int color) { if(color==1) { chessBlack_x[chessBlackCount]=a*20; chessBlack_y[chessBlackCount]=b*20; chessBlackCount++; } else if(color==-1) { chessWhite_x[chessWhiteCount]=a*20; chessWhite_y[chessWhiteCount]=b*20; chessWhiteCount++; } } public boolean checkWin(int a,int b,int checkColor) { int step=1,chessLink=1,chessLinkTest=1,chessCompare=0; if(checkColor==1) { chessLink=1; for(step=1;step<=4;step++) { for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++) { if(((a+step)*20==chessBlack_x[chessCompare]) && ((b*20)==chessBlack_y[chessCompare])) { chessLink=chessLink+1; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } for(step=1;step<=4;step++) { for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++) { if(((a-step)*20==chessBlack_x[chessCompare]) && (b*20==chessBlack_y[chessCompare])) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } chessLink=1; chessLinkTest=1; for(step=1;step<=4;step++) { for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++) { if((a*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare])) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break;

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值