bl双性强迫侵犯h_国产在线观看人成激情视频_蜜芽188_被诱拐的少孩全彩啪啪漫画

java對(duì)戰(zhàn)五子棋代碼 java五子棋代碼

java五子棋代碼帶詳細(xì)解釋

浩大的工程 你有五子棋程序 如果你水平還行的話你參照這個(gè)聊天室程序應(yīng)該也比較容易寫出人人對(duì)戰(zhàn)的

施秉ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書未來(lái)市場(chǎng)廣闊!成為成都創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:13518219792(備注:SSL證書合作)期待與您的合作!

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("請(qǐng)輸入聊天信息");

//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類來(lái)讀取數(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);

}

/**

* 客戶端線程類用來(lái)監(jiān)聽服務(wù)器傳來(lái)的信息

*/

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ù)器傳來(lái)的信息

msg = br.readLine();

System.out.println("receive msg: " + msg);

} catch (IOException e) {

System.out.println("Error:" + e);

parent.disconnect();

}

// 如果從服務(wù)器傳來(lái)的信息為空則斷開此次連接

if (msg == null) {

parent.listener = null;

parent.soc = null;

parent.peopleList.removeAll();

running = false;

return;

}

//用StringTokenizer類來(lái)實(shí)現(xiàn)讀取分段字符

StringTokenizer st = new StringTokenizer(msg, Constants.SEPERATOR);

//讀取信息頭即關(guān)鍵字用來(lái)識(shí)別是何種信息

String keyword = st.nextToken();

if (keyword.equals(Constants.PEOPLE_IDENTIFER)) {

//如果是PEOPLE則是服務(wù)器發(fā)來(lái)的客戶連接信息

//主要用來(lái)刷新客戶端的用戶列表

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ù)器傳來(lái)的聊天信息,

//主要用來(lái)刷新客戶端聊天信息區(qū)將每個(gè)客戶的聊天內(nèi)容顯示出來(lá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)前處理客戶端請(qǐ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í)接受連接請(qǐng)求

if (clientProcessors.size() Constants.MAX_CLIENT) {

Socket socket = null;

try {

// 收到客戶端的請(qǐng)求

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 {

//如果客戶端超過(guò)了MAX_CLIENT個(gè),則等待一段時(shí)間再嘗試接受請(qǐng)求

try {

Thread.sleep(200);

} catch (InterruptedException e) {

}

}

}

}

}

/**

* 處理客戶端發(fā)送的請(qǐng)求的線程

*/

class ClientProcessor extends Thread {

//存儲(chǔ)一個(gè)連接客戶端的socket信息

Socket socket;

//存儲(chǔ)客戶端的連接姓名

String clientName;

//存儲(chǔ)客戶端的ip信息

String clientIP;

//用來(lái)實(shí)現(xiàn)接受從客戶端發(fā)來(lái)的數(shù)據(jù)流

BufferedReader br;

//用來(lái)實(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ā)來(lái)的數(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ā)來(lái)的聊天信息

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ā)來(lái)的聊天信息發(fā)送到每個(gè)連接客戶的聊天欄中

