In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Here is how the client runs:
Here is the structure of the code package:
Then let me talk about the functions accomplished by these classes in turn.
Media package
Media package: mainly contains background pictures of Gobang, classes for playing music and music content.
I got the category of playing music from my roommate, so I didn't understand it very well. At first glance, it was done in Applet and can only deal with music with .wav suffix.
Net package
Net package: contains two classes, and careful buddies should notice that the client does not have a main method. The client actually contains the socket that communicates with the server, including some read and write methods. On the server side, I use a thread pool method to handle client requests (I don't know much about thread pool either, it feels like multithreading).
View package
View package: contains four classes, namely the ChessBoard,ChessPanel,Pieces and WhoWin classes
ChessBoard is a JFrame that contains the Main method, and both the command panel and the chessboard panel are added to this JFrame.
ChessPanel is a chessboard panel, which completes such as: drawing the chessboard lines of 1919, loading background pictures, constantly receiving messages from the server and processing (adding pieces to the panel), adding pieces to the panel and sending pieces to the server after each click, judging the outcome and giving prompts.
Pieces is a chess piece, which contains attributes such as color, piece radius, piece position and command (used with the previous command panel, the default is send).
WhoWin is the part of Gobang that judges who loses and who wins. Every next step needs to be judged.
Classes that play music:
Package Media.Music;import java.io.File;import java.io.IOException;import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.Clip;import javax.sound.sampled.LineUnavailableException;import javax.sound.sampled.UnsupportedAudioFileException;public class PlayMusic {private Clip clip; public PlayMusic (String filePath) throws LineUnavailableException, UnsupportedAudioFileException, IOException {File file = new File (filePath); AudioInputStream audioInputStream = AudioSystem.getAudioInputStream (file); clip = AudioSystem.getClip () Clip.open (audioInputStream);} public void play () {clip.setFramePosition (1); clip.start ();} public void loop () {clip.loop (Clip.LOOP_CONTINUOUSLY);} public void stop () {clip.stop ();}}
TcpClient:
Package net;import view.Pieces;import java.io.*;import java.net.Socket;public class TcpClient {private Socket socket; private ObjectInputStream ois; private ObjectOutputStream oos; public TcpClient (Socket socket,ObjectInputStream ois,ObjectOutputStream oos) {this.socket= socket; this.ois = ois; this.oos = oos;} public Socket getSocket () {return socket;} public void setSocket (Socket socket) {this.socket= socket } public ObjectInputStream getOis () {return ois;} public void setOis (ObjectInputStream ois) {this.ois = ois;} public ObjectOutputStream getOos () {return oos;} public void setOos (ObjectOutputStream oos) {this.oos = oos;} public void send (Pieces pieces) throws IOException {oos.writeObject (pieces) System.out.println (socket+ "send message to server");} public Pieces accept () throws IOException, ClassNotFoundException {Pieces pieces = (Pieces) ois.readObject (); System.out.println (socket+ "read message from server"); return pieces;} public void close () {;}}
TcpServer:
Package net;import view.Pieces;import java.io.*;import java.net.ServerSocket;import java.net.Socket;import java.net.SocketException;import java.util.ArrayList;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class TcpServer {public static void main (String [] args) {/ / Save the thread processed by the client ArrayList userList = new ArrayList () / / the fixed size thread pool supports only two threads to handle client ExecutorService es = Executors.newFixedThreadPool (2); try {ServerSocket server = new ServerSocket (10086); System.out.println ("the server has been started and is waiting for a client connection.") While (true) {/ / receive the Socket of the client, Socket socket = server.accept () if there is no client connection; / / create a thread UserThread user = new UserThread (socket, userList) for each user / / start thread es.execute (user);}} catch (IOException e) {e.printStackTrace ();} class UserThread implements Runnable {private Socket socket = null; private static ArrayList list; / / client thread collection private ObjectOutputStream oos; private ObjectInputStream ois; private boolean flag = true / / Mark public UserThread (Socket socket, ArrayList list) {this.socket = socket; this.list = list; list.add (this); / / add the current thread to the list} @ Override public void run () {UserThread user = null; try {System.out.println ("client:" + socket.getInetAddress (). GetHostAddress () + "connected") Ois = new ObjectInputStream (socket.getInputStream ()); oos = new ObjectOutputStream (socket.getOutputStream ()); while (true) {Pieces pieces = (Pieces) ois.readObject (); / / the message sent to the server by the client to int size = list.size (); for (int I = 0; I)
< size; i++) { user = list.get(i); if (user.socket != socket) { user.oos.writeObject(pieces); System.out.println("从"+socket+"向"+user.socket+"发送消息"); } } } } catch(SocketException e){ // todo 客户端掉线后,移除客户端。没想好{1.从客户端列表移除当前元素,关闭当前:socket,通知另一方:这一方已经掉线,然后关闭这一方的socket} try { int i = list.size(); if (i ==2){ list.remove(user); System.out.println("已经删除了一个客户端"); list.get(0).oos.writeObject(new Pieces("对方掉线")); }else if (i==1){ list.remove(0); System.out.println("又移除了另一个客户端"); } } catch (IOException ex) { ex.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }} ChessBoard: /** 1.变量值不变的问题* 2.输入输出流先后顺序的问题(socket阻塞)* 3.socket 短连接不关闭输入输出流,为何看起来就像长连接一样(长短连接的区别是什么)* */// todo 一个提示框package view;import Media.Music.PlayMusic;import javax.sound.sampled.LineUnavailableException;import javax.sound.sampled.UnsupportedAudioFileException;import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.IOException;public class ChessBoard extends JFrame implements ActionListener { private JButton PlayMusic = new JButton("播放音乐"); private ChessPanel chessPanel; private Panel CommandPanel = new Panel(); private JButton reStart = new JButton("重新开始"); private JButton fail = new JButton("认输"); private JButton Regret = new JButton("悔棋"); private String command=null; // 触发按钮后发送的命令 private PlayMusic music = null; private int count = 1; // todo 静态语句块 { try { music = new PlayMusic("./src/Media/Music/bg3.wav"); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public ChessBoard() { this.setTitle("欢乐五子棋"); chessPanel = new ChessPanel(); this.add(chessPanel,BorderLayout.CENTER); reStart.addActionListener(this); fail .addActionListener(this); Regret.addActionListener(this); PlayMusic.addActionListener(this); CommandPanel.add(reStart); CommandPanel.add(fail); CommandPanel.add(Regret); CommandPanel.add(PlayMusic); this.add(CommandPanel,BorderLayout.SOUTH); this.setBounds(10, 10, 800, 800); this.setVisible(true); this.setResizable(false); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { ChessBoard Board = new ChessBoard(); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==reStart){ command ="重新开始"; chessPanel.canPlay = true; }else if(e.getSource()==fail){ command ="认输"; JOptionPane.showMessageDialog(chessPanel,"It's a pity,you have fail the game!"); chessPanel.canPlay = false; }else if (e.getSource()==Regret){ command ="悔棋"; }else if (e.getSource()==PlayMusic){ // todo 播放音乐,单数次播放; if (count%2==1){ music.play(); }else { music.stop(); } count++; command = null; } if(command!=null){ Pieces pieces = new Pieces(command); try { this.chessPanel.client.send(pieces); } catch (IOException ex) { ex.printStackTrace(); } } }} ChessPanel: package view;// 五子棋面板,就是在这里面画图。// todo 背景图片 ,也许一个背景音乐import net.TcpClient;import javax.swing.*;import java.awt.*;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.net.ConnectException;import java.net.Socket;import java.util.ArrayList;import java.util.Iterator;public class ChessPanel extends JPanel implements MouseListener{ // TODO 从服务器接收来的棋子 ,值不变有问题// Pieces accept_pieces = new Pieces();// Pieces send_pieces = new Pieces(); whoWin ifWin =new whoWin() ; // 是否胜利 TcpClient client = null; // 客户端 boolean canPlay = true; // 是否能继续玩 boolean isBlack = true; // 是否黑子,黑1,白2 ArrayList allPieces = new ArrayList(); // 存储棋子对象,就是通过这个画图的 int [][] allChess = new int[19][19]; int PanelWidth; int PanelHeight; int width = 600; int height = 600; int temp = width / 18; int xbase,ybase; Image image = Toolkit.getDefaultToolkit().getImage("./src/Media/bg.jpeg"); // "./"表示当前项目下 public ChessPanel(){ this.addMouseListener(this); try { Socket socket = new Socket("172.27.29.190", 10086); //TODO 构建输出输入流,输入输出流问题,先输出后输入 ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); client = new TcpClient(socket,ois,oos); new Thread(new getMessage()).start(); // 开启读取的线程 } catch (ConnectException e){ System.out.println("服务器拒绝连接!"); } catch (IOException e) { e.printStackTrace(); }catch(Exception e ){ e.printStackTrace(); } } // 画图部分 public void paintComponent(Graphics g) { super.paintComponent(g); PanelWidth = this.getSize().width; // 这两步骤 PanelHeight = this.getSize().height; xbase = (PanelWidth - width) / 2; ybase = (PanelHeight - height) / 2; Graphics2D g2d = (Graphics2D) g;// this.setBackground(new Color(246, 186, 114)); g2d.drawImage(image,0,0,this.getWidth(),this.getHeight(),this); int x1, y1, x2, y2; // 画线 for (int i = 0; i < 19; i++) { if (i == 0 || i == 18) { g2d.setStroke(new BasicStroke(3.0f)); } else g2d.setStroke(new BasicStroke(1.0f)); x1 = xbase + temp * i; y1 = ybase; y2 = ybase + 18 * temp; g2d.drawLine(x1, y1, x1, y2); x1 = xbase; y1 = ybase + temp * i; x2 = xbase + temp * 18; g2d.drawLine(x1, y1, x2, y1); } // 开始画棋子 int radius ; int xPos,yPos; Iterator it = allPieces.iterator(); // 迭代器遍历arraylist while(it.hasNext()){ Pieces pieces = (Pieces) it.next(); radius = pieces.getRadius(); xPos = pieces.getxPos(); yPos = pieces.getyPos(); System.out.println(pieces.getColor()+","+pieces.getxPos()+","+pieces.getyPos()); if (pieces.getColor() == 1){ g2d.setColor(Color.black); g2d.fillOval(xPos*temp+xbase-radius/2,yPos*temp+ybase-radius/2,radius,radius); } else if (pieces.getColor() == 2) { g2d.setColor(Color.white); g2d.fillOval(xPos * temp + xbase - radius / 2, yPos * temp + ybase - radius / 2, radius, radius); } } } @Override public void mousePressed(MouseEvent e) { int x ,y ; if (canPlay) { x = e.getX(); y = e.getY(); // 判断鼠标点击位置 if (x >= xbase & x = ybase & y
< (ybase + 18 * temp)) { // 判断是不是下在空的位置 int tempX = (x - xbase) / temp, tempY = (y - ybase) / temp; // todo 这里是关键判断这点坐标的数组下标是什么 if ((x - xbase) % temp >Temp / 2) {x = tempX + 1;} else x = tempX; if ((y-ybase)% temp > temp / 2) y = tempY + 1; else y = tempY / / first judge whether there are chess pieces, and deal with the case where there are no chess pieces if (allChess [x] [y]! = 0) {JOptionPane.showMessageDialog (this, "there are chess pieces here");} else {Pieces send_pieces = new Pieces (); send_pieces.setxPos (x) Send_pieces.setyPos (y); if (isBlack) {send_pieces.setColor (1); allChess [x] [y] = 1; isBlack = false } else {send_pieces.setColor (2); allChess [x] [y] = 2; isBlack = true;} allPieces.add (send_pieces) / / add current pieces to the chess team canPlay = false;// canPlay in the case of true, do not click this.repaint (); ifWin = new whoWin (allChess,x,y); / / if you win, you can't play and give a message that you win. If (ifWin.isWin ()) {canPlay = false; JOptionPane.showMessageDialog (this, "Congratulations you have won tha game!");} try {if (clientproof null) {client.send (send_pieces) }} catch (IOException ex) {ex.printStackTrace ();}} / / read the information from the server class getMessage implements Runnable {private boolean flag = true Public void setFlag (boolean flag) {this.flag = flag;} @ Override public void run () {/ / Loop read while (flag) {if (clientcircle read null) {try {Pieces accept_pieces = client.accept () String command = accept_pieces.getCommand (); int color = accept_pieces.getColor (); switch (command) {case "send": {canPlay = true If (color = = 1) {isBlack = false;// the other party is black and I am white} else {isBlack = true } allPieces.add (accept_pieces); allChess [accept _ pieces.getxPos ()] [accept_pieces.getyPos ()] = accept_pieces.getColor (); ChessPanel.this.repaint () IfWin.setY (accept_pieces.getyPos ()); ifWin.setX (accept_pieces.getxPos ()); ifWin.setAllChess (allChess); if (ifWin.isWin ()) {canPlay = false JOptionPane.showMessageDialog (ChessPanel.this, "It's a pity you have fail the game!");} break } case "repentance Chess": {int I = JOptionPane.showConfirmDialog (ChessPanel.this, "whether the other party requests repentance Chess, do you agree!") / / yes 0 Pieces pieces no 1 remorse (); if (I = = 0) {/ / agree to repentance: 1. Agree to pieces.setCommand ("agree to repentance"); / / arraylist to remove the last two values, corresponding to allChess set 0 int size = allPieces.size (); for (int j = 1) J = 5) return true;} return false;} private int Count (int xChange, int yChange, int color) {int count = 1; int tempX = xChange, tempY = yChange; while (color = = allChess [x + xChange] [y + yChange]) {count++ If (xChange! = 0) {xChange++;} if (yChange! = 0) {if (yChange > 0) yChange++; else yChange--;}} xChange = tempX; yChange = tempY While (color = = allChess [x-xChange] [y-yChange]) {count++; if (xChange! = 0) xChange++; if (yChange! = 0) {if (yChange > 0) yChange++; else yChange-- }} return count;}} this is the end of the introduction of "how java implements online Gobang". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.