java+五子棋报告(完整版)

发布时间:   来源:文档文库   
字号:

下面的源代码分为4个文件;

(2chessInterface.java:客户端的界面。(3chessPad.java:棋盘的绘制。(4chessServer.java:服务器端。
可同时容纳50个人同时在线下棋,聊天。

publicvoidacceptMessage(StringrecMessage{
if(recMessage.startsWith("/userlist"{
StringTokenizeruserToken=newStringTokenizer(recMessage,"";intuserNumber=0;
chessclient.userpad.userList.removeAll(;chessclient.inputpad.userChoice.removeAll(;chessclient.inputpad.userChoice.addItem("所有人";while(userToken.hasMoreTokens(
{
Stringuser=(StringuserToken.nextToken("";if(userNumber>0&&!user.startsWith("[inchess]"{
chessclient.userpad.userList.add(user;chessclient.inputpad.userChoice.addItem(user;}
userNumber++;
}
chessclient.inputpad.userChoice.select("所有人";}
elseif(recMessage.startsWith("/yourname"{
chessclient.chessClientName=recMessage.substring(10;
chessclient.setTitle("Java五子棋客户端"+"用户名:"+chessclient.chessClientName;}
elseif(recMessage.equals("/reject"{try{
chessclient.chesspad.statusText.setText("不能加入游戏";chessclient.controlpad.cancelGameButton.setEnabled(false;chessclient.controlpad.joinGameButton.setEnabled(true;chessclient.controlpad.creatGameButton.setEnabled(true;



}
catch(Exceptionef{
chessclient.chatpad.chatLineArea.setText("chessclient.chesspad.chessSocket.close无法关闭";
}
chessclient.controlpad.joinGameButton.setEnabled(true;}
elseif(recMessage.startsWith("/peer"{
chessclient.chesspad.chessPeerName=recMessage.substring(6;if(chessclient.isServer
{
chessclient.chesspad.chessColor=1;
chessclient.chesspad.isMouseEnabled=true;
chessclient.chesspad.statusText.setText("请黑棋下子";}
elseif(chessclient.isClient{
chessclient.chesspad.chessColor=-1;
chessclient.chesspad.statusText.setText("已加入游戏,等待对方下子...";}}
elseif(recMessage.equals("/youwin"{
chessclient.isOnChess=false;
chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor;
chessclient.chesspad.statusText.setText("对方退出,请点放弃游戏退出连接";chessclient.chesspad.isMouseEnabled=false;}
elseif(recMessage.equals("/OK"
{
chessclient.chesspad.statusText.setText("创建游戏成功,等待别人加入...";}
elseif(recMessage.equals("/error"{
chessclient.chatpad.chatLineArea.append("传输错误:请退出程序,重新加入\n";}else{
chessclient.chatpad.chatLineArea.append(recMessage+"\n";chessclient.chatpad.chatLineArea.setCaretPosition(chessclient.chatpad.chatLineArea.getText(.length(;



}
}
publicvoidrun({
Stringmessage="";try{
while(true{
message=chessclient.in.readUTF(;acceptMessage(message;}
}
catch(IOExceptiones{}}}
publicclasschessClientextendsFrameimplementsActionListener,KeyListener{
userPaduserpad=newuserPad(;chatPadchatpad=newchatPad(;
controlPadcontrolpad=newcontrolPad(;chessPadchesspad=newchessPad(;inputPadinputpad=newinputPad(;
SocketchatSocket;DataInputStreamin;DataOutputStreamout;StringchessClientName=null;Stringhost=null;
intport=4331;
booleanisOnChat=false;//在聊天?



booleanisOnChess=false;//在下棋?
booleanisGameConnected=false;//下棋的客户端连接?booleanisServer=false;//如果是下棋的主机booleanisClient=false;//如果是下棋的客户端
PanelsouthPanel=newPanel(;PanelnorthPanel=newPanel(;PanelcenterPanel=newPanel(;PanelwestPanel=newPanel(;PaneleastPanel=newPanel(;
chessClient(
{
super("Java五子棋客户端";setLayout(newBorderLayout(;host=controlpad.inputIP.getText(;

westPanel.setLayout(newBorderLayout(;
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(newWindowAdapter(



{
publicvoidwindowClosing(WindowEvente{
if(isOnChat{try{
chatSocket.close(;}
catch(Exceptioned{}
}
if(isOnChess||isGameConnected{try
{
chesspad.chessSocket.close(;}
catch(Exceptionee{
}}
System.exit(0;}
publicvoidwindowActivated(WindowEventea{}};

add(westPanel,BorderLayout.WEST;add(centerPanel,BorderLayout.CENTER;add(southPanel,BorderLayout.SOUTH;
pack(;
setSize(670,548;setVisible(true;setResizable(false;validate(;}



publicbooleanconnectServer(StringserverIP,intserverPortthrowsException{try{
chatSocket=newSocket(serverIP,serverPort;
in=newDataInputStream(chatSocket.getInputStream(;
out=newDataOutputStream(chatSocket.getOutputStream(;
clientThreadclientthread=newclientThread(this;clientthread.start(;isOnChat=true;returntrue;
}
catch(IOExceptionex
{
chatpad.chatLineArea.setText("chessClient:connectServer:无法连接,建议重新启动程序\n";}
returnfalse;}

publicvoidactionPerformed(ActionEvente{
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(Exceptionei
{
chatpad.chatLineArea.setText("controlpad.connectButton:,\n";



}
}
if(e.getSource(==controlpad.exitGameButton{
if(isOnChat{try
{
chatSocket.close(;}
catch(Exceptioned{}}
if(isOnChess||isGameConnected{
try{
chesspad.chessSocket.close(;}
catch(Exceptionee{}}
System.exit(0;}
if(e.getSource(==controlpad.joinGameButton{
StringselectedUser=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(Exceptionee{
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(Exceptionec{
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;}}
publicvoidkeyPressed(KeyEvente{
TextFieldinputWords=(TextFielde.getSource(;

if(e.getKeyCode(==KeyEvent.VK_ENTER{
if(inputpad.userChoice.getSelectedItem(.equals("所有人"{
try{
out.writeUTF(inputWords.getText(;inputWords.setText("";}
catch(Exceptionea
{
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(Exceptionea{



chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接\n";userpad.userList.removeAll(;inputpad.userChoice.removeAll(;inputWords.setText("";
controlpad.connectButton.setEnabled(true;}}}}
publicvoidkeyTyped(KeyEvente{}
publicvoidkeyReleased(KeyEvente{}

publicstaticvoidmain(Stringargs[]{
chessClientchessClient=newchessClient(;}}

/******************************************************************************************下面是:chessInteface.java
******************************************************************************************/
importjava.awt.*;importjava.awt.event.*;importjava.io.*;importjava.net.*;

classuserPadextendsPanel{
ListuserList=newList(10;



userPad(
{
setLayout(newBorderLayout(;
for(inti=0;i<50;i++
{
userList.add(i+"."+"没有用户";}
add(userList,BorderLayout.CENTER;}}
classchatPadextendsPanel{
TextArea
TextArea("",18,30,TextArea.SCROLLBARS_VERTICAL_ONLY;
chatPad({
setLayout(newBorderLayout(;
add(chatLineArea,BorderLayout.CENTER;}}
classcontrolPadextendsPanel{
LabelIPlabel=newLabel("IP",Label.LEFT;
TextFieldinputIP=newTextField("localhost",10;ButtonconnectButton=newButton("连接主机";ButtoncreatGameButton=newButton("建立游戏";ButtonjoinGameButton=newButton("加入游戏";ButtoncancelGameButton=newButton("放弃游戏";ButtonexitGameButton=newButton("关闭程序";
controlPad(
{
setLayout(newFlowLayout(FlowLayout.LEFT;setBackground(Color.pink;

chatLineArea=new



add(IPlabel;add(inputIP;
add(connectButton;add(creatGameButton;add(joinGameButton;add(cancelGameButton;add(exitGameButton;}}
classinputPadextendsPanel{
TextFieldinputWords=newTextField("",40;ChoiceuserChoice=newChoice(;
inputPad({
setLayout(newFlowLayout(FlowLayout.LEFT;for(inti=0;i<50;i++
{
userChoice.addItem(i+"."+"没有用户";}
userChoice.setSize(60,24;add(userChoice;add(inputWords;}}
/**********************************************************************************************下面是:chessPad.java
**********************************************************************************************/importjava.awt.*;importjava.awt.event.*;importjava.io.*;importjava.net.*;importjava.util.*;
classchessThreadextendsThread{
chessPadchesspad;




chessThread(chessPadchesspad{
this.chesspad=chesspad;}

publicvoidsendMessage(StringsndMessage{try{
chesspad.outData.writeUTF(sndMessage;}
catch(Exceptionea{
System.out.println("chessThread.sendMessage:"+ea;}}
publicvoidacceptMessage(StringrecMessage{
if(recMessage.startsWith("/chess"{
StringTokenizeruserToken=newStringTokenizer(recMessage,"";StringchessToken;
String[]chessOpt={"-1","-1","0"};intchessOptNum=0;

while(userToken.hasMoreTokens({
chessToken=(StringuserToken.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];
}
elseif(recMessage.startsWith("/yourname"{



chesspad.chessSelfName=recMessage.substring(10;
}
elseif(recMessage.equals("/error"{
chesspad.statusText.setText("错误:没有这个用户,请退出程序,重新加入";}else
{
//System.out.println(recMessage;}}

publicvoidrun({
Stringmessage="";try{
while(true
{
message=chesspad.inData.readUTF(;acceptMessage(message;}}
catch(IOExceptiones{}}}
classchessPadextendsPanelimplementsMouseListener,ActionListener{
intchessPoint_x=-1,chessPoint_y=-1,chessColor=1;intchessBlack_x[]=newint[200];intchessBlack_y[]=newint[200];intchessWhite_x[]=newint[200];intchessWhite_y[]=newint[200];
intchessBlackCount=0,chessWhiteCount=0;intchessBlackWin=0,chessWhiteWin=0;
booleanisMouseEnabled=false,isWin=false,isInGame=false;



TextFieldstatusText=newTextField("请先连接服务器";
SocketchessSocket;DataInputStreaminData;DataOutputStreamoutData;
StringchessSelfName=null;StringchessPeerName=null;Stringhost=null;intport=4331;
chessThreadchessthread=newchessThread(this;
chessPad({
setSize(440,440;setLayout(null;
setBackground(Color.pink;addMouseListener(this;add(statusText;
statusText.setBounds(40,5,360,24;statusText.setEditable(false;
}
publicbooleanconnectServer(StringServerIP,intServerPortthrowsException{try
{
chessSocket=newSocket(ServerIP,ServerPort;
inData=newDataInputStream(chessSocket.getInputStream(;outData=newDataOutputStream(chessSocket.getOutputStream(;chessthread.start(;returntrue;}
catch(IOExceptionex{
statusText.setText("chessPad:connectServer:无法连接\n";}
returnfalse;}

publicvoidchessVictory(intchessColorWin{



this.removeAll(;
for(inti=0;i<=chessBlackCount;i++{
chessBlack_x[i]=0;chessBlack_y[i]=0;
}
for(inti=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+",重新开局,等待白棋下子...";}
elseif(chessColorWin==-1{
chessWhiteWin++;
statusText.setText("白棋胜,:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待黑棋下子...";}}

publicvoidgetLocation(inta,intb,intcolor{
if(color==1{
chessBlack_x[chessBlackCount]=a*20;chessBlack_y[chessBlackCount]=b*20;chessBlackCount++;}
elseif(color==-1
{
chessWhite_x[chessWhiteCount]=a*20;chessWhite_y[chessWhiteCount]=b*20;



chessWhiteCount++;}}
publicbooleancheckWin(inta,intb,intcheckColor{
intstep=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+1chessLinkTest++;elsebreak;}
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+1chessLinkTest++;elsebreak;}
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+1chessLinkTest++;elsebreak;
}
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+1chessLinkTest++;elsebreak;

&&
&&


}
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+1chessLinkTest++;elsebreak;
}
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+1chessLinkTest++;elsebreak;}
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+1chessLinkTest++;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+1chessLinkTest++;elsebreak;}
}
elseif(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+1chessLinkTest++;elsebreak;}
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+1chessLinkTest++;elsebreak;}
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+1chessLinkTest++;elsebreak;}
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+1chessLinkTest++;elsebreak;}
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+1chessLinkTest++;elsebreak;
}
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+1chessLinkTest++;elsebreak;}
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++;
elsebreak;}
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+1chessLinkTest++;elsebreak;}}
return(false;}

publicvoidpaint(Graphicsg{
for(inti=40;i<=380;i=i+20{
g.drawLine(40,i,400,i;}
g.drawLine(40,400,400,400;for(intj=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;}
publicvoidchessPaint(intchessPoint_a,intchessPoint_b,intcolor{
chessPoint_blackchesspoint_black=newchessPoint_black(this;chessPoint_whitechesspoint_white=newchessPoint_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+""+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+""+chessPoint_b+""+color;
/chess
"+chessPoint_a+"
/chess"+chessPoint_a+"
this.add(chesspoint_black;
chesspoint_black.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16;chessVictory(1;
isMouseEnabled=false;}}
elseif(color==-1&&isMouseEnabled
{
getLocation(chessPoint_a,chessPoint_b,color;isWin=checkWin(chessPoint_a,chessPoint_b,color;if(isWin==false
{
chessthread.sendMessage("/"+chessPeerName+""+chessPoint_b+""+color;

/chess"+chessPoint_a+"


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+""+chessPoint_b+""+color;this.add(chesspoint_white;
chesspoint_white.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16;chessVictory(-1;
isMouseEnabled=false;}}}
publicvoidnetChessPaint(intchessPoint_a,intchessPoint_b,intcolor{
chessPoint_blackchesspoint_black=newchessPoint_black(this;chessPoint_whitechesspoint_white=newchessPoint_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;}}

/chess"+chessPoint_a+"


elseif(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;}}}

publicvoidmousePressed(MouseEvente{
if(e.getModifiers(==InputEvent.BUTTON1_MASK{
chessPoint_x=(inte.getX(;chessPoint_y=(inte.getY(;
inta=(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;}}}
publicvoidmouseReleased(MouseEvente{}publicvoidmouseEntered(MouseEvente{}publicvoidmouseExited(MouseEvente{}publicvoidmouseClicked(MouseEvente{}



publicvoidactionPerformed(ActionEvente{}}
classchessPoint_blackextendsCanvasimplementsMouseListener{
chessPadchesspad=null;chessPoint_black(chessPadp{
setSize(20,20;chesspad=p;
addMouseListener(this;}

publicvoidpaint(Graphicsg{
g.setColor(Color.black;g.fillOval(0,0,14,14;
}
publicvoidmousePressed(MouseEvente{
//if(e.getModifiers(==InputEvent.BUTTON3_MASK//{
//chesspad.remove(this;//chesspad.chessColor=1;//chesspad.text_2.setText("";
//chesspad.text_1.setText("请黑棋下子";//}
}
publicvoidmouseReleased(MouseEvente{}publicvoidmouseEntered(MouseEvente{}publicvoidmouseExited(MouseEvente{}publicvoidmouseClicked(MouseEvente{}}

classchessPoint_whiteextendsCanvasimplementsMouseListener{
chessPadchesspad=null;
chessPoint_white(chessPadp



{
setSize(20,20;
addMouseListener(this;chesspad=p;}

publicvoidpaint(Graphicsg{
g.setColor(Color.white;g.fillOval(0,0,14,14;}
publicvoidmousePressed(MouseEvente{
//if(e.getModifiers(==InputEvent.BUTTON3_MASK//{
//chesspad.remove(this;//chesspad.chessColor=-1;
//chesspad.text_2.setText("请白旗下子";//chesspad.text_1.setText("";//}
}
publicvoidmouseReleased(MouseEvente{}publicvoidmouseEntered(MouseEvente{}publicvoidmouseExited(MouseEvente{}publicvoidmouseClicked(MouseEvente{
//if(e.getClickCount(>=2//chesspad.remove(this;}}

/******************************************************************************************最后是:chessServer.java
*******************************************************************************************/importjava.io.*;importjava.net.*;importjava.awt.*;importjava.util.*;
importjava.awt.event.*;

classMessageServerextendsPanel//implementsActionListener{



TextArea
TextArea("",22,50,TextArea.SCROLLBARS_VERTICAL_ONLY;LabelstatusLabel=newLabel("当前连接数:",Label.LEFT;PanelboardPanel=newPanel(;PanelstatusPanel=newPanel(;
MessageServer({
setSize(350,300;
setBackground(Color.pink;setLayout(newBorderLayout(;
boardPanel.setLayout(newFlowLayout(;boardPanel.setSize(210,210;
statusPanel.setLayout(newBorderLayout(;statusPanel.setSize(210,50;boardPanel.add(messageBoard;
statusPanel.add(statusLabel,BorderLayout.WEST;add(boardPanel,BorderLayout.CENTER;add(statusPanel,BorderLayout.NORTH;}}

classServerThreadextendsThread{
SocketclientSocket;
HashtableclientDataHash;HashtableclientNameHash;HashtablechessPeerHash;MessageServerserver;
booleanisClientClosed=false;
ServerThread(Socket
clientSocket,Hashtable
messageBoard=new
clientDataHash,Hashtable
clientNameHash,HashtablechessPeerHash,MessageServerserver{
this.clientSocket=clientSocket;this.clientDataHash=clientDataHash;this.clientNameHash=clientNameHash;this.chessPeerHash=chessPeerHash;this.server=server;}




publicvoidmessageTransfer(Stringmessage{
StringclientName,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]"+(StringclientNameHash.get(clientSocket{
synchronized(clientNameHash
{
clientNameHash.put((SocketgetHashKey(clientNameHash,("[inchess]"+clientNameHash.get(clientSocket,
("[inchess]"+clientName;
chessPeerTalk(("[inchess]"+clientName,("/yourname"+("[inchess]"+clientName;}}
elseif(chessPeerHash.containsKey(clientNameHash.get(clientSocket{
//游戏客户端改名字
synchronized(clientNameHash
{
clientNameHash.put((SocketgetHashKey(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((StringchessPeerHash.get(clientName,("/peer"+"[inchess]"+clientName;
}
elseif(chessPeerHash.containsValue(clientNameHash.get(clientSocket{
synchronized(clientNameHash{
//游戏客户端改名字
clientNameHash.put((SocketgetHashKey(clientNameHash,("[inchess]"+clientNameHash.get(clientSocket,
("[inchess]"+clientName;}
synchronized(chessPeerHash
{
//chessPeerHash重新映射
chessPeerHash.put((StringgetHashKey(chessPeerHash,clientNameHash.get(clientSocket,clientName;
//向游戏客户端发送新名字
chessPeerTalk(("[inchess]"+clientName,("/yourname"+("[inchess]"+clientName;}
//peer游戏客户端发送
chessPeerTalk((StringgetHashKey(chessPeerHash,clientName,("/peer"+"[inchess]"+clientName;}

message=clientNameHash.get(clientSocket+"改名为:"+clientName;synchronized(clientNameHash{
clientNameHash.put(clientSocket,clientName;



}
publicTalk(message;
Feedback("/yourname"+(StringclientNameHash.get(clientSocket;publicTalk(getUserList(;}
}
elseif(message.equals("/list"{
Feedback(getUserList(;}
elseif(message.startsWith("/creatgame[inchess]"{
StringchessServerName=message.substring(20;synchronized(clientNameHash
{
clientNameHash.put(clientSocket,message.substring(11;}
synchronized(chessPeerHash{
chessPeerHash.put(chessServerName,"wait";}
Feedback("/yourname"+clientNameHash.get(clientSocket;chessNameOpt[getOptNum-1]=getUserToken;}
getOptNum++;
chessPeerHash.put(serverName,selfName;}
publicTalk(getUserList(;
chessPeerTalk(selfName,("/peer"+"[inchess]"+serverName;chessPeerTalk(serverName,("/peer"+"[inchess]"+selfName;}else
{
chessPeerTalk(selfName,"/reject";try
{
clientClose(;}
catch(Exceptionez{}}



}
elseif(message.startsWith("/[inchess]"{
intfirstLocation=0,lastLocation;
lastLocation=message.indexOf("",0;
peerName=message.substring((firstLocation+1,lastLocation;message=message.substring((lastLocation+1;if(chessPeerTalk(peerName,message{
Feedback("/error";}}
elseif(message.startsWith("/giveup"{
StringchessClientName=message.substring(8;if(chessPeerHash.containsKey(chessClientName
&&!((StringchessPeerHash.get(chessClientName.equals("wait"{
chessPeerTalk((StringchessPeerHash.get(chessClientName,"/youwin";synchronized(chessPeerHash{
chessPeerHash.remove(chessClientName;}
}
if(chessPeerHash.containsValue(chessClientName
{
chessPeerTalk((StringgetHashKey(chessPeerHash,chessClientName,"/youwin";synchronized(chessPeerHash
{
chessPeerHash.remove((StringgetHashKey(chessPeerHash,chessClientName;}}}else{

intfirstLocation=0,lastLocation;
lastLocation=message.indexOf("",0;if(lastLocation==-1{
Feedback("无效命令";



return;
}else{
peerName=message.substring((firstLocation+1,lastLocation;message=message.substring((lastLocation+1;
message=(StringclientNameHash.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(;}}

publicvoidpublicTalk(StringpublicTalkMessage{
synchronized(clientDataHash{
for(Enumerationenu=clientDataHash.elements(;enu.hasMoreElements(;{
DataOutputStreamoutData=(DataOutputStreamenu.nextElement(;try{
outData.writeUTF(publicTalkMessage;}
catch(IOExceptiones



{
es.printStackTrace(;}}}}
publicbooleanpeerTalk(StringpeerTalk,StringtalkMessage{

for(Enumerationenu=clientDataHash.keys(;enu.hasMoreElements(;{
SocketuserClient=(Socketenu.nextElement(;

if(peerTalk.equals((StringclientNameHash.get(userClient
&&!peerTalk.equals((StringclientNameHash.get(clientSocket{
synchronized(clientDataHash
{
DataOutputStreampeerOutData=(DataOutputStreamclientDataHash.get(userClient;try{
peerOutData.writeUTF(talkMessage;}
catch(IOExceptiones{
es.printStackTrace(;}}
Feedback(talkMessage;return(false;
}
elseif(peerTalk.equals((StringclientNameHash.get(clientSocket{
Feedback(talkMessage;return(false;}}

return(true;




}
publicbooleanchessPeerTalk(StringchessPeerTalk,StringchessTalkMessage{
for(Enumerationenu=clientDataHash.keys(;enu.hasMoreElements(;{
SocketuserClient=(Socketenu.nextElement(;
if(chessPeerTalk.equals((StringclientNameHash.get(userClient&&!chessPeerTalk.equals((StringclientNameHash.get(clientSocket{
synchronized(clientDataHash{
DataOutputStreampeerOutData=(DataOutputStreamclientDataHash.get(userClient;try{
peerOutData.writeUTF(chessTalkMessage;}
catch(IOExceptiones{
es.printStackTrace(;}
}
return(false;}}
return(true;}

publicvoidFeedback(StringfeedbackString{
synchronized(clientDataHash{
DataOutputStreamoutData=(DataOutputStreamclientDataHash.get(clientSocket;try
{
outData.writeUTF(feedbackString;}
catch(Exceptioneb{



eb.printStackTrace(;}}}

publicStringgetUserList({
StringuserList="/userlist";
for(Enumerationenu=clientNameHash.elements(;enu.hasMoreElements(;{
userList=userList+""+(Stringenu.nextElement(;}
return(userList;}

publicObjectgetHashKey(HashtabletargetHash,ObjecthashValue{
ObjecthashKey;
for(Enumerationenu=targetHash.keys(;enu.hasMoreElements(;{
hashKey=(Objectenu.nextElement(;
if(hashValue.equals((ObjecttargetHash.get(hashKeyreturn(hashKey;}
return(null;}
publicvoidfirstCome({
publicTalk(getUserList(;
Feedback("/yourname"+(StringclientNameHash.get(clientSocket;Feedback("Java五子棋聊天客户端";
Feedback("/changename<你的名字>--更改名字";Feedback("/list--更新用户列表";
Feedback("/<用户名><要说的话>--私聊";
Feedback("注意:用命令的时候,先把谈话的对象定为所有人";}




publicvoidclientClose({
server.messageBoard.append("用户断开:"+clientSocket+"\n";//如果是游戏客户端主机synchronized(chessPeerHash{
if(chessPeerHash.containsKey(clientNameHash.get(clientSocket{
chessPeerHash.remove((StringclientNameHash.get(clientSocket;}
if(chessPeerHash.containsValue(clientNameHash.get(clientSocket
{
chessPeerHash.put((StringgetHashKey(chessPeerHash,(StringclientNameHash.get(clientSocket,"tobeclosed";}
}
synchronized(clientDataHash{
clientDataHash.remove(clientSocket;}
synchronized(clientNameHash{
clientNameHash.remove(clientSocket;}
publicTalk(getUserList(;
server.statusLabel.setText("当前连接数:"+clientDataHash.size(;try{
clientSocket.close(;}
catch(IOExceptionexx{}

isClientClosed=true;}

publicvoidrun(
{
DataInputStreaminData;
synchronized(clientDataHash



{
server.statusLabel.setText("当前连接数:"+clientDataHash.size(;}try{
inData=newDataInputStream(clientSocket.getInputStream(;firstCome(;while(true{
Stringmessage=inData.readUTF(;messageTransfer(message;}
}
catch(IOExceptionesx{}
finally{
if(!isClientClosed{
clientClose(;}}}}

publicclasschessServerextendsFrameimplementsActionListener{
ButtonmessageClearButton=newButton("清除显示";ButtonserverStatusButton=newButton("服务器状态";ButtonserverOffButton=newButton("关闭服务器";PanelbuttonPanel=newPanel(;
MessageServerserver=newMessageServer(;ServerSocketserverSocket;
HashtableclientDataHash=newHashtable(50;



HashtableclientNameHash=newHashtable(50;HashtablechessPeerHash=newHashtable(50;
chessServer({
super("Java五子棋服务器";setBackground(Color.pink;
buttonPanel.setLayout(newFlowLayout(;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(newWindowAdapter({
publicvoidwindowClosing(WindowEvente{
System.exit(0;}};
pack(;
setVisible(true;setSize(400,450;setResizable(false;validate(;try{
makeMessageServer(4331,server;}
catch(Exceptione{
System.out.println("e";}}




publicvoidmakeMessageServer(intport,MessageServerserverthrowsIOException{
SocketclientSocket;
longclientAccessNumber=1;this.server=server;try{
serverSocket=newServerSocket(port;server.messageBoard.setText("
while(true
{
clientSocket=serverSocket.accept(;
server.messageBoard.append("用户连接:"+clientSocket+"\n";
DataOutputStreamoutData=newDataOutputStream(clientSocket.getOutputStream(;
clientDataHash.put(clientSocket,outData;
clientNameHash.put(clientSocket,("新来客"+clientAccessNumber++;
ServerThreadthread=newServerThread(clientSocket,clientDataHash,clientNameHash,chessPeerHash,server;
thread.start(;}}
catch(IOExceptionex
{
System.out.println("已经有服务器在运行.\n";}}
publicvoidactionPerformed(ActionEvente{
if(e.getSource(==messageClearButton{
server.messageBoard.setText("";}
if(e.getSource(==serverStatusButton


:"+serverSocket.getInetAddress(.getLocalHost(+":"+serverSocket.getLocalPort(+"\n";


{
try{
server.messageBoard.append(":"+serverSocket.getInetAddress(.getLocalHost(+":"+serverSocket.getLocalPort(+"\n";}
catch(Exceptionee
{
System.out.println("serverSocket.getInetAddress(.getLocalHost(error\n";}}
if(e.getSource(==serverOffButton{
System.exit(0;}}

publicstaticvoidmain(Stringargs[]{
chessServerchessServer=newchessServer(;}}


本文来源:https://www.2haoxitong.net/k/doc/b18956b665ce0508763213f4.html

《java+五子棋报告(完整版).doc》
将本文的Word文档下载到电脑,方便收藏和打印
推荐度:
点击下载文档

文档为doc格式