您现在的位置:首页 >> 基础 >> Java编程 >> 内容

java实现联机五子棋--Java学习网

时间:2016-12-7 7:59:22

  核心提示:a.jpgConfig.xml ~ 122B ?xml version='1.0' encoding='UTF-8'?CONFIGSIZE50/SIZEROW8/ROWCLOUNM8/CLOUNM/C...
a.jpg 

 Config.xml ~ 122B
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <CONFIG>
  3. <SIZE>50</SIZE>
  4. <ROW>8</ROW>
  5. <CLOUNM>8</CLOUNM>
  6. </CONFIG>
复制代码
Main.java ~ 112B
  1. import panel.MainUI;
  2. public class Main {
  3. public static void main(String[] args) {
  4. new MainUI();
  5. }
  6. }
复制代码
[文件] Config.java ~ 5KB
  1. package panel;
  2. import java.awt.Color;
  3. import java.io.File;
  4. import javax.xml.parsers.DocumentBuilder;
  5. import javax.xml.parsers.DocumentBuilderFactory;
  6. import org.w3c.dom.Document;
  7. import org.w3c.dom.NodeList;
  8. public class Config {
  9. private static int port;
  10. /**
  11. * ?à×ó±??ò?àà?
  12. */
  13. public static final int STARTX = 50;
  14. /**
  15. * ?Yé?±??ò?àà?
  16. */
  17. public static final int STARTY = 90;
  18. /**
  19. * ????
  20. */
  21. public static int SIZE = 50;
  22. /**
  23. * DDêy
  24. */
  25. public static int ROW = 10;
  26. /**
  27. * áDêy
  28. */
  29. public static int CLOUNM = 10;
  30. private static Color color = Color.BLACK;
  31. private static byte[][] chess ;
  32. private static int[] notify = { -1, -1 };
  33. static {
  34. try {
  35. File f = new File("Config.xml");
  36. DocumentBuilderFactory factory = DocumentBuilderFactory
  37. .newInstance();
  38. DocumentBuilder builder = factory.newDocumentBuilder();
  39. Document doc = builder.parse(f);
  40. NodeList nl = doc.getElementsByTagName("CONFIG");
  41. // SIZE=Integer.parseInt(doc.getElementsByTagName("SIZE").item(0).getFirstChild().getNodeValue()));
  42. for (int i = 0; i < nl.getLength(); i++) {
  43. SIZE = Integer.parseInt(doc.getElementsByTagName("SIZE")
  44. .item(i).getFirstChild().getNodeValue());
  45. ROW = Integer.parseInt(doc.getElementsByTagName("ROW").item(i)
  46. .getFirstChild().getNodeValue());
  47. CLOUNM = Integer.parseInt(doc.getElementsByTagName("CLOUNM")
  48. .item(i).getFirstChild().getNodeValue());
  49. // System.out.println(SIZE+" "+ROW+ " "+CLOUNM);
  50. }
  51. chess = new byte[ROW + 1][CLOUNM + 1];
  52. } catch (Exception e) {
  53. // TODO Auto-generated catch block
  54. e.printStackTrace();
  55. }
  56. }
  57. public static void setX(int x) {
  58. notify[0] = x;
  59. }
  60. public static int getX() {
  61. return notify[0];
  62. }
  63. public static void setY(int y) {
  64. notify[1] = y;
  65. }
  66. public static int getY() {
  67. return notify[1];
  68. }
  69. public static void clearNotify() {
  70. notify[0] = notify[1] = -1;
  71. }
  72. /**
  73. * éè????×ó??é?
  74. */
  75. public static void setColor(Color cr) {
  76. color = cr;
  77. }
  78. public static void exchangeColor(){
  79. color=(color==Color.BLACK)?Color.WHITE:Color.BLACK;
  80. }
  81. /**
  82. * ??μ???×ó??é?
  83. */
  84. public static Color getColor() {
  85. return color;
  86. }
  87. /**
  88. * ?D??êó±ê?ùμ??÷????ê?·??é????×ó
  89. */
  90. public static boolean isChessMan(int x, int y, Color color) {
  91. int j = (x - STARTX) / SIZE;
  92. int i = (y - STARTY) / SIZE;
  93. if (chess[i][j] != 0)
  94. return false;
  95. else {
  96. chess[i][j] = (color == Color.BLACK) ? (byte) 1 : -1;
  97. return true;
  98. }
  99. }
  100. /**
  101. * ?D??êó±ê?ùμ??÷×?±êê?·??é????×ó
  102. */
  103. public static boolean isChessMan(byte j, byte i, Color color) {
  104. if (chess[i][j] != 0)
  105. return false;
  106. else {
  107. chess[i][j] = (color == Color.BLACK) ? (byte) 1 : -1;
  108. return true;
  109. }
  110. }
  111. /**
  112. * ???????ì
  113. */
  114. public static void resetChess(byte[][] buf) {
  115. chess = buf;
  116. }
  117. /**
  118. * ?D??ê?·?ê¤à?
  119. */
  120. public static boolean isWin(Color color) {
  121. boolean flag = false;
  122. int n = 0;
  123. int c = (color == Color.BLACK) ? 1 : -1;
  124. // ?D??áD
  125. for (int i = 0; i <= ROW; i++) {
  126. for (int j = 0; j <= CLOUNM; j++) {
  127. if (chess[i][j] == c && flag == false) {
  128. n = 1;
  129. flag = true;
  130. } else if (chess[i][j] == c && flag == true) {
  131. n++;
  132. } else if (chess[i][j] != c) {
  133. n = 0;
  134. flag = false;
  135. }
  136. if (5 == n) {
  137. n = 0;
  138. flag = false;
  139. return true;
  140. }
  141. }
  142. }
  143. n = 0;
  144. flag = false;
  145. // ?D??DD
  146. for (int j = 0; j <= CLOUNM; j++) {
  147. for (int i = 0; i <= ROW; i++) {
  148. if (chess[i][j] == c && flag == false) {
  149. n = 1;
  150. flag = true;
  151. } else if (chess[i][j] == c && flag == true) {
  152. n++;
  153. } else if (chess[i][j] != c) {
  154. n = 0;
  155. flag = false;
  156. }
  157. if (5 == n) {
  158. n = 0;
  159. flag = false;
  160. return true;
  161. }
  162. }
  163. }
  164. n = 0;
  165. flag = false;
  166. // ?D??×óD±
  167. for (int i = 0; i <= ROW; i++) {
  168. for (int j = 0; j <= CLOUNM; j++) {
  169. for (int ii = i, jj = j; ii <= ROW && jj >= 0; ii++, jj--) {
  170. if (chess[ii][jj] == c && flag == false) {
  171. n = 1;
  172. flag = true;
  173. } else if (chess[ii][jj] == c && flag == true) {
  174. n++;
  175. } else if (chess[ii][jj] != c) {
  176. n = 0;
  177. flag = false;
  178. }
  179. if (5 == n) {
  180. n = 0;
  181. flag = false;
  182. return true;
  183. }
  184. }
  185. }
  186. }
  187. n = 0;
  188. flag = false;
  189. // ?D??óòD±
  190. for (int i = 0; i <= ROW; i++) {
  191. for (int j = 0; j <= CLOUNM; j++) {
  192. for (int ii = i, jj = j; jj <= CLOUNM && ii <= ROW; ii++, jj++) {
  193. if (chess[ii][jj] == c && flag == false) {
  194. n = 1;
  195. flag = true;
  196. } else if (chess[ii][jj] == c && flag == true) {
  197. n++;
  198. } else if (chess[ii][jj] != c) {
  199. n = 0;
  200. flag = false;
  201. }
  202. if (5 == n) {
  203. n = 0;
  204. flag = false;
  205. return true;
  206. }
  207. }
  208. }
  209. }
  210. return false;
  211. }
  212. /**
  213. * éè?????úo?
  214. */
  215. public static void setPort(int p) {
  216. port = p;
  217. // System.out.println(port);
  218. }
  219. /**
  220. * ??è????úo?
  221. */
  222. public static int getPort() {
  223. return port;
  224. }
  225. /**
  226. * ??????×ó
  227. */
  228. public static void clearChess() {
  229. chess = new byte[ROW + 1][CLOUNM + 1];
  230. }
  231. /**
  232. * ??μ???×ó
  233. */
  234. public static byte[][] getChess() {
  235. return chess;
  236. }
  237. }
