導航:首頁 > 編程語言 > java四子棋

java四子棋

發布時間:2022-08-27 10:37:39

java五子棋怎麼畫ER圖

先畫正方形,然後畫兩條對折線完成。
第一步、我們先來畫一畫五子棋的棋盤,畫出一個棋盤,畫一個四方形。
第二步、接著我們畫一畫棋盤的棋盤格,橫橫豎豎的橫要平,豎要直溜溜。
第三步、接著我們畫出棋盤裡面的棋子,黑色和白色的棋子就完成啦。

❷ java五子棋

我有82237475

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;

❸ 求java編寫的五子棋代碼,要有電腦AI的

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做五子棋源代碼

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實現

其實我也有用JAVA做五子棋呢~,棋盤都是用畫的,我把代碼發下,你自己試下,也不定合你一意.事件代碼我都去啦,因為是簡單的麻煩事.~!

import java.awt.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class ChessBoard extends JPanel{
/*
* 製作棋盤的寬高;
*/
public static final int BOARD_WIDTH=515;
/*
* 計算棋盤表格坐標(單元格寬高相等)
*/
public static int [] location=new int[22];
static{
for(int i=0,WIDTH=30;i<location.length;i++,WIDTH+=22){
location[i]=WIDTH;
}
}
public ChessBoard(int x,int y){
super(null);
this.setBounds(x, y, BOARD_WIDTH, BOARD_WIDTH);
this.setBackground(new Color(255, 164, 85));
}
/**
* 重寫方法,繪制棋盤表格圖;
*/
public void paintComponent(Graphics g){
super.paintComponent(g);
char ch='A';
g.setFont(new Font("宋體",Font.BOLD,12));
//畫橫線
for(int i=0,width=30+22*21;i<location.length;i++,ch++){
g.setColor(Color.black);
g.drawLine(30,location[i],width,location[i]);
g.setColor(Color.blue);
g.drawString(""+ch,5,location[i]+3);
}
//畫豎線
for(int i=0,width=30+22*21;i<location.length;i++){
g.setColor(Color.black);
g.drawLine(location[i],30,location[i],width);
g.setColor(Color.blue);
g.drawString(""+(i+1),location[i]-3,13);
}

}
}

