導航:首頁 > 編程大全 > java網路五子棋代碼

java網路五子棋代碼

發布時間:2023-06-26 13:19:33

㈠ 跪求java五子棋源代碼

很sb的電腦五子棋:
import java.io.*;
import java.util.*;

public class Gobang {
// 定義一個二維數組來充當棋盤
private String[][] board;
// 定義棋盤的大小
private static int BOARD_SIZE = 15;

public void initBoard() {
// 初始化棋盤數組
board = new String[BOARD_SIZE][BOARD_SIZE];
// 把每個元素賦為"╋",用於在控制台畫出棋盤
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
// windows是一行一行來列印的。坐標值為(行值, 列值)
board[i][j] = "╋";
}
}
}

// 在控制台輸出棋盤的方法
public void printBoard() {
// 列印每個數組元素
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
// 列印數組元素後不換行
System.out.print(board[i][j]);
}
// 每列印完一行數組元素後輸出一個換行符
System.out.print("\n");
}
}

// 該方法處理電腦下棋:隨機生成2個整數,作為電腦下棋的坐標,賦給board數組。
private void compPlay() {
// 構造一個隨機數生成器
Random rnd = new Random();
// Random類的nextInt(int n))方法:隨機地生成並返回指定范圍中的一個 int 值,
// 即:在此隨機數生成器序列中 0(包括)和 n(不包括)之間均勻分布的一個int值。
int compXPos = rnd.nextInt(15);
int compYPos = rnd.nextInt(15);
// 保證電腦下的棋的坐標上不能已經有棋子(通過判斷對應數組元素只能是"╋"來確定)
while (board[compXPos][compYPos].equals("╋") == false) {
compXPos = rnd.nextInt(15);
compYPos = rnd.nextInt(15);
}
System.out.println(compXPos);
System.out.println(compYPos);
// 把對應的數組元素賦為"○"。
board[compXPos][compYPos] = "○";
}

// 該方法用於判斷勝負:進行四次循環掃描,判斷橫、豎、左斜、右斜是否有5個棋連在一起
private boolean judgeWin() {
// flag表示是否可以斷定贏/輸
boolean flag = false;
// joinEle:將每一個橫/豎/左斜/右斜行中的元素連接起來得到的一個字元串
String joinEle;
// 進行橫行掃描
for (int i = 0; i < BOARD_SIZE; i++) {
// 每掃描一行前,將joinEle清空
joinEle = "";
for (int j = 0; j < BOARD_SIZE; j++) {
joinEle += board[i][j];
}
// String類的contains方法:當且僅當該字元串包含指定的字元序列時,返回true。
if (joinEle.contains("●●●●●")) {
System.out.println("您贏啦!");
flag = true;
// 停止往下繼續執行,提前返回flag。
// 如果執行了這個return,就直接返回該方法的調用處;
// 不會再執行後面的任何語句,包括最後那個return語句。
// (而break僅僅是完全跳出這個for循環,還會繼續執行下面的for循環。)
return flag;
} else if (joinEle.contains("○○○○○")) {
System.out.println("您輸啦!");
flag = true;
// 提前返回flag
return flag;
}
}
// 進行豎行掃描
for (int i = 0; i < BOARD_SIZE; i++) {
joinEle = "";
for (int j = 0; j < BOARD_SIZE; j++) {
// 豎行的元素是它們的列值相同
joinEle += board[j][i];
}
if (joinEle.contains("●●●●●")) {
System.out.println("您贏啦!");
flag = true;
return flag;
} else if (joinEle.contains("○○○○○")) {
System.out.println("您輸啦!");
flag = true;
return flag;
}
}
// 進行左斜行掃描
for (int i = -(BOARD_SIZE - 2); i < BOARD_SIZE - 1; i++) {
joinEle = "";
for (int j = 0; j < BOARD_SIZE; j++) {
int line = i + j;
// 只截取坐標值沒有越界的點
if (line >= 0 && line < 15) {
joinEle += board[j][line];
}
}
if (joinEle.contains("●●●●●")) {
System.out.println("您贏啦!");
flag = true;
return flag;
} else if (joinEle.contains("○○○○○")) {
System.out.println("您輸啦!");
flag = true;
return flag;
}
}
// 進行右斜行掃描
for (int i = 1; i < 2 * (BOARD_SIZE - 1); i++) {
joinEle = "";
for (int j = 0; j < BOARD_SIZE; j++) {
int line = i - j;
if (line >= 0 && line < 15) {
joinEle += board[j][line];
}
}
if (joinEle.contains("●●●●●")) {
System.out.println("您贏啦!");
flag = true;
return flag;
} else if (joinEle.contains("○○○○○")) {
System.out.println("您輸啦!");
flag = true;
// 最後這個return可省略
}
}
// 確保該方法有返回值(如果上面條件都不滿足時)
return flag;
}