复制代码
[文件] MainUI.java ~ 3KB
  1. package panel;
  2. import game.ChessUtils;
  3. import java.awt.BorderLayout;
  4. import java.awt.Color;
  5. import java.awt.Graphics;
  6. import javax.swing.ImageIcon;
  7. import javax.swing.JFrame;
  8. import javax.swing.JLabel;
  9. import javax.swing.JMenu;
  10. import javax.swing.JMenuBar;
  11. import javax.swing.JMenuItem;
  12. import javax.swing.JPanel;
  13. @SuppressWarnings("serial")
  14. public class MainUI extends JFrame {
  15. private MenuListener menupolice;
  16. private JMenuBar menubar;
  17. private JMenu menu;
  18. private JMenuItem itemStart;
  19. private JMenuItem itemjoin;
  20. private JMenuItem itemOver;
  21. public MainUI() {
  22. setSize(2 * Config.STARTX + Config.CLOUNM * Config.SIZE, Config.STARTY
  23. + Config.SIZE * (Config.ROW + 1));
  24. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  25. setLayout(new BorderLayout());
  26. itemStart = new JMenuItem("创建游戏");
  27. itemjoin = new JMenuItem("加入游戏");
  28. itemOver = new JMenuItem("结束游戏");
  29. menu = new JMenu("菜单");
  30. menubar = new JMenuBar();
  31. menu.add(itemStart);
  32. menu.add(itemjoin);
  33. menu.add(itemOver);
  34. menubar.add(menu);
  35. add(menubar, BorderLayout.NORTH);
  36. menupolice = new MenuListener(itemStart, itemjoin, itemOver, this);
  37. itemStart.addActionListener(menupolice);
  38. itemjoin.addActionListener(menupolice);
  39. itemOver.addActionListener(menupolice);
  40. // 添加窗体背景图片
  41. ImageIcon icon = new ImageIcon("1.jpg");
  42. JLabel label = new JLabel(icon);
  43. getLayeredPane().add(label, new Integer(Integer.MIN_VALUE));
  44. label.setBounds(0, 0, 1000,1000);
  45. ((JPanel) this.getContentPane()).setOpaque(false);
  46. ChessUtils.locateFrameCenter(this);
  47. setVisible(true);
  48. setTitle("五子棋");
  49. }
  50. /**
  51. * 重写父类重绘方法
  52. */
  53. public void paint(Graphics g) {
  54. // 调用父类重绘方法
  55. super.paint(g);
  56. drawLine(g);
  57. drawChessMan(g);
  58. }
  59. /**
  60. * 重绘棋盘
  61. */
  62. private void drawLine(Graphics g) {
  63. g.setColor(Color.BLACK);
  64. // 纵线
  65. for (int i = 0; i <= Config.CLOUNM; i++) {
  66. g.drawLine(Config.SIZE * i + Config.STARTX, Config.STARTY,
  67. Config.SIZE * i + Config.STARTX, (Config.ROW) * Config.SIZE
  68. + Config.STARTY);
  69. }
  70. // 横线
  71. for (int i = 0; i <= Config.ROW; i++) {
  72. g.drawLine(Config.STARTX, Config.STARTY + Config.SIZE * i,
  73. Config.SIZE * (Config.CLOUNM) + Config.STARTX,
  74. Config.STARTY + Config.SIZE * i);
  75. }
  76. }
  77. /**
  78. * 重绘棋子
  79. */
  80. private void drawChessMan(Graphics g) {
  81. g.setColor(Config.getColor());
  82. byte[][] chess = Config.getChess();
  83. // System.out.println(Config.ROW);
  84. for (int i = 0; i <= Config.ROW; i++) {
  85. for (int j = 0; j <= Config.CLOUNM; j++) {
  86. if (1 == chess[i][j]) {
  87. g.setColor(Color.BLACK);
  88. g.fillOval((j * Config.SIZE + Config.STARTX)
  89. - (Config.SIZE / 2),
  90. (i * Config.SIZE + Config.STARTY)
  91. - (Config.SIZE / 2), Config.SIZE - 5,
  92. Config.SIZE - 5);
  93. }
  94. if (-1 == chess[i][j]) {
  95. g.setColor(Color.WHITE);
  96. g.fillOval((j * Config.SIZE + Config.STARTX)
  97. - (Config.SIZE / 2),
  98. (i * Config.SIZE + Config.STARTY)
  99. - (Config.SIZE / 2), Config.SIZE - 5,
  100. Config.SIZE - 5);
  101. }
  102. }
  103. }
  104. // g.setColor(Color.BLACK);
  105. }
  106. }