ChatServer.sendMsgToClients(msg);

} else if (keyword.equals(Constants.QUIT_IDENTIFER)) {

// 如果關(guān)鍵字是QUIT則是客戶端發(fā)來(lái)斷開連接的信息

// 服務(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做五子棋源代碼

java網(wǎng)絡(luò)五子棋

下面的源代碼分為4個(gè)文件;

chessClient.java:客戶端主程序。

chessInterface.java:客戶端的界面。

chessPad.java:棋盤的繪制。

chessServer.java:服務(wù)器端。

可同時(shí)容納50個(gè)人同時(shí)在線下棋,聊天。

沒(méi)有加上詳細(xì)注釋,不過(guò)絕對(duì)可以運(yùn)行,j2sdk1.4下通過(guò)。

/*********************************************************************************************

1.chessClient.java

**********************************************************************************************/

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

import java.util.*;

class clientThread extends Thread

{

chessClient chessclient;

clientThread(chessClient chessclient)

{

this.chessclient=chessclient;

}

public void acceptMessage(String recMessage)

{

if(recMessage.startsWith("/userlist "))

{

StringTokenizer userToken=new StringTokenizer(recMessage," ");

int userNumber=0;

chessclient.userpad.userList.removeAll();

chessclient.inputpad.userChoice.removeAll();

chessclient.inputpad.userChoice.addItem("所有人");

while(userToken.hasMoreTokens())

{

String user=(String)userToken.nextToken(" ");

if(userNumber0 !user.startsWith("[inchess]"))

{

chessclient.userpad.userList.add(user);

chessclient.inputpad.userChoice.addItem(user);

}

userNumber++;

}

chessclient.inputpad.userChoice.select("所有人");

}

else if(recMessage.startsWith("/yourname "))

{

chessclient.chessClientName=recMessage.substring(10);

chessclient.setTitle("Java五子棋客戶端 "+"用戶名:"+chessclient.chessClientName);

}

else if(recMessage.equals("/reject"))

{

try

{

chessclient.chesspad.statusText.setText("不能加入游戲");

chessclient.controlpad.cancelGameButton.setEnabled(false);

chessclient.controlpad.joinGameButton.setEnabled(true);

chessclient.controlpad.creatGameButton.setEnabled(true);

}

catch(Exception ef)

{

chessclient.chatpad.chatLineArea.setText("chessclient.chesspad.chessSocket.close無(wú)法關(guān)閉");

}

chessclient.controlpad.joinGameButton.setEnabled(true);

}

else if(recMessage.startsWith("/peer "))

{

chessclient.chesspad.chessPeerName=recMessage.substring(6);

if(chessclient.isServer)

{

chessclient.chesspad.chessColor=1;

chessclient.chesspad.isMouseEnabled=true;

chessclient.chesspad.statusText.setText("請(qǐng)黑棋下子");

}

else if(chessclient.isClient)

{

chessclient.chesspad.chessColor=-1;

chessclient.chesspad.statusText.setText("已加入游戲,等待對(duì)方下子...");

}

}

else if(recMessage.equals("/youwin"))

{

chessclient.isOnChess=false;

chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor);

chessclient.chesspad.statusText.setText("對(duì)方退出,請(qǐng)點(diǎn)放棄游戲退出連接");

chessclient.chesspad.isMouseEnabled=false;

}

else if(recMessage.equals("/OK"))

{

chessclient.chesspad.statusText.setText("創(chuàng)建游戲成功,等待別人加入...");

}

else if(recMessage.equals("/error"))

{

chessclient.chatpad.chatLineArea.append("傳輸錯(cuò)誤:請(qǐng)退出程序,重新加入 \n");

}

else

{

chessclient.chatpad.chatLineArea.append(recMessage+"\n");

chessclient.chatpad.chatLineArea.setCaretPosition(

chessclient.chatpad.chatLineArea.getText().length());

}

}

public void run()

{

String message="";

try

{

while(true)

{

message=chessclient.in.readUTF();

acceptMessage(message);

}

}

catch(IOException es)

{

}

}

}

public class chessClient extends Frame implements ActionListener,KeyListener

{

userPad userpad=new userPad();

chatPad chatpad=new chatPad();

controlPad controlpad=new controlPad();

chessPad chesspad=new chessPad();

inputPad inputpad=new inputPad();

Socket chatSocket;

DataInputStream in;

DataOutputStream out;

String chessClientName=null;

String host=null;

int port=4331;

boolean isOnChat=false; //在聊天?

boolean isOnChess=false; //在下棋?

boolean isGameConnected=false; //下棋的客戶端連接?

boolean isServer=false; //如果是下棋的主機(jī)

boolean isClient=false; //如果是下棋的客戶端

Panel southPanel=new Panel();

Panel northPanel=new Panel();

Panel centerPanel=new Panel();

Panel westPanel=new Panel();

Panel eastPanel=new Panel();

chessClient()

{

super("Java五子棋客戶端");

setLayout(new BorderLayout());

host=controlpad.inputIP.getText();

westPanel.setLayout(new BorderLayout());

westPanel.add(userpad,BorderLayout.NORTH);

westPanel.add(chatpad,BorderLayout.CENTER);

westPanel.setBackground(Color.pink);

inputpad.inputWords.addKeyListener(this);

chesspad.host=controlpad.inputIP.getText();

centerPanel.add(chesspad,BorderLayout.CENTER);

centerPanel.add(inputpad,BorderLayout.SOUTH);

centerPanel.setBackground(Color.pink);

controlpad.connectButton.addActionListener(this);

controlpad.creatGameButton.addActionListener(this);

controlpad.joinGameButton.addActionListener(this);

controlpad.cancelGameButton.addActionListener(this);

controlpad.exitGameButton.addActionListener(this);

controlpad.creatGameButton.setEnabled(false);

controlpad.joinGameButton.setEnabled(false);

controlpad.cancelGameButton.setEnabled(false);

southPanel.add(controlpad,BorderLayout.CENTER);

southPanel.setBackground(Color.pink);

addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent e)

{

if(isOnChat)

{

try

{

chatSocket.close();

}

catch(Exception ed)

{

}

}

if(isOnChess || isGameConnected)

{

try

{

chesspad.chessSocket.close();

}

catch(Exception ee)

{

}

}

System.exit(0);

}

public void windowActivated(WindowEvent ea)

{

}

});

