科技行者

行者学院 转型私董会 科技行者专题报道 网红大战科技行者

知识库

知识库 安全导航

至顶网软件频道java网络五子棋的源代码

java网络五子棋的源代码

  • 扫一扫
    分享文章到微信

  • 扫一扫
    关注官方公众号
    至顶头条

java网络五子棋的源代码

来源:plwww 2007年10月25日

关键字: 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);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

}

else if(checkColor==-1)

{

chessLink=1;

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

{

for(chessCompare=0;chessCompare<=chessWhiteCount;chessCompare++)

{

if(((a+step)*20==chessWhite_x[chessCompare]) && (b*20==chessWhite_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<=chessWhiteCount;chessCompare++)

{

if(((a-step)*20==chessWhite_x[chessCompare]) && (b*20==chessWhite_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<=chessWhiteCount;chessCompare++)

{

if((a*20==chessWhite_x[chessCompare]) && ((b+step)*20==chessWhite_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<=chessWhiteCount;chessCompare++)

{

if((a*20==chessWhite_x[chessCompare]) && ((b-step)*20==chessWhite_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<=chessWhiteCount;chessCompare++)

{

if(((a-step)*20==chessWhite_x[chessCompare]) && ((b+step)*20==chessWhite_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<=chessWhiteCount;chessCompare++)

{

if(((a+step)*20==chessWhite_x[chessCompare]) && ((b-step)*20==chessWhite_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<=chessWhiteCount;chessCompare++)

{

if(((a+step)*20==chessWhite_x[chessCompare]) && ((b+step)*20==chessWhite_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<=chessWhiteCount;chessCompare++)

{

if(((a-step)*20==chessWhite_x[chessCompare]) && ((b-step)*20==chessWhite_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

}

return(false);

}

public void paint(Graphics g)

{

for (int i=40;i<=380;i=i+20)

{

g.drawLine(40,i,400,i);

}

g.drawLine(40,400,400,400);

for(int j=40;j<=380;j=j+20)

{

g.drawLine(j,40,j,400);

}

g.drawLine(400,40,400,400);

g.fillOval(97,97,6,6);

g.fillOval(337,97,6,6);

g.fillOval(97,337,6,6);

g.fillOval(337,337,6,6);

g.fillOval(217,217,6,6);

}

public void chessPaint(int chessPoint_a,int chessPoint_b,int color)

{

chessPoint_black chesspoint_black=new chessPoint_black(this);

chessPoint_white chesspoint_white=new chessPoint_white(this);

if(color==1 && isMouseEnabled)

{

getLocation(chessPoint_a,chessPoint_b,color);

isWin=checkWin(chessPoint_a,chessPoint_b,color);

if(isWin==false)

{

chessthread.sendMessage("/"+chessPeerName+" /chess "+chessPoint_a+" "+chessPoint_b+" "+color);

this.add(chesspoint_black);

chesspoint_black.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16);

statusText.setText("黑(第"+chessBlackCount+"步)"+chessPoint_a+" "+chessPoint_b+",请白棋下子");

isMouseEnabled=false;

}

else

{

chessthread.sendMessage("/"+chessPeerName+" /chess "+chessPoint_a+" "+chessPoint_b+" "+color);

this.add(chesspoint_black);

chesspoint_black.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16);

chessVictory(1);

isMouseEnabled=false;

}

}

else if(color==-1 && isMouseEnabled)

{

getLocation(chessPoint_a,chessPoint_b,color);

isWin=checkWin(chessPoint_a,chessPoint_b,color);

if(isWin==false)

{

chessthread.sendMessage("/"+chessPeerName+" /chess "+chessPoint_a+" "+chessPoint_b+" "+color);

this.add(chesspoint_white);

chesspoint_white.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16);

statusText.setText("白(第"+chessWhiteCount+"步)"+chessPoint_a+" "+chessPoint_b+",请黑棋下子");

isMouseEnabled=false;

}

else

{

chessthread.sendMessage("/"+chessPeerName+" /chess "+chessPoint_a+" "+chessPoint_b+" "+color);

this.add(chesspoint_white);

chesspoint_white.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16);

chessVictory(-1);

isMouseEnabled=false;

}

}

}

public void netChessPaint(int chessPoint_a,int chessPoint_b,int color)

{

chessPoint_black chesspoint_black=new chessPoint_black(this);

chessPoint_white chesspoint_white=new chessPoint_white(this);

getLocation(chessPoint_a,chessPoint_b,color);

if(color==1)

{

isWin=checkWin(chessPoint_a,chessPoint_b,color);

if(isWin==false)

{

this.add(chesspoint_black);

chesspoint_black.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16);

statusText.setText("黑(第"+chessBlackCount+"步)"+chessPoint_a+" "+chessPoint_b+",请白棋下子");

isMouseEnabled=true;

}

else

{

this.add(chesspoint_black);

chesspoint_black.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16);

chessVictory(1);

isMouseEnabled=true;

}

}

else if(color==-1)

{

isWin=checkWin(chessPoint_a,chessPoint_b,color);

if(isWin==false)

{

this.add(chesspoint_white);

chesspoint_white.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16);

statusText.setText("白(第"+chessWhiteCount+"步)"+chessPoint_a+" "+chessPoint_b+",请黑棋下子");

isMouseEnabled=true;

}

else

{

chessthread.sendMessage("/"+chessPeerName+" /victory "+color);

this.add(chesspoint_white);

chesspoint_white.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16);

chessVictory(-1);

isMouseEnabled=true;

}

}

}

public void mousePressed(MouseEvent e)

{

if (e.getModifiers()==InputEvent.BUTTON1_MASK)

{

chessPoint_x=(int)e.getX();

chessPoint_y=(int)e.getY();

int a=(chessPoint_x+10)/20,b=(chessPoint_y+10)/20;

if(chessPoint_x/20<2||chessPoint_y/20<2||chessPoint_x/20>19||chessPoint_y/20>19)

{}

else

{

chessPaint(a,b,chessColor);

}

}

}

public void mouseReleased(MouseEvent e){}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

public void mouseClicked(MouseEvent e) {}

public void actionPerformed(ActionEvent e)

{

}

}

class chessPoint_black extends Canvas implements MouseListener

{

chessPad chesspad=null;

chessPoint_black(chessPad p)

{

setSize(20,20);

chesspad=p;

addMouseListener(this);

}

public void paint(Graphics g)

{

g.setColor(Color.black);

g.fillOval(0,0,14,14);

}

public void mousePressed(MouseEvent e)

{

// if(e.getModifiers()==InputEvent.BUTTON3_MASK)

// {

// chesspad.remove(this);

// chesspad.chessColor=1;

// chesspad.text_2.setText("");

// chesspad.text_1.setText("请黑棋下子");

// }

}

public void mouseReleased(MouseEvent e){}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

public void mouseClicked(MouseEvent e) {}

}

class chessPoint_white extends Canvas implements MouseListener

{

chessPad chesspad=null;

chessPoint_white(chessPad p)

{

setSize(20,20);

addMouseListener(this);

chesspad=p;

}

public void paint(Graphics g)

{

g.setColor(Color.white);

g.fillOval(0,0,14,14);

}

public void mousePressed(MouseEvent e)

{

// if(e.getModifiers()==InputEvent.BUTTON3_MASK)

// {

// chesspad.remove(this);

// chesspad.chessColor=-1;

// chesspad.text_2.setText("请白旗下子");

// chesspad.text_1.setText("");

// }

}

public void mouseReleased(MouseEvent e){}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

public void mouseClicked(MouseEvent e)

{

// if(e.getClickCount()>=2)

// chesspad.remove(this);

}

}

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

最后是:chessServer.java

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

import java.io.*;

import java.net.*;

import java.awt.*;

import java.util.*;

import java.awt.event.*;

class MessageServer extends Panel //implements ActionListener

{

TextArea messageBoard=new TextArea("",22,50,TextArea.SCROLLBARS_VERTICAL_ONLY);

Label statusLabel=new Label("当前连接数:",Label.LEFT);

Panel boardPanel=new Panel();

Panel statusPanel=new Panel();

MessageServer()

{

setSize(350,300);

setBackground(Color.pink);

setLayout(new BorderLayout());

boardPanel.setLayout(new FlowLayout());

boardPanel.setSize(210,210);

statusPanel.setLayout(new BorderLayout());

statusPanel.setSize(210,50);

boardPanel.add(messageBoard);

statusPanel.add(statusLabel,BorderLayout.WEST);

add(boardPanel,BorderLayout.CENTER);

add(statusPanel,BorderLayout.NORTH);

}

}

class ServerThread extends Thread

{

Socket clientSocket;

Hashtable clientDataHash;

Hashtable clientNameHash;

Hashtable chessPeerHash;

MessageServer server;

boolean isClientClosed=false;

ServerThread(Socket clientSocket,Hashtable clientDataHash,Hashtable clientNameHash,Hashtable chessPeerHash,MessageServer server)

{

this.clientSocket=clientSocket;

this.clientDataHash=clientDataHash;

this.clientNameHash=clientNameHash;

this.chessPeerHash=chessPeerHash;

this.server=server;

}

public void messageTransfer(String message)

{

String clientName,peerName;

if(message.startsWith("/"))

{

if(message.startsWith("/changename "))

{

clientName=message.substring(12);

if( clientName.length()<=0 || clientName.length()>20 ||

clientName.startsWith("/") || clientNameHash.containsValue(clientName) ||

clientName.startsWith("changename")|| clientName.startsWith("list") ||

clientName.startsWith("[inchess]") || clientName.startsWith("creatgame") ||

clientName.startsWith("joingame") || clientName.startsWith("yourname") ||

clientName.startsWith("userlist") || clientName.startsWith("chess") ||

clientName.startsWith("OK") || clientName.startsWith("reject") ||

clientName.startsWith("peer") || clientName.startsWith("peername") ||

clientName.startsWith("giveup") || clientName.startsWith("youwin") ||

clientName.startsWith("所有人"))

{

message="无效命令";

Feedback(message);

}

else

{

if(clientNameHash.containsValue(("[inchess]"+(String)clientNameHash.get(clientSocket))))

{

synchronized(clientNameHash)

{

clientNameHash.put((Socket)getHashKey(clientNameHash,("[inchess]"+clientNameHash.get(clientSocket))),

("[inchess]"+clientName));

chessPeerTalk(("[inchess]"+clientName),("/yourname "+("[inchess]"+clientName)));

}

}

else if(chessPeerHash.containsKey(clientNameHash.get(clientSocket)))

{

//游戏客户端改名字

synchronized(clientNameHash)

{

clientNameHash.put((Socket)getHashKey(clientNameHash,("[inchess]"+clientNameHash.get(clientSocket))),

("[inchess]"+clientName));

}

synchronized(chessPeerHash)

{

//chessPeerHash添加新名字映射

chessPeerHash.put(clientName,chessPeerHash.get(clientNameHash.get(clientSocket)));

//chessPeerHash删除旧映射

chessPeerHash.remove(clientNameHash.get(clientSocket));

}

//向游戏客户端发送新名字

chessPeerTalk(("[inchess]"+clientName),("/yourname "+("[inchess]"+clientName)));

//向peer游戏客户端发送

chessPeerTalk((String)chessPeerHash.get(clientName),("/peer "+"[inchess]"+clientName));

}

else if(chessPeerHash.containsValue(clientNameHash.get(clientSocket)))

{

synchronized(clientNameHash)

{

//游戏客户端改名字

clientNameHash.put((Socket)getHashKey(clientNameHash,("[inchess]"+clientNameHash.get(clientSocket))),

("[inchess]"+clientName));

}

synchronized(chessPeerHash)

{

//chessPeerHash重新映射

chessPeerHash.put((String)getHashKey(chessPeerHash,clientNameHash.get(clientSocket)),clientName);

//向游戏客户端发送新名字

chessPeerTalk(("[inchess]"+clientName),("/yourname "+("[inchess]"+clientName)));

}

//向peer游戏客户端发送

chessPeerTalk((String)getHashKey(chessPeerHash,clientName),("/peer "+"[inchess]"+clientName));

}

message=clientNameHash.get(clientSocket)+"改名为:"+clientName;

synchronized(clientNameHash)

{

clientNameHash.put(clientSocket,clientName);

}

publicTalk(message);

Feedback("/yourname "+(String)clientNameHash.get(clientSocket));

publicTalk(getUserList());

}

}

else if(message.equals("/list"))

{

Feedback(getUserList());

}

else if(message.startsWith("/creatgame [inchess]"))

{

String chessServerName=message.substring(20);

synchronized(clientNameHash)

{

clientNameHash.put(clientSocket,message.substring(11));

}

synchronized(chessPeerHash)

{

chessPeerHash.put(chessServerName,"wait");

}

Feedback("/yourname "+clientNameHash.get(clientSocket));

chessPeerTalk(chessServerName,"/OK");

publicTalk(getUserList());

}

else if(message.startsWith("/joingame "))

{

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

String getUserToken,serverName,selfName;

String[] chessNameOpt={"0","0"};

int getOptNum=0;

while(userToken.hasMoreTokens())

{

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

if(getOptNum>=1 && getOptNum<=2)

{

chessNameOpt[getOptNum-1]=getUserToken;

}

getOptNum++;

}

serverName=chessNameOpt[0];

selfName=chessNameOpt[1];

if(chessPeerHash.containsKey(serverName) && chessPeerHash.get(serverName).equals("wait"))

{

synchronized(clientNameHash)

{

clientNameHash.put(clientSocket,("[inchess]"+selfName));

}

synchronized(chessPeerHash)

{

chessPeerHash.put(serverName,selfName);

}

publicTalk(getUserList());

chessPeerTalk(selfName,("/peer "+"[inchess]"+serverName));

chessPeerTalk(serverName,("/peer "+"[inchess]"+selfName));

}

else

{

chessPeerTalk(selfName,"/reject");

try

{

clientClose();

}

catch(Exception ez)

{

}

}

}

else if(message.startsWith("/[inchess]"))

{

int firstLocation=0,lastLocation;

lastLocation=message.indexOf(" ",0);

peerName=message.substring((firstLocation+1),lastLocation);

message=message.substring((lastLocation+1));

if(chessPeerTalk(peerName,message))

{

Feedback("/error");

}

}

else if(message.startsWith("/giveup "))

{

String chessClientName=message.substring(8);

if(chessPeerHash.containsKey(chessClientName) && !((String)chessPeerHash.get(chessClientName)).equals("wait"))

{

chessPeerTalk((String)chessPeerHash.get(chessClientName),"/youwin");

synchronized(chessPeerHash)

{

chessPeerHash.remove(chessClientName);

}

}

if(chessPeerHash.containsValue(chessClientName))

{

chessPeerTalk((String)getHashKey(chessPeerHash,chessClientName),"/youwin");

synchronized(chessPeerHash)

{

chessPeerHash.remove((String)getHashKey(chessPeerHash,chessClientName));

}

}

}

else

{

int firstLocation=0,lastLocation;

lastLocation=message.indexOf(" ",0);

if(lastLocation==-1)

{

Feedback("无效命令");

return;

}

else

{

peerName=message.substring((firstLocation+1),lastLocation);

message=message.substring((lastLocation+1));

message=(String)clientNameHash.get(clientSocket)+">"+message;

if(peerTalk(peerName,message))

{

Feedback("没有这个用户:"+peerName+"\n");

}

}

}

}

else

{

message=clientNameHash.get(clientSocket)+">"+message;

server.messageBoard.append(message+"\n");

publicTalk(message);

server.messageBoard.setCaretPosition(server.messageBoard.getText().length());

}

}

public void publicTalk(String publicTalkMessage)

{

synchronized(clientDataHash)

{

for(Enumeration enu=clientDataHash.elements();enu.hasMoreElements();)

{

DataOutputStream outData=(DataOutputStream)enu.nextElement();

try

{

outData.writeUTF(publicTalkMessage);

}

catch(IOException es)

{

es.printStackTrace();

}

}

}

}

public boolean peerTalk(String peerTalk,String talkMessage)

{

for(Enumeration enu=clientDataHash.keys();enu.hasMoreElements();)

{

Socket userClient=(Socket)enu.nextElement();

if(peerTalk.equals((String)clientNameHash.get(userClient)) && !peerTalk.equals((String)clientNameHash.get(clientSocket)))

{

synchronized(clientDataHash)

{

DataOutputStream peerOutData=(DataOutputStream)clientDataHash.get(userClient);

try

{

peerOutData.writeUTF(talkMessage);

}

catch(IOException es)

{

es.printStackTrace();

}

}

Feedback(talkMessage);

return(false);

}

else if(peerTalk.equals((String)clientNameHash.get(clientSocket)))

{

Feedback(talkMessage);

return(false);

}

}

return(true);

}

public boolean chessPeerTalk(String chessPeerTalk,String chessTalkMessage)

{

for(Enumeration enu=clientDataHash.keys();enu.hasMoreElements();)

{

Socket userClient=(Socket)enu.nextElement();

if(chessPeerTalk.equals((String)clientNameHash.get(userClient)) && !chessPeerTalk.equals((String)clientNameHash.get(clientSocket)))

{

synchronized(clientDataHash)

{

DataOutputStream peerOutData=(DataOutputStream)clientDataHash.get(userClient);

try

{

peerOutData.writeUTF(chessTalkMessage);

}

catch(IOException es)

{

es.printStackTrace();

}

}

return(false);

}

}

return(true);

}

public void Feedback(String feedbackString)

{

synchronized(clientDataHash)

{

DataOutputStream outData=(DataOutputStream)clientDataHash.get(clientSocket);

try

{

outData.writeUTF(feedbackString);

}

catch(Exception eb)

{

eb.printStackTrace();

}

}

}

public String getUserList()

{

String userList="/userlist";

for(Enumeration enu=clientNameHash.elements();enu.hasMoreElements();)

{

userList=userList+" "+(String)enu.nextElement();

}

return(userList);

}

public Object getHashKey(Hashtable targetHash,Object hashValue)

{

Object hashKey;

for(Enumeration enu=targetHash.keys();enu.hasMoreElements();)

{

hashKey=(Object)enu.nextElement();

if(hashValue.equals((Object)targetHash.get(hashKey)))

return(hashKey);

}

return(null);

}

public void firstCome()

{

publicTalk(getUserList());

Feedback("/yourname "+(String)clientNameHash.get(clientSocket));

Feedback("Java五子棋聊天客户端");

Feedback("/changename <你的名字> --更改名字");

Feedback("/list --更新用户列表");

Feedback("/<用户名> <要说的话> --私聊");

Feedback("注意:用命令的时候,先把谈话的对象定为所有人");

}

public void clientClose()

{

server.messageBoard.append("用户断开:"+clientSocket+"\n");

//如果是游戏客户端主机

synchronized(chessPeerHash)

{

if(chessPeerHash.containsKey(clientNameHash.get(clientSocket)))

{

chessPeerHash.remove((String)clientNameHash.get(clientSocket));

}

if(chessPeerHash.containsValue(clientNameHash.get(clientSocket)))

{

chessPeerHash.put((String)getHashKey(chessPeerHash,(String)clientNameHash.get(clientSocket)),"tobeclosed");

}

}

synchronized(clientDataHash)

{

clientDataHash.remove(clientSocket);

}

synchronized(clientNameHash)

{

clientNameHash.remove(clientSocket);

}

publicTalk(getUserList());

server.statusLabel.setText("当前连接数:"+clientDataHash.size());

try

{

clientSocket.close();

}

catch(IOException exx)

{

}

isClientClosed=true;

}

public void run()

{

DataInputStream inData;

synchronized(clientDataHash)

{

server.statusLabel.setText("当前连接数:"+clientDataHash.size());

}

try

{

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

firstCome();

while(true)

{

String message=inData.readUTF();

messageTransfer(message);

}

}

catch(IOException esx)

{

}

finally

{

if(!isClientClosed)

{

clientClose();

}

}

}

}

public class chessServer extends Frame implements ActionListener

{

Button messageClearButton=new Button("清除显示");

Button serverStatusButton=new Button("服务器状态");

Button serverOffButton=new Button("关闭服务器");

Panel buttonPanel=new Panel();

MessageServer server=new MessageServer();

ServerSocket serverSocket;

Hashtable clientDataHash=new Hashtable(50);

Hashtable clientNameHash=new Hashtable(50);

Hashtable chessPeerHash=new Hashtable(50);

chessServer()

{

super("Java五子棋服务器");

setBackground(Color.pink);

buttonPanel.setLayout(new FlowLayout());

messageClearButton.setSize(60,25);

buttonPanel.add(messageClearButton);

messageClearButton.addActionListener(this);

serverStatusButton.setSize(75,25);

buttonPanel.add(serverStatusButton);

serverStatusButton.addActionListener(this);

serverOffButton.setSize(75,25);

buttonPanel.add(serverOffButton);

serverOffButton.addActionListener(this);

add(server,BorderLayout.CENTER);

add(buttonPanel,BorderLayout.SOUTH);

addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent e)

{

System.exit(0);

}

});

pack();

setVisible(true);

setSize(400,450);

setResizable(false);

validate();

try

{

makeMessageServer(4331,server);

}

catch(Exception e)

{

System.out.println("e");

}

}

public void makeMessageServer(int port,MessageServer server) throws IOException

{

Socket clientSocket;

long clientAccessNumber=1;

this.server=server;

try

{

serverSocket=new ServerSocket(port);

server.messageBoard.setText("服务器开始于:"+serverSocket.getInetAddress().getLocalHost()+":"+serverSocket.getLocalPort()+"\n");

while(true)

{

clientSocket=serverSocket.accept();

server.messageBoard.append("用户连接:"+clientSocket+"\n");

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

clientDataHash.put(clientSocket,outData);

clientNameHash.put(clientSocket,("新来客"+clientAccessNumber++));

ServerThread thread=new ServerThread(clientSocket,clientDataHash,clientNameHash,chessPeerHash,server);

thread.start();

}

}

catch(IOException ex)

{

System.out.println("已经有服务器在运行. \n");

}

}

public void actionPerformed(ActionEvent e)

{

if(e.getSource()==messageClearButton)

{

server.messageBoard.setText("");

}

if(e.getSource()==serverStatusButton)

{

try

{

server.messageBoard.append("服务器信息:"+serverSocket.getInetAddress().getLocalHost()+":"+serverSocket.getLocalPort()+"\n");

}

catch(Exception ee)

{

System.out.println("serverSocket.getInetAddress().getLocalHost() error \n");

}

}

if(e.getSource()==serverOffButton)

{

System.exit(0);

}

}

public static void main(String args[])

{

chessServer chessServer=new chessServer();

}

}

查看本文来源
    • 评论
    • 分享微博
    • 分享邮件
    邮件订阅

    如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。

    重磅专题
    往期文章
    最新文章