复制代码
[文件] MyListener.java ~ 3KB
  1. package panel;
  2. import game.GameClient;
  3. import game.GameServer;
  4. import game.MyDialog;
  5. import java.awt.event.ActionEvent;
  6. import java.awt.event.ActionListener;
  7. import java.awt.event.MouseEvent;
  8. import java.awt.event.MouseListener;
  9. import javax.swing.JFrame;
  10. import javax.swing.JMenuItem;
  11. /**
  12. * 处理输赢判断以及坐标转换
  13. *
  14. * @author chenj_000
  15. *
  16. */
  17. public class MyListener implements MouseListener {
  18. /**
  19. * 鼠标点击触发
  20. */
  21. public void mousePressed(MouseEvent e) {
  22. // 1,获得焦点坐标
  23. int x = e.getX();
  24. int y = e.getY();
  25. x = ((x - Config.STARTX) + (Config.SIZE / 2)) / Config.SIZE
  26. * Config.SIZE + Config.STARTX;
  27. y = ((y - Config.STARTY) + (Config.SIZE / 2)) / Config.SIZE
  28. * Config.SIZE + Config.STARTY;
  29. // 2,判断坐标是否闲置
  30. if (!Config.isChessMan(x, y, Config.getColor()))
  31. return;
  32. // 3,若坐标可用,则向配置文件发送坐标信息
  33. Config.setX(x);
  34. Config.setY(y);
  35. }
  36. public void mouseClicked(MouseEvent e) {
  37. }
  38. public void mouseReleased(MouseEvent e) {
  39. }
  40. public void mouseEntered(MouseEvent e) {
  41. }
  42. public void mouseExited(MouseEvent e) {
  43. }
  44. }
  45. /**
  46. * 菜单项监视器
  47. *
  48. * @author chenj_000
  49. *
  50. */
  51. class MenuListener implements ActionListener {
  52. private JMenuItem itemStart;
  53. private JMenuItem itemjoin;
  54. private JMenuItem itemOver;
  55. private JFrame frame;
  56. private Thread start;
  57. private Thread join;
  58. private GameServer server;
  59. private GameClient client;
  60. public MenuListener(JMenuItem Start, JMenuItem join, JMenuItem Over,
  61. JFrame f) {
  62. itemStart = Start;
  63. itemjoin = join;
  64. itemOver = Over;
  65. frame = f;
  66. }
  67. @Override
  68. public void actionPerformed(ActionEvent e) {
  69. JMenuItem item = (JMenuItem) e.getSource();
  70. if (item.equals(itemStart)) {
  71. server=new GameServer(frame);
  72. start = new Thread(server);
  73. start.start();
  74. itemStart.setEnabled(false);
  75. itemjoin.setEnabled(false);
  76. } else if (item.equals(itemjoin)) {
  77. client=new GameClient(frame);
  78. join = new Thread(client);
  79. join.start();
  80. itemStart.setEnabled(false);
  81. itemjoin.setEnabled(false);
  82. } else if (item.equals(itemOver)) {
  83. if (null != start)
  84. try {
  85. server.threadDestory();
  86. } catch (Exception e1) {
  87. e1.printStackTrace();
  88. }
  89. if (null != join)
  90. try {
  91. client.threadDestory();
  92. } catch (Exception e1) {
  93. e1.printStackTrace();
  94. }
  95. itemStart.setEnabled(true);
  96. itemjoin.setEnabled(true);
  97. Config.clearChess();
  98. new MyDialog(frame, "棋局已经重置", false).setVisible(true);
  99. }
  100. }
  101. }