add(westPanel,BorderLayout.WEST);

add(centerPanel,BorderLayout.CENTER);

add(southPanel,BorderLayout.SOUTH);

pack();

setSize(670,548);

setVisible(true);

setResizable(false);

validate();

}

public boolean connectServer(String serverIP,int serverPort) throws Exception

{

try

{

chatSocket=new Socket(serverIP,serverPort);

in=new DataInputStream(chatSocket.getInputStream());

out=new DataOutputStream(chatSocket.getOutputStream());

clientThread clientthread=new clientThread(this);

clientthread.start();

isOnChat=true;

return true;

}

catch(IOException ex)

{

chatpad.chatLineArea.setText("chessClient:connectServer:無(wú)法連接,建議重新啟動(dòng)程序 \n");

}

return false;

}

public void actionPerformed(ActionEvent e)

{

if(e.getSource()==controlpad.connectButton)

{

host=chesspad.host=controlpad.inputIP.getText();

try

{

if(connectServer(host,port))

{

chatpad.chatLineArea.setText("");

controlpad.connectButton.setEnabled(false);

controlpad.creatGameButton.setEnabled(true);

controlpad.joinGameButton.setEnabled(true);

chesspad.statusText.setText("連接成功,請(qǐng)創(chuàng)建游戲或加入游戲");

}

}

catch(Exception ei)

{

chatpad.chatLineArea.setText("controlpad.connectButton:無(wú)法連接,建議重新啟動(dòng)程序 \n");

}

}

if(e.getSource()==controlpad.exitGameButton)

{

if(isOnChat)

{

try

{

chatSocket.close();

}

catch(Exception ed)

{

}

}

if(isOnChess || isGameConnected)

{

try

{

chesspad.chessSocket.close();

}

catch(Exception ee)

{

}

}

System.exit(0);

}

if(e.getSource()==controlpad.joinGameButton)

{

String selectedUser=userpad.userList.getSelectedItem();

if(selectedUser==null || selectedUser.startsWith("[inchess]") ||

selectedUser.equals(chessClientName))

{

chesspad.statusText.setText("必須先選定一個(gè)有效用戶");

}

else

{

try

{

if(!isGameConnected)

{

if(chesspad.connectServer(chesspad.host,chesspad.port))

{

isGameConnected=true;

isOnChess=true;

isClient=true;

controlpad.creatGameButton.setEnabled(false);

controlpad.joinGameButton.setEnabled(false);

controlpad.cancelGameButton.setEnabled(true);

chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName);

}

}

else

{

isOnChess=true;

isClient=true;

controlpad.creatGameButton.setEnabled(false);

controlpad.joinGameButton.setEnabled(false);

controlpad.cancelGameButton.setEnabled(true);

chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName);

}

}

catch(Exception ee)

{

isGameConnected=false;

isOnChess=false;

isClient=false;

controlpad.creatGameButton.setEnabled(true);

controlpad.joinGameButton.setEnabled(true);

controlpad.cancelGameButton.setEnabled(false);

chatpad.chatLineArea.setText("chesspad.connectServer無(wú)法連接 \n"+ee);

}

}

}

if(e.getSource()==controlpad.creatGameButton)

{

try

{

if(!isGameConnected)

{

if(chesspad.connectServer(chesspad.host,chesspad.port))

{

isGameConnected=true;

isOnChess=true;

isServer=true;

controlpad.creatGameButton.setEnabled(false);

controlpad.joinGameButton.setEnabled(false);

controlpad.cancelGameButton.setEnabled(true);

chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName);

}

}

else

{

isOnChess=true;

isServer=true;

controlpad.creatGameButton.setEnabled(false);

controlpad.joinGameButton.setEnabled(false);

controlpad.cancelGameButton.setEnabled(true);

chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName);

}

}

catch(Exception ec)

{

isGameConnected=false;

isOnChess=false;

isServer=false;

controlpad.creatGameButton.setEnabled(true);

controlpad.joinGameButton.setEnabled(true);

controlpad.cancelGameButton.setEnabled(false);

ec.printStackTrace();

chatpad.chatLineArea.setText("chesspad.connectServer無(wú)法連接 \n"+ec);

}

}

if(e.getSource()==controlpad.cancelGameButton)

