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

📄 clientplayer.java

📁 connectN 网络游戏。内含server and client端源程序
💻 JAVA
字号:
package client;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import javax.swing.*;
import javax.swing.border.LineBorder;
import model.ClientModel;
import utility.ClockThread;
import utility.ConnectNConstants;

public class ClientPlayer extends JFrame implements Runnable, ActionListener,
		ConnectNConstants {
	private static final long serialVersionUID = 1L;
	private int player;
	private Color myColor, otherColor;
	private String host;
	private int port;
	private ClientModel model = new ClientModel();
	private Board board;
	private InfoPanel info;
	private JLabel statusLabel = new JLabel();
	private JLabel titleLabel = new JLabel();
	private RoundButton[][] discs;
	private ClockThread time;
	private Socket socket;
	private DataInputStream fromServer;
	private DataOutputStream toServer;
	private int rowSelected;
	private int columnSelected;
	private boolean myTurn = false;
	private boolean continueToPlay = true;
	private boolean waiting = true;

	public ClientPlayer() {
		this.host = "localhost";
		this.port = 8000;
	}

	public ClientPlayer(String host, String port) {
		this.host = host;
		this.port = Integer.parseInt(port);
	}

	public void init() {
		this.setTitle("Connect N Client");
		titleLabel.setHorizontalAlignment(JLabel.CENTER);
		titleLabel.setFont(new Font("SansSerif", Font.BOLD, 16));
		titleLabel.setBorder(new LineBorder(Color.black, 1));
		statusLabel.setBorder(new LineBorder(Color.black, 1));

		// Place the panel and the labels to the applet
		this.getContentPane().add(titleLabel, BorderLayout.NORTH);
		this.getContentPane().add(statusLabel, BorderLayout.SOUTH);
		// Connect to the server
		connectToServer();
	}

	private void connectToServer() {
		try {
			// Create a socket to connect to the server
			this.socket = new Socket(host, port);
			// Create an input stream to receive data from the server
			fromServer = new DataInputStream(socket.getInputStream());
			// Create an output stream to send data to the server
			toServer = new DataOutputStream(socket.getOutputStream());
		} catch (Exception ex) {
			System.err.println("Cannot connect to server");
			System.exit(0);
		}
		// Control the game on a separate thread
		Thread thread = new Thread(this);
		thread.start();
	}

	public void run() {
		try {
			// Get notification from the server
			player = fromServer.readInt();
			// Am I player 1 or 2?
			if (player == PLAYER1) {
				this.setVisible(false);
				SetupGameDialog setupGame = new SetupGameDialog(this,
						this.model);
				setupGame.show();

				titleLabel.setText("Player 1");
				statusLabel.setText("Waiting for player 2 to join");
				this.myColor = PLAYER1COLOR;
				this.otherColor = PLAYER2COLOR;
				// Receive startup notification from the server
				fromServer.readInt(); // Whatever read is ignored
				board = new Board(model.getRowNum(), model.getColNum());
				this.getContentPane().add(this.board, BorderLayout.CENTER);
				info = new InfoPanel(model);
				this.getContentPane().add(info, BorderLayout.EAST);
				this.placeDiscs();
				this.validate();
				// The other player has joined
				statusLabel.setText("Player 2 has joined. I start first");
				// It is my turn
				myTurn = true;
			} else if (player == PLAYER2) {
				model.setRowNum(fromServer.readInt());
				model.setColNum(fromServer.readInt());
				model.setConnectN(fromServer.readInt());
				model.setDropNum(fromServer.readInt());
				myColor = PLAYER2COLOR;
				otherColor = PLAYER1COLOR;
				board = new Board(model.getRowNum(), model.getColNum());
				this.getContentPane().add(this.board, BorderLayout.CENTER);
				info = new InfoPanel(model);
				this.getContentPane().add(info, BorderLayout.EAST);
				this.placeDiscs();
				this.validate();
				titleLabel.setText("Player 2");
				statusLabel.setText("Waiting for player 1 to move");
			}			
			time = new ClockThread(TIMEOUT, TIMEUNIT, info, this);
			time.start();

			// Continue to play
			while (continueToPlay) {
				if (player == PLAYER1) {
					if (myTurn) {
						waitForPlayerAction(); // Wait for player 1 to move
						sendMove(); // Send the move to the server
						}
					receiveInfoFromServer(); // Receive info from the server
				} else if (player == PLAYER2) {
					receiveInfoFromServer();// Receive info from the server
					if (myTurn) {
						waitForPlayerAction(); // Wait for player 2 to move
						sendMove(); // Send player 2's move to the server
					}
				}
			}			
		} catch (Exception ex) {
		}
		finally
		{
			time.stopTimer();
			this.finish();
		}
	}

	public void sendSetting() {
		try {
			toServer.writeInt(model.getRowNum());
			toServer.writeInt(model.getColNum());
			toServer.writeInt(model.getConnectN());
			toServer.writeInt(model.getDropNum());
		} catch (IOException e) {
			this.finish();
		}
	}

	public void placeDiscs() {
		this.discs = new RoundButton[model.getRowNum()][model.getColNum()];
		for (int i = 0; i < model.getRowNum(); i++) {
			for (int j = 0; j < model.getColNum(); j++) {
				discs[i][j] = new RoundButton();
				discs[i][j].addActionListener(this);
				discs[i][j].setEnabled(true);
				board.add(discs[i][j]);
			}
		}
		model.initMap();
	}

	private void waitForPlayerAction() throws InterruptedException {
		while (waiting) {
			Thread.sleep(100);
		}
		waiting = true;
	}

	/** Send this player's move to the server */
	private void sendMove() throws IOException {
		toServer.writeInt(rowSelected); // send the selected row
		toServer.writeInt(columnSelected); // Send the selected column
	}

	/** Receive info from the server */
	private void receiveInfoFromServer() throws IOException {
		// Receive game status
		int sta = fromServer.readInt();
		if (sta == PLAYER1_WON) {
			// Player 1 won, stop playing
			continueToPlay = false;
			if (player == PLAYER1) {
				statusLabel.setText("  I won! ");
			} else if (player == PLAYER2) {
				statusLabel.setText("Player 1 has won!");
				receiveMove();
			}
		} else if (sta == PLAYER2_WON) {
			// Player 2 won, stop playing
			continueToPlay = false;
			if (player == PLAYER2) {
				statusLabel.setText("  I won! ");
			} else if (player == PLAYER1) {
				statusLabel.setText("Player 2 has won!");
				receiveMove();
			}
		} else if (sta == DRAW) {
			// No winner, game is over
			continueToPlay = false;
			statusLabel.setText("Game is over, no winner!");
			receiveMove();
		} else if (sta == SECONDTIME) {
			time.setCurrentTime(TIMEOUT);
			time.wakeup();
			statusLabel.setText("My turn");
			myTurn = true;
		} else if (sta == WAITFORSECONDMOVE) {
			time.setCurrentTime(TIMEOUT);
			time.wakeup();
			receiveMove();
		} else if (sta == CONTINUE) {
			time.setCurrentTime(TIMEOUT);
			time.wakeup();
			receiveMove();
			statusLabel.setText("My turn");
			myTurn = true; // It is my turn
		}
	}

	private void receiveMove() throws IOException {
		// Get the other player's move
		int row = fromServer.readInt();
		int column = fromServer.readInt();
		model.placeDisc(column);
		discs[row][column].setBackground(otherColor);
	}

	public void actionPerformed(ActionEvent e) {
		if (myTurn) {
			for (int i = 0; i < model.getRowNum(); i++)
				for (int j = 0; j < model.getColNum(); j++) {
					if (e.getSource() == discs[i][j]) {
						int t = model.placeDisc(j);
						if (t != -1) {
							discs[t][j].setBackground(myColor);
							time.setCurrentTime(TIMEOUT);
							this.rowSelected = t;
							this.columnSelected = j;
							myTurn = false;
							statusLabel.setText("Waiting for the other player to move");
							waiting = false;
						}
					}
				}
		}

	}
	
	public boolean isMyTurn() {
		return this.myTurn;
	}

	public void timeOut() {
		int row = 0, col = 0;
		boolean exit = false;
		while (!exit) {
			col = model.computerPlace();
			row = model.placeDisc(col);
			if (row != -1) {
				exit = true;
			}
		}
		rowSelected = row;
		columnSelected = col;
		if (player == PLAYER1)
			discs[rowSelected][columnSelected].setBackground(PLAYER1COLOR);
		else
			discs[rowSelected][columnSelected].setBackground(PLAYER2COLOR);
		time.setCurrentTime(TIMEOUT);
		time.wakeup();
		myTurn = false;
		statusLabel.setText("Waiting for the other player to move");
		waiting = false;
	}
	
	
	
	private void finish()
	{
		try {
			this.fromServer.close();
			this.toServer.close();
			this.socket.close();
		} catch (IOException e) {
			System.exit(1);
		}
		
	}

	public static void main(String[] args) {
		// Get host
		ClientPlayer client;
		if (args.length == 2)
			client = new ClientPlayer(args[0], args[1]);
		else
			client = new ClientPlayer();
		client.setSize(600, 480);
		client.init();

		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = client.getSize();
		if (frameSize.height > screenSize.height) {
			frameSize.height = screenSize.height;
		}
		if (frameSize.width > screenSize.width) {
			frameSize.width = screenSize.width;
		}
		client.setLocation((screenSize.width - frameSize.width) / 2,
				(screenSize.height - frameSize.height) / 2);
		client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		client.setVisible(true);
	}	

}

⌨️ 快捷键说明

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