复制代码
[文件] ChessUtils.java ~ 1KB
  1. package game;
  2. import java.awt.*;
  3. import javax.swing.*;
  4. /**
  5. * 本类为其他类提供可静态引用的方法
  6. *
  7. * @author chenj_000
  8. *
  9. */
  10. public class ChessUtils {
  11. /**
  12. * 将一个容器的位置设置为居中
  13. */
  14. public static void locateFrameCenter(JFrame frame) {
  15. int frameWidth = frame.getWidth();
  16. int frameHeight = frame.getHeight();
  17. /* Toolkit是所有 Abstract Window Toolkit 实际实现的抽象超类。 getDefaultToolkit()获取默认工具包。*/
  18. Toolkit toolkit = Toolkit.getDefaultToolkit();
  19. /* Dimension 类封装单个对象中组件的宽度和高度(精确到整数)。 getScreenSize() 获取当前显示器尺寸 */
  20. Dimension screen = toolkit.getScreenSize();
  21. int screenWidth = screen.width;
  22. int screenHeight = screen.height;
  23. /* 调整当前容器位置居中 */
  24. frame.setLocation((screenWidth - frameWidth) / 2,
  25. (screenHeight - frameHeight) / 2);
  26. }
  27. /**
  28. * 设置对话框居中显示
  29. */
  30. public static void locateDialogCenter(JDialog dialog) {
  31. int frameWidth = dialog.getWidth();
  32. int frameHeight = dialog.getHeight();
  33. Toolkit toolkit = Toolkit.getDefaultToolkit();
  34. Dimension screen = toolkit.getScreenSize();
  35. int screenWidth = screen.width;
  36. int screenHeight = screen.height;
  37. dialog.setLocation((screenWidth - frameWidth) / 2,
  38. (screenHeight - frameHeight) / 2);
  39. }
  40. }