{

if(isOnChess)

{

chesspad.chessthread.sendMessage("/giveup "+chessClientName);

chesspad.chessVictory(-1*chesspad.chessColor);

controlpad.creatGameButton.setEnabled(true);

controlpad.joinGameButton.setEnabled(true);

controlpad.cancelGameButton.setEnabled(false);

chesspad.statusText.setText("請(qǐng)建立游戲或者加入游戲");

}

if(!isOnChess)

{

controlpad.creatGameButton.setEnabled(true);

controlpad.joinGameButton.setEnabled(true);

controlpad.cancelGameButton.setEnabled(false);

chesspad.statusText.setText("請(qǐng)建立游戲或者加入游戲");

}

isClient=isServer=false;

}

}

public void keyPressed(KeyEvent e)

{

TextField inputWords=(TextField)e.getSource();

if(e.getKeyCode()==KeyEvent.VK_ENTER)

{

if(inputpad.userChoice.getSelectedItem().equals("所有人"))

{

try

{

out.writeUTF(inputWords.getText());

inputWords.setText("");

}

catch(Exception ea)

{

chatpad.chatLineArea.setText("chessClient:KeyPressed無(wú)法連接,建議重新連接 \n");

userpad.userList.removeAll();

inputpad.userChoice.removeAll();

inputWords.setText("");

controlpad.connectButton.setEnabled(true);

}

}

else

{

try

{

out.writeUTF("/"+inputpad.userChoice.getSelectedItem()+" "+inputWords.getText());

inputWords.setText("");

}

catch(Exception ea)

{

chatpad.chatLineArea.setText("chessClient:KeyPressed無(wú)法連接,建議重新連接 \n");

userpad.userList.removeAll();

inputpad.userChoice.removeAll();

inputWords.setText("");

controlpad.connectButton.setEnabled(true);

}

}

}

}

public void keyTyped(KeyEvent e)

{

}

public void keyReleased(KeyEvent e)

{

}

public static void main(String args[])

{

chessClient chessClient=new chessClient();

}

}

/******************************************************************************************

下面是:chessInteface.java

******************************************************************************************/

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

class userPad extends Panel

{

List userList=new List(10);

userPad()

{

setLayout(new BorderLayout());

for(int i=0;i50;i++)

{

userList.add(i+"."+"沒(méi)有用戶");

}

add(userList,BorderLayout.CENTER);

}

}

class chatPad extends Panel

{

TextArea chatLineArea=new TextArea("",18,30,TextArea.SCROLLBARS_VERTICAL_ONLY);

chatPad()

{

setLayout(new BorderLayout());

add(chatLineArea,BorderLayout.CENTER);

}

}

class controlPad extends Panel

{

Label IPlabel=new Label("IP",Label.LEFT);

TextField inputIP=new TextField("localhost",10);

Button connectButton=new Button("連接主機(jī)");

Button creatGameButton=new Button("建立游戲");

Button joinGameButton=new Button("加入游戲");

Button cancelGameButton=new Button("放棄游戲");

Button exitGameButton=new Button("關(guān)閉程序");

controlPad()

{

setLayout(new FlowLayout(FlowLayout.LEFT));

setBackground(Color.pink);

add(IPlabel);

add(inputIP);

add(connectButton);

add(creatGameButton);

add(joinGameButton);

add(cancelGameButton);

add(exitGameButton);

}

}

class inputPad extends Panel

{

TextField inputWords=new TextField("",40);

Choice userChoice=new Choice();

inputPad()

{

setLayout(new FlowLayout(FlowLayout.LEFT));

for(int i=0;i50;i++)

{

userChoice.addItem(i+"."+"沒(méi)有用戶");

}

userChoice.setSize(60,24);

add(userChoice);

add(inputWords);

}

}

/**********************************************************************************************

下面是:chessPad.java

**********************************************************************************************/

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

import java.util.*;

class chessThread extends Thread

{

chessPad chesspad;

chessThread(chessPad chesspad)

{

this.chesspad=chesspad;

}

public void sendMessage(String sndMessage)

{

try

{

chesspad.outData.writeUTF(sndMessage);

}

catch(Exception ea)

{

System.out.println("chessThread.sendMessage:"+ea);

}

}

public void acceptMessage(String recMessage)

{

if(recMessage.startsWith("/chess "))

{

StringTokenizer userToken=new StringTokenizer(recMessage," ");

String chessToken;

String[] chessOpt={"-1","-1","0"};

int chessOptNum=0;

while(userToken.hasMoreTokens())

{

chessToken=(String)userToken.nextToken(" ");

if(chessOptNum=1 chessOptNum=3)

{

chessOpt[chessOptNum-1]=chessToken;

}

chessOptNum++;

}

chesspad.netChessPaint(Integer.parseInt(chessOpt[0]),Integer.parseInt(chessOpt[1]),Integer.parseInt(chessOpt[2]));

}

else if(recMessage.startsWith("/yourname "))

{

chesspad.chessSelfName=recMessage.substring(10);

}

else if(recMessage.equals("/error"))

{

chesspad.statusText.setText("錯(cuò)誤:沒(méi)有這個(gè)用戶,請(qǐng)退出程序,重新加入");

}

else

{

//System.out.println(recMessage);

}

}

public void run()

{

String message="";

try

{

while(true)

{

message=chesspad.inData.readUTF();

acceptMessage(message);

}

}

catch(IOException es)

{

}

}

}