public static void main(String[] args) throws Exception, IOException {
Gobang gb = new Gobang();
gb.initBoard();
gb.printBoard();
// BufferedReader類:帶緩存的讀取器————從字元輸入流中讀取文本,並緩存字元。可用於高效讀取字元、數組和行。
// 最好用它來包裝所有其 read() 操作可能開銷很高的 Reader(如 FileReader 和 InputStreamReader)。
// 下面構造一個讀取器對象。
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 定義輸入字元串
String inputStr = null;
// br.readLine():每當在鍵盤上輸入一行內容按回車,剛輸入的內容將被br(讀取器對象)讀取到。
// BufferedReader類的readLine方法:讀取一個文本行。
// 初始狀態由於無任何輸入,br.readLine()會拋出異常。因而main方法要捕捉異常。
while ((inputStr = br.readLine()) != null) {
// 將用戶輸入的字元串以逗號(,)作為分隔符,分隔成2個字元串。
// String類的split方法,將會返回一個拆分後的字元串數組。
String[] posStrArr = inputStr.split(",");
// 將2個字元串轉換成用戶下棋的坐標
int xPos = Integer.parseInt(posStrArr[0]);
int yPos = Integer.parseInt(posStrArr[1]);
// 校驗用戶下棋坐標的有效性,只能是數字,不能超出棋盤范圍
if (xPos > 15 || xPos < 1 || yPos > 15 || yPos < 1) {
System.out.println("您下棋的坐標值應在1到15之間,請重新輸入!");
continue;
}
// 保證用戶下的棋的坐標上不能已經有棋子(通過判斷對應數組元素只能是"╋"來確定)
// String類的equals方法:比較字元串和指定對象是否相等。結果返回true或false。
if (gb.board[xPos - 1][yPos - 1].equals("╋")) {
// 把對應的數組元素賦為"●"。
gb.board[xPos - 1][yPos - 1] = "●";
} else {
System.out.println("您下棋的點已有棋子,請重新輸入!");
continue;
}
// 電腦下棋
gb.compPlay();
gb.printBoard();
// 每次下棋後,看是否可以斷定贏/輸了
if (gb.judgeWin() == false) {
System.out.println("請輸入您下棋的坐標,應以x,y的格式:");
} else {
// 完全跳出這個while循環,結束下棋
break;
}
}
}
}

㈡ 用JAVA做五子棋源代碼

java網路五子棋

下面的源代碼分為4個文件
chessClient.java:客戶端主程序
chessInterface.java:客戶端的界面。
chessPad.java:棋盤的繪制。
chessServer.java:伺服器端。
可同時容納50個人同時在線下棋,聊天。
沒有加上詳細注釋,不過絕對可以運行,j2sdk1.4下通過。