复制代码
[文件] GameClient.java ~ 5KB (13)
  1. package game;
  2. import java.awt.Color;
  3. import java.awt.Graphics;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.net.InetAddress;
  8. import java.net.Socket;
  9. import javax.swing.JFrame;
  10. import javax.swing.JOptionPane;
  11. import panel.Config;
  12. import panel.MyListener;
  13. public class GameClient implements Runnable {
  14. private Socket client;
  15. private int port;
  16. private String ip;
  17. private JFrame frame;
  18. private InputStream in;
  19. private OutputStream out;
  20. private String name;
  21. private boolean flag = false;
  22. public GameClient(JFrame frame) {
  23. this.frame = frame;
  24. init();
  25. }
  26. /**
  27. * 判断是否建立了连接
  28. */
  29. private boolean confirm() throws IOException {
  30. byte[] buf = new byte[64];
  31. int n = in.read(buf);
  32. name = new String(buf, 0, n);
  33. return (name.length() > 0) ? true : false;
  34. }
  35. /**
  36. * 接收初始化信息
  37. *
  38. * @throws IOException
  39. */
  40. private void resetUI() throws IOException {
  41. byte buf[] = new byte[64];
  42. int n = in.read(buf);
  43. // System.out.println(s);
  44. String[] numberStrs = new String(buf, 0, n).split("#");
  45. // System.out.println(numberStrs.toString());
  46. Config.SIZE = Integer.parseInt(numberStrs[0]);
  47. Config.ROW = Integer.parseInt(numberStrs[1]);
  48. Config.CLOUNM = Integer.parseInt(numberStrs[2]);
  49. frame.setSize(2 * Config.STARTX + Config.CLOUNM * Config.SIZE,
  50. Config.STARTY + Config.SIZE * (Config.ROW + 1));
  51. Config.resetChess(new byte[Config.ROW + 1][Config.CLOUNM + 1]);
  52. frame.paint(frame.getGraphics());
  53. }
  54. public void run() {
  55. try {
  56. InetAddress address = InetAddress.getByName(ip);
  57. client = new Socket(address, port);
  58. in = client.getInputStream();
  59. out = client.getOutputStream();
  60. if (!confirm()) {
  61. new MyDialog(frame, "连接服务器失败", true).setVisible(true);
  62. return;
  63. }
  64. resetUI();
  65. frame.setTitle("五子棋 " + "已连接:" + name + " 的游戏:本机端口号:"
  66. + client.getLocalPort());
  67. // 1,设置棋子颜色
  68. Config.setColor(Color.WHITE);
  69. // 2,交替下棋
  70. MyListener police = new MyListener();
  71. while (true) {
  72. if (flag) {
  73. frame.addMouseListener(police);
  74. while (Config.getX() == -1) {
  75. Thread.sleep(20);
  76. }
  77. int x = Config.getX();
  78. int y = Config.getY();
  79. Config.clearNotify();
  80. Graphics g = frame.getGraphics();
  81. g.setColor(Config.getColor());
  82. g.fillOval(x - (Config.SIZE / 2), y - (Config.SIZE / 2),
  83. Config.SIZE - 5, Config.SIZE - 5);
  84. // 将位置转换为坐标并发送给服务器端
  85. x = (x - Config.STARTX) / Config.SIZE;
  86. y = (y - Config.STARTY) / Config.SIZE;
  87. byte buf[] = new byte[2];
  88. buf[0] = (byte) x;
  89. buf[1] = (byte) y;
  90. out.write(buf);
  91. if (Config.isWin(Color.BLACK)) {
  92. new MyDialog(frame, Color.BLACK).setVisible(true);
  93. } else if (Config.isWin(Color.WHITE)) {
  94. new MyDialog(frame, Color.WHITE).setVisible(true);
  95. }
  96. flag = !flag;
  97. frame.removeMouseListener(police);
  98. } else {
  99. byte[][] buf = new byte[Config.ROW + 1][Config.CLOUNM + 1];
  100. for (int i = 0; i <= Config.ROW; i++) {
  101. in.read(buf[i]);
  102. }
  103. Config.resetChess(buf);
  104. frame.paint(frame.getGraphics());
  105. if (Config.isWin(Color.BLACK)) {
  106. new MyDialog(frame, Color.BLACK).setVisible(true);
  107. } else if (Config.isWin(Color.WHITE)) {
  108. new MyDialog(frame, Color.WHITE).setVisible(true);
  109. }
  110. flag = true;
  111. }
  112. }
  113. } catch (Exception e) {
  114. e.printStackTrace();
  115. new MyDialog(frame, "连接服务器失败", true).setVisible(true);
  116. return;
  117. }
  118. }
  119. public void threadDestory() throws Exception{
  120. in.close();
  121. out.close();
  122. client.close();
  123. }
  124. private void init() {
  125. String[][] initValue = new String[][] { { "IP地址:", "127.0.0.1" },
  126. { "端口:", "7777" } };
  127. // 创建创建账号的对话框
  128. MyDialog initDialog = new MyDialog(frame, "请输入对方地址", true, initValue);
  129. initDialog.setVisible(true);
  130. // 获得输入数据
  131. String[] nameAndPort = initDialog.getValue();
  132. if (nameAndPort == null) {
  133. return;
  134. }
  135. this.ip = nameAndPort[0];
  136. try {
  137. this.port = Integer.valueOf(nameAndPort[1]);
  138. // 判断端口号是否正确
  139. if (port <= 0 || port > 65536) {
  140. String errMsg = "错误的端口号" + nameAndPort[1] + "。端口号必须在0和65536之间";
  141. JOptionPane.showMessageDialog(frame, errMsg, "错误的端口号",
  142. JOptionPane.ERROR_MESSAGE);
  143. return;
  144. }
  145. } catch (NumberFormatException ex) {
  146. JOptionPane.showMessageDialog(frame, "输入的端口号不是数字。", "错误的端口号",
  147. JOptionPane.ERROR_MESSAGE);
  148. return;
  149. }
  150. Config.setPort(port);
  151. Config.clearChess();
  152. frame.paint(frame.getGraphics());
  153. }
  154. }