class chessPad extends Panel implements MouseListener,ActionListener

{

int chessPoint_x=-1,chessPoint_y=-1,chessColor=1;

int chessBlack_x[]=new int[200];

int chessBlack_y[]=new int[200];

int chessWhite_x[]=new int[200];

int chessWhite_y[]=new int[200];

int chessBlackCount=0,chessWhiteCount=0;

int chessBlackWin=0,chessWhiteWin=0;

boolean isMouseEnabled=false,isWin=false,isInGame=false;

TextField statusText=new TextField("請(qǐng)先連接服務(wù)器");

Socket chessSocket;

DataInputStream inData;

DataOutputStream outData;

String chessSelfName=null;

String chessPeerName=null;

String host=null;

int port=4331;

chessThread chessthread=new chessThread(this);

chessPad()

{

setSize(440,440);

setLayout(null);

setBackground(Color.pink);

addMouseListener(this);

add(statusText);

statusText.setBounds(40,5,360,24);

statusText.setEditable(false);

}

public boolean connectServer(String ServerIP,int ServerPort) throws Exception

{

try

{

chessSocket=new Socket(ServerIP,ServerPort);

inData=new DataInputStream(chessSocket.getInputStream());

outData=new DataOutputStream(chessSocket.getOutputStream());

chessthread.start();

return true;

}

catch(IOException ex)

{

statusText.setText("chessPad:connectServer:無(wú)法連接 \n");

}

return false;

}

public void chessVictory(int chessColorWin)

{

this.removeAll();

for(int i=0;i=chessBlackCount;i++)

{

chessBlack_x[i]=0;

chessBlack_y[i]=0;

}

for(int i=0;i=chessWhiteCount;i++)

{

chessWhite_x[i]=0;

chessWhite_y[i]=0;

}

chessBlackCount=0;

chessWhiteCount=0;

add(statusText);

statusText.setBounds(40,5,360,24);

if(chessColorWin==1)

{ chessBlackWin++;

statusText.setText("黑棋勝,黑:白為"+chessBlackWin+":"+chessWhiteWin+",重新開局,等待白棋下子...");

}

else if(chessColorWin==-1)

{

chessWhiteWin++;

statusText.setText("白棋勝,黑:白為"+chessBlackWin+":"+chessWhiteWin+",重新開局,等待黑棋下子...");

}

}

public void getLocation(int a,int b,int color)

{

if(color==1)

{

chessBlack_x[chessBlackCount]=a*20;

chessBlack_y[chessBlackCount]=b*20;

chessBlackCount++;

}

else if(color==-1)

{

chessWhite_x[chessWhiteCount]=a*20;

chessWhite_y[chessWhiteCount]=b*20;

chessWhiteCount++;

}

}

public boolean checkWin(int a,int b,int checkColor)

{

int step=1,chessLink=1,chessLinkTest=1,chessCompare=0;

if(checkColor==1)

{

chessLink=1;

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if(((a+step)*20==chessBlack_x[chessCompare]) ((b*20)==chessBlack_y[chessCompare]))

{

chessLink=chessLink+1;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if(((a-step)*20==chessBlack_x[chessCompare]) (b*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

chessLink=1;

chessLinkTest=1;

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if((a*20==chessBlack_x[chessCompare]) ((b+step)*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if((a*20==chessBlack_x[chessCompare]) ((b-step)*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

chessLink=1;

chessLinkTest=1;

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if(((a-step)*20==chessBlack_x[chessCompare]) ((b+step)*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if(((a+step)*20==chessBlack_x[chessCompare]) ((b-step)*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

chessLink=1;

chessLinkTest=1;

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if(((a+step)*20==chessBlack_x[chessCompare]) ((b+step)*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if(((a-step)*20==chessBlack_x[chessCompare]) ((b-step)*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

求java五子棋代碼要注釋~現(xiàn)在1小時(shí)等待

package org.crazyit.gobang;

import java.io.BufferedReader;

import java.io.InputStreamReader;

/**

* 五子棋游戲類

*

* @author yangenxiong yangenxiong2009@gmail.com

* @author Kelvin Mak kelvin.mak125@gmail.com

* @version 1.0

* br/網(wǎng)站: a href=""瘋狂Java聯(lián)盟/a

* brCopyright (C), 2009-2010, yangenxiong

* brThis program is protected by copyright laws.

*/

public class GobangGame {

// 定義達(dá)到贏條件的棋子數(shù)目

private final int WIN_COUNT = 5;

// 定義用戶輸入的X坐標(biāo)

private int posX = 0;

// 定義用戶輸入的X坐標(biāo)

private int posY = 0;

// 定義棋盤

private Chessboard chessboard;

/**

* 空構(gòu)造器

*/

public GobangGame() {

}

/**

* 構(gòu)造器,初始化棋盤和棋子屬性

*

* @param chessboard

* 棋盤類

*/

public GobangGame(Chessboard chessboard) {

this.chessboard = chessboard;

}

/**

* 檢查輸入是否合法。

*

* @param inputStr

* 由控制臺(tái)輸入的字符串。

* @return 字符串合法返回true,反則返回false。

*/

public boolean isValid(String inputStr) {

// 將用戶輸入的字符串以逗號(hào)(,)作為分隔,分隔成兩個(gè)字符串

String[] posStrArr = inputStr.split(",");

try {

posX = Integer.parseInt(posStrArr[0]) - 1;

posY = Integer.parseInt(posStrArr[1]) - 1;

} catch (NumberFormatException e) {

chessboard.printBoard();

System.out.println("請(qǐng)以(數(shù)字,數(shù)字)的格式輸入:");

return false;

}

// 檢查輸入數(shù)值是否在范圍之內(nèi)

if (posX 0 || posX = Chessboard.BOARD_SIZE || posY 0

|| posY = Chessboard.BOARD_SIZE) {

chessboard.printBoard();

System.out.println("X與Y坐標(biāo)只能大于等于1,與小于等于" + Chessboard.BOARD_SIZE

+ ",請(qǐng)重新輸入:");

return false;

}

// 檢查輸入的位置是否已經(jīng)有棋子

String[][] board = chessboard.getBoard();

if (board[posX][posY] != "十") {

chessboard.printBoard();

System.out.println("此位置已經(jīng)有棋子,請(qǐng)重新輸入:");

return false;

}

return true;

}

/**

* 開始下棋

*/

public void start() throws Exception {

// true為游戲結(jié)束

boolean isOver = false;

chessboard.initBoard();

chessboard.printBoard();

// 獲取鍵盤的輸入

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String inputStr = null;

// br.readLine:每當(dāng)鍵盤輸入一行內(nèi)容按回車鍵,則輸入的內(nèi)容被br讀取到

while ((inputStr = br.readLine()) != null) {

isOver = false;

if (!isValid(inputStr)) {

// 如果不合法,要求重新輸入,再繼續(xù)

continue;

}

// 把對(duì)應(yīng)的數(shù)組元素賦為"●"

String chessman = Chessman.BLACK.getChessman();

chessboard.setBoard(posX, posY, chessman);

// 判斷用戶是否贏了

if (isWon(posX, posY, chessman)) {

isOver = true;

} else {

// 計(jì)算機(jī)隨機(jī)選擇位置坐標(biāo)

int[] computerPosArr = computerDo();

chessman = Chessman.WHITE.getChessman();

chessboard.setBoard(computerPosArr[0], computerPosArr[1],

chessman);

// 判斷計(jì)算機(jī)是否贏了

if (isWon(computerPosArr[0], computerPosArr[1], chessman)) {

isOver = true;

}

}

// 如果產(chǎn)生勝者,詢問(wèn)用戶是否繼續(xù)游戲

if (isOver) {

// 如果繼續(xù),重新初始化棋盤,繼續(xù)游戲

if (isReplay(chessman)) {

chessboard.initBoard();

chessboard.printBoard();

continue;

}

// 如果不繼續(xù),退出程序

break;

}

chessboard.printBoard();

System.out.println("請(qǐng)輸入您下棋的坐標(biāo),應(yīng)以x,y的格式輸入:");

}

}

/**

* 是否重新開始下棋。

*

* @param chessman

* "●"為用戶,"○"為計(jì)算機(jī)。

* @return 開始返回true,反則返回false。

*/

public boolean isReplay(String chessman) throws Exception {

chessboard.printBoard();

String message = chessman.equals(Chessman.BLACK.getChessman()) ? "恭喜您,您贏了,"

: "很遺憾,您輸了,";

System.out.println(message + "再下一局?(y/n)");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

if (br.readLine().equals("y")) {

// 開始新一局

return true;

}

return false;

}

/**

* 計(jì)算機(jī)隨機(jī)下棋

*/

public int[] computerDo() {

int posX = (int) (Math.random() * (Chessboard.BOARD_SIZE - 1));

int posY = (int) (Math.random() * (Chessboard.BOARD_SIZE - 1));

String[][] board = chessboard.getBoard();

while (board[posX][posY] != "十") {

posX = (int) (Math.random() * (Chessboard.BOARD_SIZE - 1));

posY = (int) (Math.random() * (Chessboard.BOARD_SIZE - 1));

}

int[] result = { posX, posY };

return result;

}

/**

* 判斷輸贏

*

* @param posX

* 棋子的X坐標(biāo)。

* @param posY

* 棋子的Y坐標(biāo)

* @param ico

* 棋子類型

* @return 如果有五顆相鄰棋子連成一條直接,返回真,否則相反。

*/

public boolean isWon(int posX, int posY, String ico) {

// 直線起點(diǎn)的X坐標(biāo)

int startX = 0;

// 直線起點(diǎn)Y坐標(biāo)

int startY = 0;

// 直線結(jié)束X坐標(biāo)

int endX = Chessboard.BOARD_SIZE - 1;

// 直線結(jié)束Y坐標(biāo)

int endY = endX;

// 同條直線上相鄰棋子累積數(shù)

int sameCount = 0;

int temp = 0;

// 計(jì)算起點(diǎn)的最小X坐標(biāo)與Y坐標(biāo)

temp = posX - WIN_COUNT + 1;

startX = temp 0 ? 0 : temp;

temp = posY - WIN_COUNT + 1;

startY = temp 0 ? 0 : temp;

// 計(jì)算終點(diǎn)的最大X坐標(biāo)與Y坐標(biāo)

temp = posX + WIN_COUNT - 1;

endX = temp Chessboard.BOARD_SIZE - 1 ? Chessboard.BOARD_SIZE - 1

: temp;

temp = posY + WIN_COUNT - 1;

endY = temp Chessboard.BOARD_SIZE - 1 ? Chessboard.BOARD_SIZE - 1

: temp;

// 從左到右方向計(jì)算相同相鄰棋子的數(shù)目

String[][] board = chessboard.getBoard();

for (int i = startY; i endY; i++) {

if (board[posX][i] == ico board[posX][i + 1] == ico) {

sameCount++;

} else if (sameCount != WIN_COUNT - 1) {

sameCount = 0;

}

}

if (sameCount == 0) {

// 從上到下計(jì)算相同相鄰棋子的數(shù)目

for (int i = startX; i endX; i++) {

if (board[i][posY] == ico board[i + 1][posY] == ico) {

sameCount++;

} else if (sameCount != WIN_COUNT - 1) {

sameCount = 0;

}

}

}

if (sameCount == 0) {

// 從左上到右下計(jì)算相同相鄰棋子的數(shù)目

int j = startY;

for (int i = startX; i endX; i++) {

if (j endY) {

if (board[i][j] == ico board[i + 1][j + 1] == ico) {

sameCount++;

} else if (sameCount != WIN_COUNT - 1) {

sameCount = 0;

}

j++;

}

}

}

return sameCount == WIN_COUNT - 1 ? true : false;

}

public static void main(String[] args) throws Exception {

GobangGame gb = new GobangGame(new Chessboard());

gb.start();

}

}

求一個(gè)簡(jiǎn)單的JAVA五子棋代碼!! 網(wǎng)上復(fù)制的別來(lái)了!

以下是現(xiàn)寫的 實(shí)現(xiàn)了兩人對(duì)戰(zhàn) 自己復(fù)制后運(yùn)行把 沒(méi)什么難度 類名 Games

import java.util.Scanner;

public class Games {

private String board[][];

private static int SIZE = 17;

private static String roles = "A玩家";

//初始化數(shù)組

public void initBoard() {

board = new String[SIZE][SIZE];

for (int i = 0; i SIZE; i++) {

for (int j = 0; j SIZE; j++) {

// if(i==0){

// String str = "";

// str += j+" ";

// board[i][j]= str;

// }else if(i!=0j==0){

// String str = "";

// str += i+" ";

// board[i][j]= str;

// }else{

board[i][j] = "╋";

// }

}

}

}

//輸出棋盤

public void printBoard() {

for (int i = 0; i SIZE; i++) {

for (int j = 0; j SIZE; j++) {

System.out.print(board[i][j]);

}

System.out.println();

}

}

//判斷所下棋子位置是否合理

public boolean isOk(int x, int y) {

boolean isRight = true;

if (x = 16 || x 1 || y = 16 | y 1) {

//System.out.println("輸入錯(cuò)誤,請(qǐng)從新輸入");

isRight = false;

}

if (board[x][y].equals("●") || board[x][y].equals("○")) {

isRight = false;

}

return isRight;

}

//判斷誰(shuí)贏了

public void whoWin(Games wz) {

// 從數(shù)組挨個(gè)查找找到某個(gè)類型的棋子就從該棋子位置向右,向下,斜向右下 各查找5連續(xù)的位置看是否為5個(gè)相同的

int xlabel;// 記錄第一次找到某個(gè)棋子的x坐標(biāo)

int ylabel;// 記錄第一次找到某個(gè)棋子的y坐標(biāo)

// ●○╋

// 判斷人是否贏了

for (int i = 0; i SIZE; i++) {

for (int j = 0; j SIZE; j++) {

if (board[i][j].equals("○")) {

xlabel = i;

ylabel = j;

// 橫向找 x坐標(biāo)不變 y坐標(biāo)以此加1連成字符串

String heng = "";

if (i + 5 SIZE j + 5 SIZE) {

for (int k = j; k j + 5; k++) {

heng += board[i][k];

}

if (heng.equals("○○○○○")) {

System.out.println(roles+"贏了!您輸了!");

System.exit(0);

}

// 向下判斷y不變 x逐增5 連成字符串

String xia = "";

for (int l = j; l i + 5; l++) {

xia += board[l][j];

// System.out.println(xia);

}

if (xia.equals("○○○○○")) {

System.out.println(roles+"贏了!您輸了!");

System.exit(0);

}

// 斜向右下判斷

String youxia = "";

for (int a = 1; a = 5; a++) {

youxia += board[xlabel++][ylabel++];

}

if (youxia.equals("○○○○○")) {

System.out.println(roles+"贏了!您輸了!");

System.exit(0);

}

}

}

}

}

// 判斷電腦是否贏了

for (int i = 0; i SIZE; i++) {

for (int j = 0; j SIZE; j++) {

if (board[i][j].equals("●")) {

xlabel = i;

ylabel = j;

// 橫向找 x坐標(biāo)不變 y坐標(biāo)以此加1連成字符串

String heng = "";

if (j + 5 SIZE i + 5 SIZE) {

for (int k = j; k j + 5; k++) {

heng += board[i][k];

}

if (heng.equals("●●●●●")) {

System.out.println(roles+"贏輸了!您輸了!");

System.exit(0);

}

// 向下判斷y不變 x逐增5 連成字符串

String xia = "";

for (int l = i; l i + 5; l++) {

xia += board[l][ylabel];

// System.out.println(xia);

}

if (xia.equals("●●●●●")) {

System.out.println(roles+"贏了!您輸了!");

System.exit(0);

}

// 斜向右下判斷

String youxia = "";

for (int a = 1; a = 5; a++) {

youxia += board[xlabel++][ylabel++];

}

if (youxia.equals("●●●●●")) {

System.out.println(roles+"贏了!您輸了!");

System.exit(0);

}

}

}

}

}

}

public static void main(String[] args) {

Games wz = new Games();

Scanner sc = new Scanner(System.in);

wz.initBoard();

wz.printBoard();

while (true) {

System.out.print("請(qǐng)"+roles+"輸入X,Y坐標(biāo),必須在0-15范圍內(nèi),xy以空格隔開,輸入16 16結(jié)束程序");

int x = sc.nextInt();

int y = sc.nextInt();

if (x == SIZE y == SIZE) {

System.out.println("程序結(jié)束");

System.exit(0);

}

if (x SIZE || x 0 || y SIZE | y 0) {

System.out.println("輸入錯(cuò)誤,請(qǐng)從新輸入");

continue;

}

//如果roles是A玩家 就讓A玩家下棋,否則就讓B玩家下棋。

if (wz.board[x][y].equals("╋")roles.equals("A玩家")) {

wz.board[x][y] = "○";

wz.printBoard();

//判斷輸贏

wz.whoWin(wz);

}else if(wz.board[x][y].equals("╋")roles.equals("B玩家")){

wz.board[x][y] = "●";

wz.printBoard();

//判斷輸贏

wz.whoWin(wz);

} else {

System.out.println("此處已經(jīng)有棋子,從新輸入");

continue;

}

if(roles.equals("A玩家")){

roles = "B玩家";

}else if(roles.equals("B玩家")){

roles = "A玩家";

}

}

}

}

網(wǎng)站標(biāo)題:java對(duì)戰(zhàn)五子棋代碼 java五子棋代碼
文章轉(zhuǎn)載:http://vcdvsql.cn/article28/ddoiccp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作網(wǎng)站導(dǎo)航服務(wù)器托管網(wǎng)站制作營(yíng)銷型網(wǎng)站建設(shè)手機(jī)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)