/*********************************************************************************************
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(userNumber>0 && !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無法關閉");
}
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("請黑棋下子");
}
else if(chessclient.isClient)
{
chessclient.chesspad.chessColor=-1;
chessclient.chesspad.statusText.setText("已加入游戲,等待對方下子...");
}

}
else if(recMessage.equals("/youwin"))
{
chessclient.isOnChess=false;
chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor);
chessclient.chesspad.statusText.setText("對方退出,請點放棄游戲退出連接");
chessclient.chesspad.isMouseEnabled=false;
}
else if(recMessage.equals("/OK"))
{
chessclient.chesspad.statusText.setText("創建游戲成功,等待別人加入...");
}
else if(recMessage.equals("/error"))
{
chessclient.chatpad.chatLineArea.append("傳輸錯誤:請退出程序,重新加入 \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; //如果是下棋的主機
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:無法連接,建議重新啟動程序 \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("連接成功,請創建游戲或加入游戲");
}

}
catch(Exception ei)
{
chatpad.chatLineArea.setText("controlpad.connectButton:無法連接,建議重新啟動程序 \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("必須先選定一個有效用戶");
}
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無法連接 \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無法連接 \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("請建立游戲或者加入游戲");
}
if(!isOnChess)
{
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chesspad.statusText.setText("請建立游戲或者加入游戲");
}
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無法連接,建議重新連接 \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無法連接,建議重新連接 \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;i<50;i++)
{
userList.add(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("連接主機");
Button creatGameButton=new Button("建立游戲");
Button joinGameButton=new Button("加入游戲");
Button cancelGameButton=new Button("放棄游戲");
Button exitGameButton=new Button("關閉程序");

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;i<50;i++)
{
userChoice.addItem(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("錯誤:沒有這個用戶,請退出程序,重新加入");
}
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("請先連接伺服器");

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:無法連接 \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五子棋代碼帶詳細解釋

浩大的工程 你有五子棋程序 如果你水平還行的話你參照這個聊天室程序應該也比較容易寫出人人對戰的
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{

// 登陸聊天室的名字標簽和輸入框
JLabel nameLabel = new JLabel();
JTextField nameTextField = new JTextField(15);

// 連接和斷開連接的按鈕
JButton connectButton = new JButton();
JButton disConnectButton = new JButton();

// 聊天室內容的文本域
JTextArea chatContentTextArea = new JTextArea(9, 30);

// 發送消息的按鈕
JButton sendMsgButton = new JButton();
// 消息輸入框
JTextField msgTextField = new JTextField(20);
JLabel msglabel = new JLabel();
// 聊天室用戶列表
java.awt.List peopleList = new java.awt.List(10);

/*以下定義數據流和網路變數*/
Socket soc = null;
PrintStream ps = null;

// 客戶端偵聽伺服器消息的線程
ClentListener listener = null;

public ChatClient() {
init();
}

// 初始化圖形界面
public void init() {

this.setTitle("聊天室客戶端");

// 初始化按鈕和標簽
nameLabel.setText("姓名:");
connectButton.setText("連 接");
connectButton.addActionListener(this);
disConnectButton.setText("斷 開");
disConnectButton.addActionListener(this);
// 設置聊天內容不可編輯
chatContentTextArea.setEditable(false);
sendMsgButton.setText("發 送");
sendMsgButton.addActionListener(this);
msgTextField.setText("請輸入聊天信息");

//panel1放置輸入姓名和連接兩個按鈕
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)), "聊天內容"));
panel2.add(pane1);
JScrollPane pane2 = new JScrollPane(peopleList);
pane2.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(134, 134, 134)), "用戶列表"));
panel2.add(pane2);

//用於放置發送信息區域
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();
}
}

/**
* 關閉聊天室客戶端事件
*/
protected void processWindowEvent(WindowEvent e){
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
// 如果是關閉聊天室客戶端,則斷開連接
disconnect();
dispose();
System.exit(0);
}
}

/**
* 處理按鈕事件
*/
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == connectButton){
// 如果點擊連接按鈕
if (soc == null) {
try {
// 使用埠2525實例化一個本地套接字
soc = new Socket(InetAddress.getLocalHost(), Constants.SERVER_PORT);
// 在控制台列印實例化的結果
System.out.println(soc);
//將ps指向soc的輸出流
ps = new PrintStream(soc.getOutputStream());
//定義一個字元緩沖存儲發送信息
StringBuffer info = new StringBuffer(Constants.CONNECT_IDENTIFER).append(Constants.SEPERATOR);
//其中INFO為關鍵字讓伺服器識別為連接信息
//並將name和ip用":"分開,在伺服器端將用一個
//StringTokenizer類來讀取數據
String userinfo = nameTextField.getText() + Constants.SEPERATOR
+ InetAddress.getLocalHost().getHostAddress();
ps.println(info.append(userinfo));

ps.flush();
//將客戶端線程實例化,並啟動
listener = new ClentListener(this, nameTextField.getText(), soc);
listener.start();
} catch (IOException e) {
System.out.println("Error:" + e);
disconnect();
}
}

} else if (source == disConnectButton){
// 如果點擊斷開連接按鈕
disconnect();

} else if (source == sendMsgButton) {
//如果點擊發送按鈕
if (soc != null) {
//定義並實例化一個字元緩沖存儲發送的聊天信息
StringBuffer msg = new StringBuffer(Constants.MSG_IDENTIFER).append(Constants.SEPERATOR);
//用列印流發送聊天信息
ps.println(msg.append(msgTextField.getText()));
ps.flush();
}
}
}