复制代码
[文件] GameServer.java ~ 4KB (13)
  1. package game;
  2. import java.awt.Color;
  3. import java.awt.Graphics;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.net.ServerSocket;
  8. import java.net.Socket;
  9. import javax.swing.JFrame;
  10. import javax.swing.JOptionPane;
  11. import panel.Config;
  12. import panel.MyListener;
  13. public class GameServer implements Runnable {
  14. private ServerSocket server;
  15. private Socket client;
  16. private JFrame frame;
  17. private int port;
  18. private String name;
  19. private InputStream in;
  20. private OutputStream out;
  21. private boolean flag = true;
  22. public GameServer(JFrame frame) {
  23. this.frame = frame;
  24. }
  25. public void threadDestory() throws Exception{
  26. in.close();
  27. out.close();
  28. client.close();
  29. server.close();
  30. }
  31. /**
  32. * 确认连接
  33. */
  34. private void confirm() throws IOException {
  35. out.write(name.getBytes());
  36. }
  37. private void sendUI() throws IOException{
  38. String s=new String(Config.SIZE+"#"+Config.ROW+"#"+Config.CLOUNM);
  39. out.write(s.getBytes());
  40. }
  41. public void run() {
  42. init();
  43. try {
  44. server = new ServerSocket(Config.getPort());
  45. client = server.accept();
  46. in = client.getInputStream();
  47. out = client.getOutputStream();
  48. confirm();
  49. sendUI();
  50. // 设置棋子颜色
  51. Config.setColor(Color.BLACK);
  52. // 交替下棋
  53. MyListener police = new MyListener();
  54. Graphics g = frame.getGraphics();
  55. while (true) {
  56. if (flag) {
  57. frame.addMouseListener(police);
  58. while (Config.getX() == -1) {
  59. Thread.sleep(20);
  60. }
  61. int x = Config.getX();
  62. int y = Config.getY();
  63. Config.clearNotify();
  64. g.setColor(Config.getColor());
  65. g.fillOval(x - (Config.SIZE / 2), y - (Config.SIZE / 2),
  66. Config.SIZE - 5, Config.SIZE - 5);
  67. // 发送棋盘给客户端
  68. byte[][] chess = Config.getChess();
  69. for (int i = 0; i <= Config.ROW; i++) {
  70. out.write(chess[i]);
  71. }
  72. if (Config.isWin(Color.BLACK)) {
  73. new MyDialog(frame, Color.BLACK).setVisible(true);
  74. } else if (Config.isWin(Color.WHITE)) {
  75. new MyDialog(frame, Color.WHITE).setVisible(true);
  76. }
  77. flag = !flag;
  78. frame.removeMouseListener(police);
  79. } else {
  80. byte[] buf = new byte[2];
  81. in.read(buf);
  82. Config.isChessMan(buf[0], buf[1],
  83. (Config.getColor() == Color.BLACK) ? Color.WHITE
  84. : Color.BLACK);
  85. frame.paint(g);
  86. if (Config.isWin(Color.BLACK)) {
  87. new MyDialog(frame, Color.BLACK).setVisible(true);
  88. } else if (Config.isWin(Color.WHITE)) {
  89. new MyDialog(frame, Color.WHITE).setVisible(true);
  90. }
  91. flag = true;
  92. }
  93. }
  94. } catch (Exception e) {
  95. e.printStackTrace();
  96. new MyDialog(frame, "客户端已下线", true).setVisible(true);
  97. return;
  98. }
  99. }
  100. private void init() {
  101. String[][] initValue = new String[][] { { "用户名:", "CJN" },
  102. { "端口:", "7777" } };
  103. MyDialog initDialog = new MyDialog(frame, "请输入用户名和端口", true, initValue);
  104. initDialog.setVisible(true);
  105. String[] nameAndPort = initDialog.getValue();
  106. if (nameAndPort == null) {
  107. return;
  108. }
  109. this.name = nameAndPort[0];
  110. try {
  111. this.port = Integer.valueOf(nameAndPort[1]);
  112. // 判断端口号是否正确
  113. if (port <= 0 || port > 65536) {
  114. String errMsg = "错误的端口号" + nameAndPort[1] + "。端口号必须在0和65536之间";
  115. JOptionPane.showMessageDialog(frame, errMsg, "错误的端口号",
  116. JOptionPane.ERROR_MESSAGE);
  117. return;
  118. }
  119. } catch (NumberFormatException ex) {
  120. JOptionPane.showMessageDialog(frame, "输入的端口号不是数字。", "错误的端口号",
  121. JOptionPane.ERROR_MESSAGE);
  122. return;
  123. }
  124. Config.setPort(port);
  125. frame.setTitle("五子棋 " + "玩家: " + name + " 端口号:" + port);
  126. Config.clearChess();
  127. frame.paint(frame.getGraphics());
  128. }
  129. }
