本文目錄一覽:
求五子棋Java代碼旁邊就注釋 讓我看的清楚明白一些,要詳細(xì)的解釋和思路
import java.applet.*;
import t.*;
import t.event.*;
import java.applet.Applet;
import t.Color; //這一段import就不說了,下面要用到的就import進(jìn)來
public class wuziqi extends Applet implements ActionListener,MouseListener,MouseMotionListener,ItemListener
//繼承Applet表明是個(gè)applet,后面的接口必須要實(shí)現(xiàn)每個(gè)接口的所有方法
{
int color_Qizi=0;//旗子的顏色標(biāo)識(shí) 0:白子 1:黑子
int intGame_Start=0;//游戲開始標(biāo)志 0未開始 1游戲中
int intGame_Body[][]=new int[16][16]; //設(shè)置棋盤棋子狀態(tài) 0 無子 1 白子 2 黑子
java五子棋代碼帶詳細(xì)解釋
浩大的工程 你有五子棋程序 如果你水平還行的話你參照這個(gè)聊天室程序應(yīng)該也比較容易寫出人人對(duì)戰(zhàn)的
package Chat;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.StringTokenizer;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
/**
* 聊天室的客戶端程序,GUI界面。
*/
public class ChatClient extends JFrame implements ActionListener{
// 登陸聊天室的名字標(biāo)簽和輸入框
JLabel nameLabel = new JLabel();
JTextField nameTextField = new JTextField(15);
// 連接和斷開連接的按鈕
JButton connectButton = new JButton();
JButton disConnectButton = new JButton();
// 聊天室內(nèi)容的文本域
JTextArea chatContentTextArea = new JTextArea(9, 30);
// 發(fā)送消息的按鈕
JButton sendMsgButton = new JButton();
// 消息輸入框
JTextField msgTextField = new JTextField(20);
JLabel msglabel = new JLabel();
// 聊天室用戶列表
java.awt.List peopleList = new java.awt.List(10);
/*以下定義數(shù)據(jù)流和網(wǎng)絡(luò)變量*/
Socket soc = null;
PrintStream ps = null;
// 客戶端偵聽服務(wù)器消息的線程
ClentListener listener = null;
public ChatClient() {
init();
}
// 初始化圖形界面
public void init() {
this.setTitle("聊天室客戶端");
// 初始化按鈕和標(biāo)簽
nameLabel.setText("姓名:");
connectButton.setText("連 接");
connectButton.addActionListener(this);
disConnectButton.setText("斷 開");
disConnectButton.addActionListener(this);
// 設(shè)置聊天內(nèi)容不可編輯
chatContentTextArea.setEditable(false);
sendMsgButton.setText("發(fā) 送");
sendMsgButton.addActionListener(this);
msgTextField.setText("請輸入聊天信息");
//panel1放置輸入姓名和連接兩個(gè)按鈕
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout());
panel1.add(nameLabel);
panel1.add(nameTextField);
panel1.add(connectButton);
panel1.add(disConnectButton);
//用于放置聊天信息顯示和聊天人員列表
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
JScrollPane pane1 = new JScrollPane(chatContentTextArea);
pane1.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(134, 134, 134)), "聊天內(nèi)容"));
panel2.add(pane1);
JScrollPane pane2 = new JScrollPane(peopleList);
pane2.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(134, 134, 134)), "用戶列表"));
panel2.add(pane2);
//用于放置發(fā)送信息區(qū)域
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
panel3.add(msglabel);
panel3.add(msgTextField);
panel3.add(sendMsgButton);
// 將組件添加到界面
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(panel1, BorderLayout.NORTH);
this.getContentPane().add(panel2, BorderLayout.CENTER);
this.getContentPane().add(panel3, BorderLayout.SOUTH);
this.pack();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 關(guān)閉聊天室客戶端事件
*/
protected void processWindowEvent(WindowEvent e){
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
// 如果是關(guān)閉聊天室客戶端,則斷開連接
disconnect();
dispose();
System.exit(0);
}
}
/**
* 處理按鈕事件
*/
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == connectButton){
// 如果點(diǎn)擊連接按鈕
if (soc == null) {
try {
// 使用端口2525實(shí)例化一個(gè)本地套接字
soc = new Socket(InetAddress.getLocalHost(), Constants.SERVER_PORT);
// 在控制臺(tái)打印實(shí)例化的結(jié)果
System.out.println(soc);
//將ps指向soc的輸出流
ps = new PrintStream(soc.getOutputStream());
//定義一個(gè)字符緩沖存儲(chǔ)發(fā)送信息
StringBuffer info = new StringBuffer(Constants.CONNECT_IDENTIFER).append(Constants.SEPERATOR);
//其中INFO為關(guān)鍵字讓服務(wù)器識(shí)別為連接信息
//并將name和ip用":"分開,在服務(wù)器端將用一個(gè)
//StringTokenizer類來讀取數(shù)據(jù)
String userinfo = nameTextField.getText() + Constants.SEPERATOR
+ InetAddress.getLocalHost().getHostAddress();
ps.println(info.append(userinfo));
ps.flush();
//將客戶端線程實(shí)例化,并啟動(dòng)
listener = new ClentListener(this, nameTextField.getText(), soc);
listener.start();
} catch (IOException e) {
System.out.println("Error:" + e);
disconnect();
}
}
} else if (source == disConnectButton){
// 如果點(diǎn)擊斷開連接按鈕
disconnect();
} else if (source == sendMsgButton) {
//如果點(diǎn)擊發(fā)送按鈕
if (soc != null) {
//定義并實(shí)例化一個(gè)字符緩沖存儲(chǔ)發(fā)送的聊天信息
StringBuffer msg = new StringBuffer(Constants.MSG_IDENTIFER).append(Constants.SEPERATOR);
//用打印流發(fā)送聊天信息
ps.println(msg.append(msgTextField.getText()));
ps.flush();
}
}
}
/**
* 斷開與服務(wù)器的連接
*/
public void disconnect(){
if (soc != null) {
try {
// 用打印流發(fā)送QUIT信息通知服務(wù)器斷開此次通信
ps.println(Constants.QUIT_IDENTIFER);
ps.flush();
soc.close(); //關(guān)閉套接字
listener.toStop();
soc = null;
} catch (IOException e) {
System.out.println("Error:" + e);
}
}
}
public static void main(String[] args){
ChatClient client = new ChatClient();
client.setVisible(true);
}
/**
* 客戶端線程類用來監(jiān)聽服務(wù)器傳來的信息
*/
class ClentListener extends Thread {
//存儲(chǔ)客戶端連接后的name信息
String name = null;
//客戶端接受服務(wù)器數(shù)據(jù)的輸入流
BufferedReader br = null;
//實(shí)現(xiàn)從客戶端發(fā)送數(shù)據(jù)到服務(wù)器的打印流
PrintStream ps = null;
//存儲(chǔ)客戶端的socket信息
Socket socket = null;
//存儲(chǔ)當(dāng)前運(yùn)行的ChatClient實(shí)例
ChatClient parent = null;
boolean running = true;
//構(gòu)造方法
public ClentListener(ChatClient p, String n, Socket s) {
//接受參數(shù)
parent = p;
name = n;
socket = s;
try {
//實(shí)例化兩個(gè)數(shù)據(jù)流
br = new BufferedReader(new InputStreamReader(s
.getInputStream()));
ps = new PrintStream(s.getOutputStream());
} catch (IOException e) {
System.out.println("Error:" + e);
parent.disconnect();
}
}
// 停止偵聽
public void toStop(){
this.running = false;
}
//線程運(yùn)行方法
public void run(){
String msg = null;
while (running) {
msg = null;
try {
// 讀取從服務(wù)器傳來的信息
msg = br.readLine();
System.out.println("receive msg: " + msg);
} catch (IOException e) {
System.out.println("Error:" + e);
parent.disconnect();
}
// 如果從服務(wù)器傳來的信息為空則斷開此次連接
if (msg == null) {
parent.listener = null;
parent.soc = null;
parent.peopleList.removeAll();
running = false;
return;
}
//用StringTokenizer類來實(shí)現(xiàn)讀取分段字符
StringTokenizer st = new StringTokenizer(msg, Constants.SEPERATOR);
//讀取信息頭即關(guān)鍵字用來識(shí)別是何種信息
String keyword = st.nextToken();
if (keyword.equals(Constants.PEOPLE_IDENTIFER)) {
//如果是PEOPLE則是服務(wù)器發(fā)來的客戶連接信息
//主要用來刷新客戶端的用戶列表
parent.peopleList.removeAll();
//遍歷st取得目前所連接的客戶
while (st.hasMoreTokens()) {
String str = st.nextToken();
parent.peopleList.add(str);
}
} else if (keyword.equals(Constants.MSG_IDENTIFER)) {
//如果關(guān)鍵字是MSG則是服務(wù)器傳來的聊天信息,
//主要用來刷新客戶端聊天信息區(qū)將每個(gè)客戶的聊天內(nèi)容顯示出來
String usr = st.nextToken();
parent.chatContentTextArea.append(usr);
parent.chatContentTextArea.append(st.nextToken("\0"));
parent.chatContentTextArea.append("\r\n");
} else if (keyword.equals(Constants.QUIT_IDENTIFER)) {
//如果關(guān)鍵字是QUIT則是服務(wù)器關(guān)閉的信息, 切斷此次連接
System.out.println("Quit");
try {
running = false;
parent.listener = null;
parent.soc.close();
parent.soc = null;
} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
parent.soc = null;
parent.peopleList.removeAll();
}
break;
}
}
//清除用戶列表
parent.peopleList.removeAll();
}
}
}
package Chat;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
/**
* 聊天室的服務(wù)器端程序,GUI界面
*/
public class ChatServer extends JFrame {
// 狀態(tài)欄標(biāo)簽
static JLabel statusBar = new JLabel();
// 顯示客戶端的連接信息的列表
static java.awt.List connectInfoList = new java.awt.List(10);
// 保存當(dāng)前處理客戶端請求的處理器線程
static Vector clientProcessors = new Vector(10);
// 當(dāng)前的連接數(shù)
static int activeConnects = 0;
// 構(gòu)造方法
public ChatServer() {
init();
try {
// 設(shè)置界面為系統(tǒng)默認(rèn)外觀
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
e.printStackTrace();
}
}
private void init(){
this.setTitle("聊天室服務(wù)器");
statusBar.setText("");
// 初始化菜單
JMenu fileMenu = new JMenu();
fileMenu.setText("文件");
JMenuItem exitMenuItem = new JMenuItem();
exitMenuItem.setText("退出");
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exitActionPerformed(e);
}
});
fileMenu.add(exitMenuItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);
// 將組件進(jìn)行布局
JPanel jPanel1 = new JPanel();
jPanel1.setLayout(new BorderLayout());
JScrollPane pane = new JScrollPane(connectInfoList);
pane.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(134, 134, 134)), "客戶端連接信息"));
jPanel1.add(new JScrollPane(pane), BorderLayout.CENTER);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(statusBar, BorderLayout.SOUTH);
this.getContentPane().add(jPanel1, BorderLayout.CENTER);
this.pack();
}
/**
* 退出菜單項(xiàng)事件
* @param e
*/
public void exitActionPerformed(ActionEvent e){
// 向客戶端發(fā)送斷開連接信息
sendMsgToClients(new StringBuffer(Constants.QUIT_IDENTIFER));
// 關(guān)閉所有的連接
closeAll();
System.exit(0);
}
/**
* 處理窗口關(guān)閉事件
*/
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
exitActionPerformed(null);
}
}
/**
* 刷新聊天室,不斷刷新clientProcessors,制造最新的用戶列表
*/
public static void notifyRoomPeople(){
StringBuffer people = new StringBuffer(Constants.PEOPLE_IDENTIFER);
for (int i = 0; i clientProcessors.size(); i++) {
ClientProcessor c = (ClientProcessor) clientProcessors.elementAt(i);
people.append(Constants.SEPERATOR).append(c.clientName);
}
// 用sendClients方法向客戶端發(fā)送用戶列表的信息
sendMsgToClients(people);
}
/**
* 向所有客戶端群發(fā)消息
* @param msg
*/
public static synchronized void sendMsgToClients(StringBuffer msg) {
for (int i = 0; i clientProcessors.size(); i++) {
ClientProcessor c = (ClientProcessor) clientProcessors.elementAt(i);
System.out.println("send msg: " + msg);
c.send(msg);
}
}
/**
* 關(guān)閉所有連接
*/
public static void closeAll(){
while (clientProcessors.size() 0) {
ClientProcessor c = (ClientProcessor) clientProcessors.firstElement();
try {
// 關(guān)閉socket連接和處理線程
c.socket.close();
c.toStop();
} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
clientProcessors.removeElement(c);
}
}
}
/**
* 判斷客戶端是否合法。
* 不允許同一客戶端重復(fù)登陸,所謂同一客戶端是指IP和名字都相同。
* @param newclient
* @return
*/
public static boolean checkClient(ClientProcessor newclient){
if (clientProcessors.contains(newclient)){
return false;
} else {
return true;
}
}
/**
* 斷開某個(gè)連接,并且從連接列表中刪除
* @param client
*/
public static void disconnect(ClientProcessor client){
disconnect(client, true);
}
/**
* 斷開某個(gè)連接,根據(jù)要求決定是否從連接列表中刪除
* @param client
* @param toRemoveFromList
*/
public static synchronized void disconnect(ClientProcessor client, boolean toRemoveFromList){
try {
//在服務(wù)器端程序的list框中顯示斷開信息
connectInfoList.add(client.clientIP + "斷開連接");
ChatServer.activeConnects--; //將連接數(shù)減1
String constr = "目前有" + ChatServer.activeConnects + "客戶相連";
statusBar.setText(constr);
//向客戶發(fā)送斷開連接信息
client.send(new StringBuffer(Constants.QUIT_IDENTIFER));
client.socket.close();
} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
//從clients數(shù)組中刪除此客戶的相關(guān)socket等信息, 并停止線程。
if (toRemoveFromList) {
clientProcessors.removeElement(client);
client.toStop();
}
}
}
public static void main(String[] args) {
ChatServer chatServer1 = new ChatServer();
chatServer1.setVisible(true);
System.out.println("Server starting ...");
ServerSocket server = null;
try {
// 服務(wù)器端開始偵聽
server = new ServerSocket(Constants.SERVER_PORT);
} catch (IOException e) {
System.out.println("Error:" + e);
System.exit(1);
}
while (true) {
// 如果當(dāng)前客戶端數(shù)小于MAX_CLIENT個(gè)時(shí)接受連接請求
if (clientProcessors.size() Constants.MAX_CLIENT) {
Socket socket = null;
try {
// 收到客戶端的請求
socket = server.accept();
if (socket != null) {
System.out.println(socket + "連接");
}
} catch (IOException e) {
System.out.println("Error:" + e);
}
// 定義并實(shí)例化一個(gè)ClientProcessor線程類,用于處理客戶端的消息
ClientProcessor c = new ClientProcessor(socket);
if (checkClient(c)) {
// 添加到列表
clientProcessors.addElement(c);
// 如果客戶端合法,則繼續(xù)
int connum = ++ChatServer.activeConnects;
// 在狀態(tài)欄里顯示連接數(shù)
String constr = "目前有" + connum + "客戶相連";
ChatServer.statusBar.setText(constr);
// 將客戶socket信息寫入list框
ChatServer.connectInfoList.add(c.clientIP + "連接");
c.start();
// 通知所有客戶端用戶列表發(fā)生變化
notifyRoomPeople();
} else {
//如果客戶端不合法
c.ps.println("不允許重復(fù)登陸");
disconnect(c, false);
}
} else {
//如果客戶端超過了MAX_CLIENT個(gè),則等待一段時(shí)間再嘗試接受請求
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
}
}
}
}
/**
* 處理客戶端發(fā)送的請求的線程
*/
class ClientProcessor extends Thread {
//存儲(chǔ)一個(gè)連接客戶端的socket信息
Socket socket;
//存儲(chǔ)客戶端的連接姓名
String clientName;
//存儲(chǔ)客戶端的ip信息
String clientIP;
//用來實(shí)現(xiàn)接受從客戶端發(fā)來的數(shù)據(jù)流
BufferedReader br;
//用來實(shí)現(xiàn)向客戶端發(fā)送信息的打印流
PrintStream ps;
boolean running = true;
/**
* 構(gòu)造方法
* @param s
*/
public ClientProcessor(Socket s) {
socket = s;
try {
// 初始化輸入輸出流
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ps = new PrintStream(socket.getOutputStream());
// 讀取收到的信息,第一條信息是客戶端的名字、IP信息
String clientInfo = br.readLine();
// 讀取信息,根據(jù)消息分隔符解析消息
StringTokenizer stinfo = new StringTokenizer(clientInfo, Constants.SEPERATOR);
String head = stinfo.nextToken();
if (head.equals(Constants.CONNECT_IDENTIFER)){
if (stinfo.hasMoreTokens()){
//關(guān)鍵字后的第二段數(shù)據(jù)是客戶名信息
clientName = stinfo.nextToken();
}
if (stinfo.hasMoreTokens()){
//關(guān)鍵字后的第三段數(shù)據(jù)是客戶ip信息
clientIP = stinfo.nextToken();
}
System.out.println(head); //在控制臺(tái)打印頭信息
}
} catch (IOException e) {
System.out.println("Error:" + e);
}
}
/**
* 向客戶端發(fā)送消息
* @param msg
*/
public void send(StringBuffer msg) {
ps.println(msg);
ps.flush();
}
//線程運(yùn)行方法
public void run() {
while (running) {
String line = null;
try {
//讀取客戶端發(fā)來的數(shù)據(jù)流
line = br.readLine();
} catch (IOException e) {
System.out.println("Error" + e);
ChatServer.disconnect(this);
ChatServer.notifyRoomPeople();
return;
}
//客戶已離開
if (line == null){
ChatServer.disconnect(this);
ChatServer.notifyRoomPeople();
return;
}
StringTokenizer st = new StringTokenizer(line, Constants.SEPERATOR);
String keyword = st.nextToken();
// 如果關(guān)鍵字是MSG則是客戶端發(fā)來的聊天信息
if (keyword.equals(Constants.MSG_IDENTIFER)){
StringBuffer msg = new StringBuffer(Constants.MSG_IDENTIFER).append(Constants.SEPERATOR);
msg.append(clientName);
msg.append(st.nextToken("\0"));
// 再將某個(gè)客戶發(fā)來的聊天信息發(fā)送到每個(gè)連接客戶的聊天欄中
ChatServer.sendMsgToClients(msg);
} else if (keyword.equals(Constants.QUIT_IDENTIFER)) {
// 如果關(guān)鍵字是QUIT則是客戶端發(fā)來斷開連接的信息
// 服務(wù)器斷開與這個(gè)客戶的連接
ChatServer.disconnect(this);
// 繼續(xù)監(jiān)聽聊天室并刷新其他客戶的聊天人名list
ChatServer.notifyRoomPeople();
running = false;
}
}
}
public void toStop(){
running = false;
}
// 覆蓋Object類的equals方法
public boolean equals(Object obj){
if (obj instanceof ClientProcessor){
ClientProcessor obj1 = (ClientProcessor)obj;
if (obj1.clientIP.equals(this.clientIP)
(obj1.clientName.equals(this.clientName))){
return true;
}
}
return false;
}
// 覆蓋Object類的hashCode方法
public int hashCode(){
return (this.clientIP + Constants.SEPERATOR + this.clientName).hashCode();
}
}
package Chat;
/**
* 定義聊天室程序中用到的常量
*/
public class Constants {
// 服務(wù)器的端口號(hào)
public static final int SERVER_PORT = 2525;
public static final int MAX_CLIENT = 10;
// 消息標(biāo)識(shí)符與消息體之間的分隔符
public static final String SEPERATOR = ":";
// 消息信息的標(biāo)識(shí)符
public static final String MSG_IDENTIFER = "MSG";
// 用戶列表信息的標(biāo)識(shí)符
public static final String PEOPLE_IDENTIFER = "PEOPLE";
// 連接服務(wù)器信息的標(biāo)識(shí)符
public static final String CONNECT_IDENTIFER = "INFO";
// 退出信息標(biāo)識(shí)符
public static final String QUIT_IDENTIFER = "QUIT";
}
JAVA實(shí)現(xiàn)游戲記錄排行
把每次游戲的時(shí)間用IO流記錄到文件上、需要查看記錄排行時(shí)、讀取文件、排序、
掃描二維碼推送至手機(jī)訪問。
版權(quán)聲明:本文由信途科技轉(zhuǎn)載于網(wǎng)絡(luò),如有侵權(quán)聯(lián)系站長刪除。
轉(zhuǎn)載請注明出處http://macbookprostickers.com/xintu/119108.html