/**
* 斷開與伺服器的連接
*/
public void disconnect(){
if (soc != null) {
try {
// 用列印流發送QUIT信息通知伺服器斷開此次通信
ps.println(Constants.QUIT_IDENTIFER);
ps.flush();
soc.close(); //關閉套接字
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);
}

/**
* 客戶端線程類用來監聽伺服器傳來的信息
*/
class ClentListener extends Thread {
//存儲客戶端連接後的name信息
String name = null;
//客戶端接受伺服器數據的輸入流
BufferedReader br = null;
//實現從客戶端發送數據到伺服器的列印流
PrintStream ps = null;

//存儲客戶端的socket信息
Socket socket = null;
//存儲當前運行的ChatClient實例
ChatClient parent = null;

boolean running = true;

//構造方法
public ClentListener(ChatClient p, String n, Socket s) {

//接受參數
parent = p;
name = n;
socket = s;

try {
//實例化兩個數據流
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;
}

//線程運行方法
public void run(){
String msg = null;
while (running) {
msg = null;
try {
// 讀取從伺服器傳來的信息
msg = br.readLine();
System.out.println("receive msg: " + msg);
} catch (IOException e) {
System.out.println("Error:" + e);
parent.disconnect();
}
// 如果從伺服器傳來的信息為空則斷開此次連接
if (msg == null) {
parent.listener = null;
parent.soc = null;
parent.peopleList.removeAll();
running = false;
return;
}

//用StringTokenizer類來實現讀取分段字元
StringTokenizer st = new StringTokenizer(msg, Constants.SEPERATOR);
//讀取信息頭即關鍵字用來識別是何種信息
String keyword = st.nextToken();

if (keyword.equals(Constants.PEOPLE_IDENTIFER)) {
//如果是PEOPLE則是伺服器發來的客戶連接信息
//主要用來刷新客戶端的用戶列表
parent.peopleList.removeAll();
//遍歷st取得目前所連接的客戶
while (st.hasMoreTokens()) {
String str = st.nextToken();
parent.peopleList.add(str);
}

} else if (keyword.equals(Constants.MSG_IDENTIFER)) {
//如果關鍵字是MSG則是伺服器傳來的聊天信息,
//主要用來刷新客戶端聊天信息區將每個客戶的聊天內容顯示出來
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)) {
//如果關鍵字是QUIT則是伺服器關閉的信息, 切斷此次連接
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;

/**
* 聊天室的伺服器端程序,GUI界面
*/
public class ChatServer extends JFrame {

// 狀態欄標簽
static JLabel statusBar = new JLabel();
// 顯示客戶端的連接信息的列表
static java.awt.List connectInfoList = new java.awt.List(10);

// 保存當前處理客戶端請求的處理器線程
static Vector clientProcessors = new Vector(10);
// 當前的連接數
static int activeConnects = 0;

// 構造方法
public ChatServer() {
init();
try {
// 設置界面為系統默認外觀
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
e.printStackTrace();
}
}

private void init(){
this.setTitle("聊天室伺服器");
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);

// 將組件進行布局
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();
}

/**
* 退出菜單項事件
* @param e
*/
public void exitActionPerformed(ActionEvent e){
// 向客戶端發送斷開連接信息
sendMsgToClients(new StringBuffer(Constants.QUIT_IDENTIFER));
// 關閉所有的連接
closeAll();
System.exit(0);
}

/**
* 處理窗口關閉事件
*/
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方法向客戶端發送用戶列表的信息
sendMsgToClients(people);
}

/**
* 向所有客戶端群發消息
* @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);
}
}

/**
* 關閉所有連接
*/
public static void closeAll(){
while (clientProcessors.size() > 0) {
ClientProcessor c = (ClientProcessor) clientProcessors.firstElement();
try {
// 關閉socket連接和處理線程
c.socket.close();
c.toStop();
} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
clientProcessors.removeElement(c);
}
}
}

/**
* 判斷客戶端是否合法。
* 不允許同一客戶端重復登陸,所謂同一客戶端是指IP和名字都相同。
* @param newclient
* @return
*/
public static boolean checkClient(ClientProcessor newclient){
if (clientProcessors.contains(newclient)){
return false;
} else {
return true;
}
}

/**
* 斷開某個連接,並且從連接列表中刪除
* @param client
*/
public static void disconnect(ClientProcessor client){
disconnect(client, true);
}

/**
* 斷開某個連接,根據要求決定是否從連接列表中刪除
* @param client
* @param toRemoveFromList
*/
public static synchronized void disconnect(ClientProcessor client, boolean toRemoveFromList){
try {
//在伺服器端程序的list框中顯示斷開信息
connectInfoList.add(client.clientIP + "斷開連接");

ChatServer.activeConnects--; //將連接數減1
String constr = "目前有" + ChatServer.activeConnects + "客戶相連";
statusBar.setText(constr);
//向客戶發送斷開連接信息
client.send(new StringBuffer(Constants.QUIT_IDENTIFER));
client.socket.close();

} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
//從clients數組中刪除此客戶的相關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 {
// 伺服器端開始偵聽
server = new ServerSocket(Constants.SERVER_PORT);
} catch (IOException e) {
System.out.println("Error:" + e);
System.exit(1);
}
while (true) {
// 如果當前客戶端數小於MAX_CLIENT個時接受連接請求
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);
}

// 定義並實例化一個ClientProcessor線程類,用於處理客戶端的消息
ClientProcessor c = new ClientProcessor(socket);
if (checkClient(c)) {
// 添加到列表
clientProcessors.addElement(c);
// 如果客戶端合法,則繼續
int connum = ++ChatServer.activeConnects;
// 在狀態欄里顯示連接數
String constr = "目前有" + connum + "客戶相連";
ChatServer.statusBar.setText(constr);
// 將客戶socket信息寫入list框
ChatServer.connectInfoList.add(c.clientIP + "連接");
c.start();
// 通知所有客戶端用戶列表發生變化
notifyRoomPeople();
} else {
//如果客戶端不合法
c.ps.println("不允許重復登陸");
disconnect(c, false);
}

} else {
//如果客戶端超過了MAX_CLIENT個,則等待一段時間再嘗試接受請求
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
}
}
}
}