复制代码
[文件] MyDialog.java ~ 5KB (11)
  1. package game;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import javax.swing.*;
  5. import panel.Config;
  6. /**
  7. * 本类用于添加建立相应的对话框
  8. *
  9. * @author chenj_000
  10. *
  11. */
  12. @SuppressWarnings("serial")
  13. public class MyDialog extends JDialog implements ActionListener {
  14. static final int YES = 1, NO = 0;
  15. int message = -1;
  16. JButton yes, no;
  17. JFrame frame;
  18. private String context;
  19. /**
  20. * 需要添加进文本框的字符串数组初值
  21. */
  22. private String[][] items;
  23. /**
  24. * 根据传入的字符串数组创建的文本框对象
  25. */
  26. private JTextField[] values;
  27. /**
  28. * 需要返回的文本框中的数据
  29. */
  30. private String[] retValues;
  31. /**
  32. * 该构造方法用以创建一个具有指定标题、所有者 Frame 和模式的对话框
  33. */
  34. public MyDialog(Frame owner, String title, boolean modal, String[][] items) {
  35. super(owner, title, modal);
  36. this.items = items;
  37. init();
  38. }
  39. /**
  40. * 设置提醒对话框
  41. */
  42. public MyDialog(JFrame j, String context, boolean flag) {
  43. super(j, "提醒", flag);
  44. frame = j;
  45. this.context = context;
  46. warn();
  47. }
  48. /**
  49. * 设置胜利对话框
  50. */
  51. public MyDialog(JFrame j, Color color) {
  52. super(j, "提示", true);
  53. frame = j;
  54. // Config.resetColor();
  55. win(color);
  56. }
  57. private void warn() {
  58. yes = new JButton("确定");
  59. no = new JButton("取消");
  60. yes.addActionListener(this);
  61. no.addActionListener(this);
  62. JPanel p1 = new JPanel();
  63. p1.add(new JLabel(context));
  64. JPanel p2 = new JPanel();
  65. p2.add(yes);
  66. p2.add(no);
  67. add(p1, BorderLayout.NORTH);
  68. add(p2, BorderLayout.CENTER);
  69. int x = (int) (frame.getBounds().x + 0.25 * frame.getBounds().width);
  70. int y = (int) (frame.getBounds().y + 0.25 * frame.getBounds().height);
  71. setBounds(x, y, 200, 110);
  72. addWindowListener(new WindowAdapter() {
  73. public void windowClosing(WindowEvent e) {
  74. message = -1;
  75. setVisible(false);
  76. }
  77. });
  78. }
  79. private void win(Color color) {
  80. yes = new JButton("确定");
  81. yes.addActionListener(this);
  82. JPanel p1 = new JPanel();
  83. String str = (Color.BLACK == color) ? "黑方胜利" : "白方胜利";
  84. p1.add(new JLabel(str));
  85. JPanel p2 = new JPanel();
  86. p2.add(yes);
  87. add(p1, BorderLayout.NORTH);
  88. add(p2, BorderLayout.CENTER);
  89. int x = (int) (frame.getBounds().x + 0.25 * frame.getBounds().width);
  90. int y = (int) (frame.getBounds().y + 0.25 * frame.getBounds().height);
  91. setBounds(x, y, 200, 110);
  92. Config.clearChess();
  93. Config.exchangeColor();
  94. addWindowListener(new WindowAdapter() {
  95. public void windowClosing(WindowEvent e) {
  96. message = -1;
  97. setVisible(false);
  98. }
  99. });
  100. }
  101. @Override
  102. public void actionPerformed(ActionEvent e) {
  103. if (e.getSource() == yes) {
  104. message = YES;
  105. frame.paint(frame.getGraphics());
  106. setVisible(false);
  107. } else if (e.getSource() == no) {
  108. message = NO;
  109. frame.paint(frame.getGraphics());
  110. setVisible(false);
  111. }
  112. }
  113. /**
  114. * 初始化对话框布局
  115. */
  116. private void init() {
  117. Container container = this.getContentPane();
  118. container.setLayout(new GridBagLayout());
  119. GridBagConstraints gbc = new GridBagConstraints();
  120. int count = items.length;
  121. gbc.gridx = 0;
  122. gbc.gridwidth = 1;
  123. gbc.gridheight = 1;
  124. gbc.fill = GridBagConstraints.NONE;
  125. gbc.insets = new Insets(3, 3, 3, 3);
  126. for (int i = 0; i < count; i++) {
  127. gbc.gridy = i;
  128. container.add(new JLabel(items[i][0]), gbc);
  129. }
  130. values = new JTextField[count];
  131. gbc.gridx = 1;
  132. gbc.gridwidth = 1;
  133. gbc.gridheight = 1;
  134. gbc.weightx = 1.0;
  135. gbc.weighty = 0;
  136. gbc.fill = GridBagConstraints.HORIZONTAL;
  137. for (int i = 0; i < count; i++) {
  138. gbc.gridy = i;
  139. values[i] = new JTextField(items[i][1]);
  140. container.add(values[i], gbc);
  141. }
  142. gbc.gridx = 0;
  143. gbc.gridy = count;
  144. gbc.gridwidth = 2;
  145. gbc.gridheight = 1;
  146. gbc.weightx = 1.0;
  147. gbc.weighty = 1.0;
  148. gbc.fill = GridBagConstraints.HORIZONTAL;
  149. gbc.anchor = GridBagConstraints.SOUTH;
  150. container.add(new JSeparator(), gbc);
  151. gbc.gridy = count + 1;
  152. gbc.weightx = 1.0;
  153. gbc.weighty = 0;
  154. gbc.fill = GridBagConstraints.NONE;
  155. gbc.anchor = GridBagConstraints.SOUTHEAST;
  156. gbc.insets = new Insets(7, 7, 7, 7);
  157. JButton btn = new JButton("确定");
  158. container.add(btn, gbc);
  159. btn.addActionListener(new ActionListener() {
  160. public void actionPerformed(ActionEvent e) {
  161. retValues = new String[items.length];
  162. for (int i = 0; i < retValues.length; i++) {
  163. retValues[i] = values[i].getText();
  164. }
  165. // 释放所有子组件所使用的所有本机屏幕资源
  166. MyDialog.this.dispose();
  167. }
  168. });
  169. this.setSize(300, count * 30 + 70);
  170. ChessUtils.locateDialogCenter(this);
  171. }
  172. /**
  173. * 获取对话框中的所有数据
  174. */
  175. public String[] getValue() {
  176. return retValues;
  177. }
  178. }

Java免费学习   Java自学网 http://www.javalearns.com

关注微信号:javalearns   随时随地学Java

或扫一扫

随时随地学Java

作者:不详 来源:网络
    你是从哪里知道本网站的?
  • 网友介绍的
  • 百度搜索的
  • Google搜索的
  • 其它搜索过来的
  • 网址输错了进来的
  • 太忙了不记得了
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
  • java学习网(www.javalearns.com) © 2014 版权所有 All Rights Reserved.
  • Email:javalearns@163.com 站长QQ:1356121699 晋ICP备14003680号-3
  • java学习网部分内容来自网络或网友发布,如侵犯了您利益,请发邮件至:javalearns@126.com,我们尽快处理!
  • Java学习网
  • 网站统计
  • 晋公网安备 14042902000001号