❻ 用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]))
{

❼ 有關java的寫程序的問題

創建一個二維字元數組,裡面全存放"╋",列印出來就是棋盤,下黑棋,就是把對應的元素的"╋"換成"●",白棋就是「○」,你可以在輸入法里的特殊符號里找到黑圓和空圓的字元。每次下棋前,判斷那個位置是否已經有棋了,如果不是"╋"就是有棋了,再定義一個數字記錄走了多少步,用奇偶性來判斷下黑棋還是下白棋,每下完一個棋子,重新輸出列印整個數組,下棋輸入的兩個整數,就是數組的坐標,這樣就可以實現簡單的控制台五子棋了。輸贏的判斷,就是判斷橫、豎、斜四個方向是否有連續的五個同顏色的棋子。試著編一下吧,自己弄出來還是有點成就感的。

❽ java游戲五子棋論文

<%@ page contentType="text/html;charset=utf-8"%>
<html>
<head>
<title>五子棋</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
body{ word-break:break-word;
}
#aboutstep{
position:absolute;
right:45px;
top:300px;
width:200px;
vertical-align:bottom;
}
</style>
<script language="javascript">
//五子棋棋子亦稱「棋石」分黑、白兩色,形狀為扁圓形,有一面凸起或兩面凸起等形狀,厚度不超過0.8厘米,直徑為2.0~2.3厘米;
//一副棋子總數為225枚,其中黑子113枚,白子112枚。
var presentperson=false; //true表示人先下,否則表示機器先下
//誰先只需要改為true或false就可以了,不需要改其它東西
var maxsize=15;
var personstep=0;
var machinestep=0;
var _stack=new Array();//needn't to allocate space
var chese=new Array(maxsize*maxsize);
var chesevalue=new Array(maxsize*maxsize);
for(var i=0;i<maxsize*maxsize;i++)//初始化棋盤
{ chese[i]=0;
}
</script>
</head>
<body onload="startup()">
<table id="chesetable" border="1px" width="auto" align="center" height="600px" style="background-color:#EED090;text-align:center;">
<%
for(int i=0;i<15;i++)
{out.print("<tr>");
for(int j=0;j<15;j++)
{out.print("<td onclick='putone(this,"+i+","+j+")' style='width:45px;height:45px;cursor:pointer;'></td>");
}
out.print("</tr>");
}
%>
</table>
<div id="aboutstep"><!-- 加計時器會降低速度,這里就不加了 -->
人<img src="images/white_.gif" alt="white" width="50px" height="50px" style="vertical-align:middle;"/><span id="aboutsteppeople" style="position:inline;">0</span>
<span style="display:inline;"><input type="text" id="peopleusedtime" size=4 maxlength="8" /></span>
<br />
機器<img src="images/black_.gif" alt="black" width="50px" height="50px" style="vertical-align:middle;"s/><span id="aboutstepmachine" style="position:inline;">0</span>
<span style="display:inline;"><input type="text" id="machineusedtime" size=4 maxlength="8" /></span>
</div>
<div align="center">
<input type="button" name="restart" value="重新開始" onclick="reload()"/><input type="button" name="turnout" value="交換順序" />
<input type="button" name="undo" value="悔棋" onclick="popstack()"/>
</div>
<script language="JavaScript">
function startup()
{
if(!presentperson)//機器先下
{ var obj=document.getElementById("chesetable").rows[7].cells[7];
putone(obj,7,7);
}
}
function putone(obj,i,j)
{ //if(obj.firstChild.nodeValue=="◎"||obj.firstChild.nodeValue=="●")
if(obj.firstChild.nodeType==1) //表示放了棋子
{ return false;}

var node=null;
if(presentperson)
{ //node=document.createTextNode("◎"); //人的棋子顏色
if(document.uniqueID) //IE
node=document.createElement("<img src='images/white_.gif' alt='white' width='40px' height='40px' />");
else { //for Firefox,Opera
node=document.createElement("img");
node.setAttribute("src","images/white_.gif");
node.setAttribute("alt","white");
node.setAttribute("width","40px");
node.setAttribute("height","40px");
}
presentperson=!presentperson;
chese[maxsize*i+j]=1;
personstep++;
document.getElementById("aboutsteppeople").innerHTML=personstep;

}
else {//node=document.createTextNode("●"); //機器的棋子顏色
if(document.uniqueID) //IE
node=document.createElement("<img src='images/black_.gif' alt='black' width='40px' height='40px' />");
else { node=document.createElement("img");
node.setAttribute("src","images/black_.gif");
node.setAttribute("alt","black");
node.setAttribute("width","40px");
node.setAttribute("height","40px");
}presentperson=!presentperson;
chese[maxsize*i+j]=2;
machinestep++;
document.getElementById("aboutstepmachine").innerHTML=machinestep;
}
obj.replaceChild(node,obj.firstChild);
_stack.push(i);
_stack.push(j); //避免數據冗餘,就不存儲presentperson
var result=checkfinish(!presentperson,i,j);
if(result)
{ if(!presentperson) alert("Congratulation!You win.");
else alert("I am sorry that the machine wins,try your best to win next time.");
setTimeout(reload,4000); //刷新頁面
}
if(!presentperson) {machinedecideposition();} //機器走。如果選擇全部由人走就去掉這個
}
function checkfinish(presentperson,i,j)
{ //persentperson為true時表示剛才人下了一步
var checkword;
var result=false; //nobody wins
if(presentperson) checkword=1;
else checkword=2;
var total=1;
var tempj=j+1;
while(tempj<maxsize) //橫
{ if(chese[maxsize*i+tempj]==checkword)
{total++; tempj++;}
else break;
}
tempj=j-1;
while(tempj>=0)
{ if(chese[maxsize*i+tempj]==checkword)
{total++; tempj--;}
else break;
}
if(total>4) { return true;}

total=1;
var tempi=i+1; //豎
while(tempi<maxsize)
{ if(chese[maxsize*tempi+j]==checkword)
{total++; tempi++;}
else break;
}
tempi=i-1;
while(tempi>=0)
{ if(chese[maxsize*tempi+j]==checkword)
{total++; tempi--;}
else break;
}
if(total>4) { return true;}

total=1;
tempi=i+1; //一三象限斜
tempj=j+1;
while(tempi<maxsize&&tempj<maxsize)
{ if(chese[maxsize*tempi+tempj]==checkword)
{total++; tempi++; tempj++;}
else break;
}

tempi=i-1;
tempj=j-1;
while(tempi>=0&&tempj>=0)
{ if(chese[maxsize*tempi+tempj]==checkword)
{total++; tempi--; tempj--;}
else break;
}
if(total>4) { return true;}

total=1;
tempi=i+1; //二四象限斜
tempj=j-1;
while(tempi<maxsize&&tempj>=0)
{ if(chese[maxsize*tempi+tempj]==checkword)
{total++; tempi++; tempj--;}
else break;
}
tempi=i-1;
tempj=j+1;
while(tempi>=0&&tempj<maxsize)
{ if(chese[maxsize*tempi+tempj]==checkword)
{total++; tempi--; tempj++;}
else break;
}
if(total>4) { return true;}
return false;
}
function pushstack()
{
}
function popstack() //悔棋
{
if(_stack.length/2<1) return;
//var ispresentperson=(_stack.length/2)%2?true:false;//這個跟誰先下有關
var ispresentperson=presentperson; //now it has not matter with the length of _stack
var j=_stack.pop();
var i=_stack.pop();
removeone(ispresentperson,i,j);

}
function removeone(ispresentperson,i,j)
{ var obj=document.getElementById("chesetable");
//text,tbody
var tbody=obj.firstChild.nextSibling;
tbody.rows[i].cells[j].innerHTML="";
chese[maxsize*i+j]=0; //也要初始化那個棋子所在的位置
presentperson=!presentperson;//也要回滾該誰走,who's turn now?
if(!ispresentperson) {personstep--;
document.getElementById("aboutsteppeople").innerHTML=personstep;
}
else {machinestep--;
document.getElementById("aboutstepmachine").innerHTML=machinestep;
}

}
function machinedecideposition() //機器決定下一步的位置
{ //在第一層節點選擇的時候採用貪婪演算法,直接找出相對分數比較高的幾個形成第一層節點,目的是為了提高搜索速度和防止堆棧溢出。
if(machinestep==0) //機器走第一步
{ var obj=document.getElementById("chesetable").rows[7].cells[7];
if(putone(obj,7,7)==false)
{ obj=document.getElementById("chesetable").rows[6].cells[6];
putone(obj,6,6);
}
}
else if(machinestep==1) //機器走第二步
{ var obj=document.getElementById("chesetable").rows[7].cells[7];
if(putone(obj,7,7)==false) //7,7位置被佔用
{ obj=document.getElementById("chesetable").rows[6].cells[6];
if(putone(obj,6,6)==false)//6,6位置被佔用
{obj=document.getElementById("chesetable").rows[6].cells[7];
putone(obj,6,7);
}
}

}
else { var checkword=2; //先判斷機器的,在設置為1判斷這個位置對人的貢獻
for(var tttt=0;tttt<maxsize*maxsize;tttt++)
chesevalue[tttt]=-10;//初始化
for(var i=0;i<maxsize;i++)
for(var j=0;j<maxsize;j++)
{ if(chese[maxsize*i+j]!=0) //the position is occupied
continue;

var total=1;
var tempj=j+1;
var spacenumber=0; //中間空多少個
var befive=0; //成5,包括五連和長連
var livefour=0; //活四,有兩個點可以成5地四
var befour=0; //沖四,只有一個點可以成為5的四
var deadfour=0; //死四,不能成為5的四
var livethree=0; //活三,再走一步就可以成為活四的三
//活三包括 連活三和跳活三
var bethree=0;
var livetwo=0;
var betwo=0;
//三三,一子落下同時形成兩個活三
//四四,一子落下同時形成兩個沖四
//四三,一子落下同時形成一個沖四和 活三
for(var tt=0;;tt++)
{ if(tt==0)
checkword=2; //machine
else checkword=1; //people
while(tempj<maxsize) //橫
{ if(chese[maxsize*i+tempj]==checkword&&checkword==2) //是機器的
{total++; tempj++;}
else if(chese[maxsize*i+tempj]==0&&checkword==2) //對於防守不考慮空格
{ //is empty
spacenumber++; break;
if((++tempj)<maxsize&&chese[maxsize*i+tempj]==checkword&&spacenumber<2)
total++;
else break;
}
else if(chese[maxsize*i+tempj]==checkword&&checkword==1) //防守
{ total++; tempj++;
}
else break;
}
var endj=tempj;
tempj=j-1;
while(tempj>=0)
{ if(chese[maxsize*i+tempj]==checkword&&checkword==2)
{total++; tempj--;}
else if(chese[maxsize*i+tempj]==0&&checkword==2)
{ //is empty
spacenumber++; break;
if((--tempj)>=0&&chese[maxsize*i+tempj]==checkword&&spacenumber<2)
total++;
else break;
}
else if(chese[maxsize*i+tempj]==checkword&&checkword==1) //防守
{ total++; tempj--;
}
else break;
}
var startj=tempj;
//由於checkword==2先運行,所以可以直接用befive=1,也可以用befive++;
if(total>4) { //能組成五個或以上的
if(checkword==2)
{befive+=2
} //堵住成五
else befive++;
}//進攻要大於防守
else if(total==4) { //能組成四個
if(checkword==2) //表示考慮進攻
{ if(startj>=0&&endj<maxsize&&chese[maxsize*i+startj]!=1&&chese[maxsize*i+endj]!=1) //兩邊為空格
livefour+=2; //放在這里可以形成一個活四
else if((startj>=0&&chese[maxsize*i+startj]!=1)||(endj<maxsize&&chese[maxsize*i+endj]!=1))
befour+=2; //形成一個沖四
else deadfour+=2;
}
else //考慮防守
{ if(startj>=0&&endj<maxsize&&chese[maxsize*i+startj]!=2&&chese[maxsize*i+endj]!=2)
livefour+=1; //放在這里可以形成一個活四
else if((startj>=0&&chese[maxsize*i+startj]!=2)||(endj<maxsize&&chese[maxsize*i+endj]!=2))
befour+=1; //形成一個沖四
else deadfour+=1;

}
}
else if(total==3){if(checkword==2) //表示考慮進攻
{ if(startj>=0&&endj<maxsize&&chese[maxsize*i+startj]!=1&&chese[maxsize*i+endj]!=1) //兩邊為空格
livethree+=2; //放在這里可以形成一個活三(算做連活三)
else if((startj>=0&&chese[maxsize*i+startj]!=1)||(endj<maxsize&&chese[maxsize*i+endj]!=1))
bethree+=2; //形成一個眠三,即可以沖四的三
// else deadfour+=2;
//跳三
}
else //考慮防守
{ if(startj>=0&&endj<maxsize&&chese[maxsize*i+startj]!=2&&chese[maxsize*i+endj]!=2) //兩邊為空格
livethree+=1; //放在這里可以形成一個活三(算做連活三)
else if((startj>=0&&chese[maxsize*i+startj]!=2)||(endj<maxsize&&chese[maxsize*i+endj]!=2))
bethree+=1; //形成一個眠三,即可以沖四的三
}
}
else if(total==2){ if(checkword==2) //表示考慮進攻
{ if(startj>=0&&endj<maxsize&&chese[maxsize*i+startj]!=1&&chese[maxsize*i+endj]!=1) //兩邊為空格
livetwo++; //放在這里可以形成一個活三(算做連活三)
}
else //考慮防守
{ if(startj>=0&&endj<maxsize&&chese[maxsize*i+startj]!=2&&chese[maxsize*i+endj]!=2) //兩邊為空格
livetwo++; //放在這里可以形成一個活三(算做連活三)

}
}

閱讀全文

與java四子棋相關的資料

熱點內容
編譯原理代碼在哪裡運行 瀏覽:584
解密攝影pdf 瀏覽:72
演算法編程中級題目 瀏覽:249
c語言編譯器畢業設計 瀏覽:715
醫保卡申請app哪個好 瀏覽:944
阿里雲伺服器上傳源碼 瀏覽:602
營銷管理科特勒pdf 瀏覽:696
願望清單app哪個好 瀏覽:459
安卓外放聲音怎麼解決 瀏覽:195
脈脈app干什麼用的 瀏覽:360
拽姐是哪個app 瀏覽:861
雲伺服器刪除了還有嗎 瀏覽:234
macbook可以用單片機嘛 瀏覽:309
南陽php招聘 瀏覽:818
去哪裡找按摩師很漂亮的app 瀏覽:821
86x99用簡便演算法計算 瀏覽:833
php截圖flash 瀏覽:276
卸載聯想app哪個好 瀏覽:722
php文字轉圖片 瀏覽:332
豆客後台怎麼加密碼 瀏覽:577