/**
* 處理客戶端發送的請求的線程
*/
class ClientProcessor extends Thread {
//存儲一個連接客戶端的socket信息
Socket socket;
//存儲客戶端的連接姓名
String clientName;

//存儲客戶端的ip信息
String clientIP;

//用來實現接受從客戶端發來的數據流
BufferedReader br;
//用來實現向客戶端發送信息的列印流
PrintStream ps;

boolean running = true;

/**
* 構造方法
* @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();

// 讀取信息,根據消息分隔符解析消息
StringTokenizer stinfo = new StringTokenizer(clientInfo, Constants.SEPERATOR);
String head = stinfo.nextToken();
if (head.equals(Constants.CONNECT_IDENTIFER)){
if (stinfo.hasMoreTokens()){
//關鍵字後的第二段數據是客戶名信息
clientName = stinfo.nextToken();
}
if (stinfo.hasMoreTokens()){
//關鍵字後的第三段數據是客戶ip信息
clientIP = stinfo.nextToken();
}
System.out.println(head); //在控制台列印頭信息
}
} catch (IOException e) {
System.out.println("Error:" + e);
}
}

/**
* 向客戶端發送消息
* @param msg
*/
public void send(StringBuffer msg) {
ps.println(msg);
ps.flush();
}

//線程運行方法
public void run() {

while (running) {
String line = null;
try {
//讀取客戶端發來的數據流
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();

// 如果關鍵字是MSG則是客戶端發來的聊天信息
if (keyword.equals(Constants.MSG_IDENTIFER)){
StringBuffer msg = new StringBuffer(Constants.MSG_IDENTIFER).append(Constants.SEPERATOR);
msg.append(clientName);
msg.append(st.nextToken("\0"));
// 再將某個客戶發來的聊天信息發送到每個連接客戶的聊天欄中
ChatServer.sendMsgToClients(msg);

} else if (keyword.equals(Constants.QUIT_IDENTIFER)) {
// 如果關鍵字是QUIT則是客戶端發來斷開連接的信息

// 伺服器斷開與這個客戶的連接
ChatServer.disconnect(this);
// 繼續監聽聊天室並刷新其他客戶的聊天人名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 {

// 伺服器的埠號
public static final int SERVER_PORT = 2525;
public static final int MAX_CLIENT = 10;

// 消息標識符與消息體之間的分隔符
public static final String SEPERATOR = ":";

// 消息信息的標識符
public static final String MSG_IDENTIFER = "MSG";
// 用戶列表信息的標識符
public static final String PEOPLE_IDENTIFER = "PEOPLE";
// 連接伺服器信息的標識符
public static final String CONNECT_IDENTIFER = "INFO";
// 退出信息標識符
public static final String QUIT_IDENTIFER = "QUIT";

}

㈣ JAVA五子棋代碼

import java.util.Arrays;

public class GoBangGame {
public static final char BLANK='*';
public static final char BLACK='@';
public static final char WHITE='O';

public static final int MAX = 16;
private static final int COUNT = 5;
//棋盤
private char[][] board;

public GoBangGame() {

}
//開始游戲
public void start() {
board = new char[MAX][MAX];
//把二維數組都填充『*』
for(char[] ary: board){
Arrays.fill(ary, BLANK);
}
}
public char[][] getChessBoard(){
return board;
}
public void addBlack(int x, int y) throws ChessExistException{
//@
//char blank = '*';
//System.out.println( x +"," + y + ":" + board[y][x] + "," + BLANK);
if(board[y][x] == BLANK){// x, y 位置上必須是空的才可以添棋子
board[y][x] = BLACK;
return;
}
throw new ChessExistException("已經有棋子了!");
}
public void addWhite(int x, int y)
throws ChessExistException{
if(board[y][x] == BLANK){// x, y 位置上必須是空的才可以添棋子
board[y][x] = WHITE;
return;
}
throw new ChessExistException("已經有棋子了!");
}
//chess 棋子:'@'/'O'
public boolean winOnY(char chess, int x, int y){
//先找到y方向第一個不是 blank的棋子
int top = y;
while(true){
if(y==0 || board[y-1][x]!=chess){
//如果y已經是棋盤的邊緣, 或者的前一個不是chess
//就不再繼續查找了
break;
}
y--;
top = y;
}
//向回統計所有chess的個數,如果是COUNT個就贏了
int count = 0;
y = top;
while(true){
if(y==MAX || board[y][x]!=chess){
//如果找到頭 或者 下一個子不是chess 就不再繼續統計了
break;
}
count++;
y++;
}
return count==COUNT;
}
//chess 棋子:'@'/'O'
public boolean winOnX(char chess, int x, int y){
//先找到x方向第一個不是 blank的棋子
int top = x;
while(true){
if(x==0 || board[y][x-1]!=chess){
//如果x已經是棋盤的邊緣, 或者的前一個不是chess
//就不再繼續查找了
break;
}
x--;
top = x;
}
//向回統計所有chess的個數,如果是COUNT個就贏了
int count = 0;
x = top;
while(true){
if(x==MAX || board[y][x]!=chess){
//如果找到頭 或者 下一個子不是chess 就不再繼續統計了
break;
}
count++;
x++;
}
return count==COUNT;
}

//chess 棋子:'@'/'O'
public boolean winOnXY(char chess, int x, int y){
//先找MAX向第一個不是 blank的棋子
int top = y;
int left = x;
while(true){
if(x==0 || y==0 || board[y-1][x-1]!=chess){
//如果x已經是棋盤的邊緣, 或者的前一個不是chess
//就不再繼續查找了
break;
}
x--;
y--;
top = y;
left=x;
}
//向回統計所有chess的個數,如果是COUNT個就贏了
int count = 0;
x = left;
y = top;
while(true){
if(x==MAX || y==MAX || board[y][x]!=chess){
//如果找到頭 或者 下一個子不是chess 就不再繼續統計了
break;
}
count++;
x++;
y++;
}
return count==COUNT;
}
//chess 棋子:'@'/'O'
public boolean winOnYX(char chess, int x, int y){
//先找到x方向第一個不是 blank的棋子
int top = y;
int left = x;
while(true){
if(x==MAX-1 || y==0 || board[y-1][x+1]!=chess){
//如果x已經是棋盤的邊緣, 或者的前一個不是chess
//就不再繼續查找了
break;
}
x++;
y--;
top = y;
left=x;
}
//向回統計所有chess的個數,如果是COUNT個就贏了
int count = 0;
x = left;
y = top;
while(true){
if(x==0 || y==MAX || board[y][x]!=chess){
//如果找到頭 或者 下一個子不是chess 就不再繼續統計了
break;
}
count++;
x--;
y++;
}
return count==COUNT;
}

public boolean whiteIsWin(int x, int y) {
//在任何一個方向上贏了,都算贏
return winOnY(WHITE, x, y) ||
winOnX(WHITE, x, y) ||
winOnXY(WHITE, x, y) ||
winOnYX(WHITE, x, y);
}
public boolean blackIsWin(int x, int y) {
return winOnY(BLACK, x, y) ||
winOnX(BLACK, x, y) ||
winOnXY(BLACK, x, y) ||
winOnYX(BLACK, x, y);
}

}

自己看看這個行不行,應該能滿足你的要求了

㈤ 多用戶五子棋游戲 JAVA編程

java網路五子棋

下面的源代碼分為4個文件;
chessClient.java:客戶端主程序。
chessInterface.java:客戶端的界面。
chessPad.java:棋盤的繪制。
chessServer.java:伺服器端。
可同時容納50個人同時在線下棋,聊天。
沒有加上詳細注釋,不過絕對可以運行,j2sdk1.4下通過。

/*********************************************************************************************
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(userNumber>0 && !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無法關閉");
}
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("請黑棋下子");
}
else if(chessclient.isClient)
{
chessclient.chesspad.chessColor=-1;
chessclient.chesspad.statusText.setText("已加入游戲,等待對方下子...");
}

}
else if(recMessage.equals("/youwin"))
{
chessclient.isOnChess=false;
chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor);
chessclient.chesspad.statusText.setText("對方退出,請點放棄游戲退出連接");
chessclient.chesspad.isMouseEnabled=false;
}
else if(recMessage.equals("/OK"))
{
chessclient.chesspad.statusText.setText("創建游戲成功,等待別人加入...");
}
else if(recMessage.equals("/error"))
{
chessclient.chatpad.chatLineArea.append("傳輸錯誤:請退出程序,重新加入 \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; //如果是下棋的主機
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:無法連接,建議重新啟動程序 \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("連接成功,請創建游戲或加入游戲");
}

}
catch(Exception ei)
{
chatpad.chatLineArea.setText("controlpad.connectButton:無法連接,建議重新啟動程序 \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("必須先選定一個有效用戶");
}
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無法連接 \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無法連接 \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("請建立游戲或者加入游戲");
}
if(!isOnChess)
{
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chesspad.statusText.setText("請建立游戲或者加入游戲");
}
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無法連接,建議重新連接 \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無法連接,建議重新連接 \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;i<50;i++)
{
userList.add(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("連接主機");
Button creatGameButton=new Button("建立游戲");
Button joinGameButton=new Button("加入游戲");
Button cancelGameButton=new Button("放棄游戲");
Button exitGameButton=new Button("關閉程序");

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;i<50;i++)
{
userChoice.addItem(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("錯誤:沒有這個用戶,請退出程序,重新加入");
}
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("請先連接伺服器");

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:無法連接 \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代碼旁邊就注釋 讓我看的清楚明白一些,要詳細的解釋和思路

import java.applet.*;
import t.*;
import t.event.*;
import java.applet.Applet;
import t.Color; //這一段import就不說了,下面要用到的就import進來

public class wuziqi extends Applet implements ActionListener,MouseListener,MouseMotionListener,ItemListener
//繼承Applet表明是個applet,後面的介面必須要實現每個介面的所有方法
{
int color_Qizi=0;//旗子的顏色標識 0:白子 1:黑子
int intGame_Start=0;//游戲開始標志 0未開始 1游戲中
int intGame_Body[][]=new int[16][16]; //設置棋盤棋子狀態 0 無子 1 白子 2 黑子

㈦ 解釋五子棋的java代碼

import java.util.Scanner;

public class FiveChess {
static char[][] chess = new char[16][16];
static boolean isBlack = true;

public static void main(String[] args) {
System.out.println(" =======五子棋游戲======= ");
System.out.println();
for (int i = 0; i < chess.length; i++) {
for (int j = 0; j < chess[i].length; j++) {
chess[i][j] = '*';
}
}// for end!
Scanner sca = new Scanner(System.in);
printChess();
while (true) {
System.out.println();
System.out.println("請" + (isBlack ? "黑方" : "白方") + "落子:");
String str = sca.next();
int r = fromCharToInt(str.charAt(0));
int c = fromCharToInt(str.charAt(1));
if ((r < 0 || r > 15) || (c < 0 || c > 15)) {
System.out.println("輸入位置錯誤,請重新輸入!");
continue;
} else if (chess[r][c] != '*') {
System.out.println("該位置有子,請重新輸入!");
continue;
} else {
chess[r][c] = isBlack ? '@' : '#';
printChess();
if (wasWin(r, c)) {
System.out.println((isBlack ? "黑方" : "白方") + "獲勝,游戲結束!");
break;
} else {
isBlack = !isBlack;
}
}
}
}// main end!

public static void printChess() { // 列印棋盤
System.out.print(" ");
for (int i = 0; i < chess.length; i++) {
if (i < 10) {
System.out.print(" " + i);
} else {
System.out.print(" " + (char) ('a' + i - 10));
}
}// for end!
System.out.println();
for (int i = 0; i < chess.length; i++) {
if (i < 10) {
System.out.print(i + " ");
} else {
System.out.print((char) ('a' + i - 10) + " ");
}
for (int j = 0; j < chess.length; j++) {
System.out.print(chess[i][j] + " ");
}
System.out.println();
}
}// printChess end!

public static int fromCharToInt(char c) {// 判斷是否越界
if (c >= '0' && c <= '9') {
return c - 48;
} else {
return c - 'a' + 10;
}
}

public static boolean wasWin(int r, int c) {// 判斷是否贏了
return wasWinAtV(r, c) || wasWinAtE(r, c) || wasWinAtRD(r, c)
|| wasWinAtLD(r, c);
}

public static boolean wasWinAtV(int r, int c) {
char ch = isBlack ? '@' : '#';
int i = r;
while (i >= 0 && chess[i][c] == ch) {
i--;
}
i++;
int num = 0;
while (i < chess.length && chess[i][c] == ch) {
num++;
i++;
}
return num >= 5;
}

public static boolean wasWinAtE(int r, int c) {
char ch = isBlack ? '@' : '#';
int i = c;
while (i >= 0 && chess[r][i] == ch) {
i--;
}
i++;
int num = 0;
while (i < chess.length && chess[r][i] == ch) {
num++;
i++;
}
return num >= 5;
}

public static boolean wasWinAtRD(int r, int c) {
char ch = isBlack ? '@' : '#';
int i = r;
int j = c;
while (i >= 0 && j < chess.length && chess[i][j] == ch) {
i--;
j++;
}
i++;
j--;
int num = 0;
while (i < chess.length && j >= 0 && chess[i][j] == ch) {
i++;
j--;
num++;
}
return num >= 5;
}

private static boolean wasWinAtLD(int r, int c) {
char ch = isBlack ? '@' : '#';
int i = r;
int j = c;
while (i >= 0 && j >= 0 && chess[i][j] == ch) {
i--;
j--;
}
i++;
j++;
int num = 0;
while (i < chess.length && j < chess.length && chess[i][j] == ch) {
i++;
j++;
num++;
}
return num >= 5;
}

}

看看我的啊!

閱讀全文

與java網路五子棋代碼相關的資料

熱點內容
電子文件保護的核心是什麼 瀏覽:196
snt修改器安裝教程 瀏覽:663
白雜訊文件是什麼 瀏覽:723
java打開新窗口 瀏覽:195
如何同步七天前的數據 瀏覽:95
從來不開數據為什麼會消耗流量 瀏覽:938
固態win10裝機教程 瀏覽:539
u盤可以用但不能保存文件 瀏覽:625
多個名稱多個文件名 瀏覽:11
如何恢復隱藏的文件夾 瀏覽:474
u盤插入電腦直接彈出文件 瀏覽:317
jt是什麼文件 瀏覽:353
法律助手app 瀏覽:937
雲存儲文件路徑 瀏覽:523
硬碟有點壞文件復制到桌面很慢 瀏覽:894
尼爾pod技能升級 瀏覽:586
vb編程打開pdf文件 瀏覽:617
qq七彩氣泡id大全 瀏覽:963
iphone4隻能免提說話才有聲音 瀏覽:79
CNC雕刻機用什麼軟體編程 瀏覽:173

友情鏈接