📄 chessmain.java
字号:
package five;
/**
* @author 张聪
*
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.net.*;
public class ChessMain extends JFrame{
// 声明各组件
private JButton connButton = new JButton("连接服务器");
private JButton serverButton = new JButton("建立服务器");
private JButton breakButton = new JButton("终止游戏");
private JButton exitButton = new JButton("退出游戏");
private JButton copyrightButton = new JButton("关于作者");
private JTextField statusBar = new JTextField();
private ServerSocket ss;
private Socket socket;
private ChessBoard board;
Panel mainPanel = new Panel();
private int currentStatus = GameStatus.UN_START;
private boolean ready;
private boolean server;
ObjectInputStream ois;
ObjectOutputStream oos;
InetAddress myIPaddress=null;
public InetAddress getMyIP() {
try { myIPaddress=InetAddress.getLocalHost();}
catch (UnknownHostException e) {}
return (myIPaddress);
}
public boolean isReady() {
return ready;
}
public void setReady(boolean ready) {
this.ready = ready;
}
public void setServer(boolean server) {
this.server = server;
}
public ChessMain() {
// 设置窗口标题
super("五子棋");
// 新建Container
Container c = getContentPane();
// 设置toobar为FlowLayout
JPanel toolbar = new JPanel(new FlowLayout(FlowLayout.CENTER));
// 给toolbar添加按钮
toolbar.add(serverButton);
toolbar.add(connButton);
toolbar.add(breakButton);
toolbar.add(exitButton);
toolbar.add(copyrightButton);
// 添加按钮提示信息
serverButton.setToolTipText("将本机建立为服务器,等待对方机器连接, 端口号为12345");
connButton.setToolTipText("连接到服务器");
exitButton.setToolTipText("退出游戏");
copyrightButton.setToolTipText("作者信息");
// 添加Listener
ButtonActionListener l = new ButtonActionListener();
serverButton.addActionListener(l);
connButton.addActionListener(l);
breakButton.addActionListener(l);
exitButton.addActionListener(l);
copyrightButton.addActionListener(l);
// 建立棋盘
board = new ChessBoard(this);
statusBar.setEditable(false);
// 将棋盘添加至一个panel中
mainPanel.add(board);
//设置主布局为BorderLayout
c.add(toolbar, BorderLayout.NORTH);
c.add(mainPanel,BorderLayout.CENTER);
c.add(statusBar, BorderLayout.SOUTH);
// 设置退出按键
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
closeWindow();
}
});
pack();
refreshByStatus();
}
public boolean isConnected() {
return currentStatus == GameStatus.CONNECTED;
}
/**
* @param args
*/
public static void main(String[] args) {
ChessMain frame = new ChessMain();
frame.setVisible(true);
}
public boolean isServer() {
// TODO Auto-generated method stub
return server;
}
public void closeWindow() {
int iClick = JOptionPane.showConfirmDialog(ChessMain.this, "您确定要退出吗?",
"退出", JOptionPane.YES_NO_OPTION);
if (iClick == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
private void getStream() throws IOException{
if(socket != null) {
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
}
}
public void processConnection() {
try {
Object o;
while ((o = ois.readObject()) != null) {
Chess c = (Chess) o;
recieveData(c);
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException cnf) {
cnf.printStackTrace();
} catch(Exception ex) {
ex.printStackTrace();
}
finally {
stopGame();
}
}
// 声明recieveData函数
public void recieveData(Chess ch) {
boolean isWin = board.addChess(ch);
setStatusBar("该您下棋了……");
setReady(true);
repaint();
if(isWin) {
processIsWin(false);
}
}
// 声明sendData函数
public void sendData(Chess ch) throws IOException{
oos.writeObject(ch);
oos.flush();
setStatusBar("请等待对方下棋……");
setReady(false);
boolean isWin = board.addChess(ch);
if(isWin) {
processIsWin(true);
}
}
// 声明胜负判定结果函数
private void processIsWin(boolean win) {
if (win)
JOptionPane.showMessageDialog(this, "恭喜,您赢了!");
else
JOptionPane.showMessageDialog(this, "Sorry,您输了!");
stopGame();
}
private void closeConnection() {
try {
ois.close();
ois = null;
} catch (Exception ex) {
}
try {
oos.close();
oos = null;
} catch (Exception ex) {
}
try {
socket.close();
socket = null;
} catch (Exception ex) {
}
try {
if (ss != null)
ss.close();
ss = null;
} catch (Exception ex) {
}
}
public void setCurrentStatus(int newStatus) {
currentStatus = newStatus;
refreshByStatus();
}
public void setStatusBar(final String str) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
statusBar.setText(str);
}
});
}
private void refreshByStatus() {
switch (currentStatus) {
case GameStatus.UN_START:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
serverButton.setEnabled(true);
connButton.setEnabled(true);
breakButton.setEnabled(false);
statusBar.setText("游戏未开始,请启动服务或连接到对方机器.");
}
});
break;
case GameStatus.WAITING:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
serverButton.setEnabled(false);
connButton.setEnabled(false);
if(isServer())
{
statusBar.setText("服务器已启动,正在等待其它机器连接……");
JOptionPane.showMessageDialog(null, "服务器成功启动!" + "\n"
+ "本服务器地址为:"+"\n"+getMyIP()+":12345", "服务器信息",
JOptionPane.INFORMATION_MESSAGE);
}
else
statusBar.setText("正在连接服务器, 请稍候…….");
}
});
break;
case GameStatus.CONNECTED:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setTitle("五子棋 - 您正在跟来自"
+ socket.getRemoteSocketAddress().toString()
+ "的玩家下棋!");
breakButton.setEnabled(true);
if(isServer()) {
statusBar.setText("连接成功,您是黑棋,先下!");
JOptionPane.showMessageDialog(null, "游戏开始!" + "\n"
+ "您是黑棋,先下!", "游戏",
JOptionPane.INFORMATION_MESSAGE);
}else{
statusBar.setText("连接成功,您是白棋,请等待对方下棋!");
JOptionPane.showMessageDialog(null, "游戏开始!" + "\n"
+ "您是白棋,请等待对方下棋!", "游戏",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
break;
}
}
public Color getUserColor() {
if(isServer()) {
return Color.black;
}else
return Color.white;
}
class ButtonActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == serverButton) {
Thread t = new Thread(new Runnable() {
private void runAsServer() throws IOException {
ss = new ServerSocket(12345);
setServer(true);
setCurrentStatus(GameStatus.WAITING);
socket = ss.accept();
getStream();
setTitle("五子棋 - 您正在跟来自"
+ socket.getRemoteSocketAddress().toString()
+ "的玩家下棋!");
setCurrentStatus(GameStatus.CONNECTED);
setReady(true);// server 先下
processConnection();
}
public void run() {
try {
runAsServer();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(ChessMain.this,
"服务器无法启动!");
setCurrentStatus(GameStatus.UN_START);
}
}
});
t.start();
} else if (src == connButton) {
Thread t = new Thread(new Runnable() {
private void runAsClient() throws IOException {
String str = JOptionPane.showInputDialog(
ChessMain.this, "请输入服务器IP, 端口号,以空格分隔!",
"192.168.1.101 12345");
while (!str
.matches("\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}\\s+\\d{1,6}")) {
str = JOptionPane
.showInputDialog("格式错误,请重新输入(ddd.ddd.ddd.ddd dddd)");
}
String[] list = str.split(" ");
setServer(false);
setCurrentStatus(GameStatus.WAITING);
socket = new Socket(list[0], Integer.parseInt(list[1]));
getStream();
setCurrentStatus(GameStatus.CONNECTED);
setReady(false);
processConnection();
}
public void run() {
try {
runAsClient();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(ChessMain.this,
"无法连接到服务器!");
setCurrentStatus(GameStatus.UN_START);
}
}
});
t.start();
} else if (src == exitButton) {
closeWindow();
} else if (src == breakButton) {
stopGame();
} else if (src == copyrightButton){
JOptionPane.showMessageDialog(null, " 作者:" + "\n"
+ " 05990163 张聪" + "\n" + " 05990164 张昊"
+ "\n" + " 05990162 张博", " 关于作者 ",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
public void stopGame() {
board.clearBoard();
closeConnection();
setCurrentStatus(GameStatus.UN_START);
setStatusBar("游戏已结束,请重新连接!");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -