用JAVA设计游戏:五子棋游戏
ChessClient.java:客户端主程序。
ChessInterface.java:客户端的接口。
ChessPad.java:棋盘的绘制。
ChessServer.java:服务器端。
可容纳50人同时在线下棋聊天。
没有详细评论,但是肯定能运行,而且是在j2sdk1.4下通过的。
/*********************************************************************************************
1.chessClient.java
**********************************************************************************************/
导入Java . awt . *;
导入Java . awt . event . *;
导入Java . io . *;
导入Java . net . *;
导入Java . util . *;
类clientThread扩展线程
{
chessClient chessclient
客户端线程(chessClient chessclient)
{
this . chess client = chess client;
}
公共void acceptMessage(字符串recMessage)
{
if(rec message . starts with("/userlist "))
{
string tokenizer user token = new string tokenizer(rec message," ");
int user number = 0;
chess client . user pad . userlist . remove all();
chess client . input pad . user choice . remove all();
ches client . input pad . user choice . addition(" all ");
while(userToken.hasMoreTokens())
{
String user =(String)user token . nexttoken(" ");
if(用户编号& gt0 & amp& amp!user.startsWith("[inchess]")
{
chess client . user pad . userlist . add(用户);
chess client . input pad . user choice . additem(用户);
}
user number++;
}
切斯客户端。input pad . user choice . select(" every one ");
}
else if(rec message . starts with("/your name "))
{
chess client . chess client name = rec message . substring(10);
Chessclient.setTitle("Java五子棋客户端"+"用户名:"+chess client . chess client name);
}
else if(recmessage . equals("/reject "))
{
尝试
{
chess client . ches SPAD . status text . settext("不能加入游戏");
chess client . control pad . cancel game button . set enabled(false);
chess client . control pad . join game button . set enabled(true);
chess client . control pad . creatgamebutton . set enabled(true);
}
捕捉(异常ef)
{
Chesclient。聊天板。chatlanerea . settext(" ches client。切斯巴德。Chessocket.close不能关闭");
}
chess client . control pad . join game button . set enabled(true);
}
else if(rec message . starts with("/peer "))
{
chess client . ches SPAD . ches speername = rec message . substring(6);
if(chessclient.isServer)
{
chess client . chess pad . chess color = 1;
chess client . ches SPAD . ismouseenabled = true;
切斯客户端。切斯巴德。statustext。settext("黑棋拜托");
}
else if(chessclient.isClient)
{
chess client . chess pad . chess color =-1;
切斯客户端。chesspad.statustext.settext("加入游戏,等待对手出牌...");
}
}
else if(recmessage . equals("/you win "))
{
chess client . ison chess = false;
chess client . ches SPAD . ches victory(chess client . ches SPAD . ches color);
切斯客户端。chesspad.statustext.settext("对方退出,请点击放弃游戏,退出连接");
chess client . ches SPAD . ismouseenabled = false;
}
else if(recMessage.equals("/OK "))
{
切斯客户端。chesspad.statustext.settext("游戏创建成功,等待其他人加入...");
}
else if(recmessage . equals("/error "))
{
切斯客户端。chat pad . chatlanerea . append("传输错误:请退出程序重新加入\ n ");
}
其他
{
chess client . chat pad . chatlanea . append(rec message+" \ n ");
chess client . chat pad . chatlanea . setcaretposition(
chess client . chat pad . chatlanea . gettext()。length());
}
}
公共无效运行()
{
字符串消息= " ";
尝试
{
while(真)
{
message = chess client . in . read utf();
acceptMessage(消息);
}
}
捕捉(IOException es)
{
}
}
}
公共类chessClient扩展框架实现ActionListener,KeyListener
{
user pad user pad = new user pad();
chatPad chatPad = new chatPad();
control pad control pad = new control pad();
ches SPAD ches SPAD = new ches SPAD();
input pad input pad = new input pad();
Socket聊天Socket
DataInputStream in
DataOutputStream out
String chessClientName = null
字符串host = null
int port = 4331;
boolean isOnChat = false//聊天?
boolean isOnChess = false//下棋?
boolean isGameConnected = false//下棋的客户端连接?
boolean isServer = false//如果是象棋主持人。
布尔isClient = false//如果是象棋客户端。
Panel south Panel = new Panel();
Panel north Panel = new Panel();
Panel center Panel = new Panel();
Panel west Panel = new Panel();
Panel east Panel = new Panel();
chessClient()
{
超级(“Java五子棋客户端”);
set layout(new BorderLayout());
host = control pad . input tip . gettext();
west panel . set layout(new BorderLayout());
westPanel.add(userpad,BorderLayout。北);
westPanel.add(chatpad,BorderLayout。中心);
west panel . set background(color . pink);
input pad . input words . addkey listener(this);
ches SPAD . host = control pad . input tip . gettext();
centerPanel.add(chesspad,BorderLayout。中心);
centerPanel.add(inputpad,BorderLayout。南);
center panel . set background(color . pink);
control pad . connect button . addactionlistener(this);
control pad . creatgamebutton . addactionlistener(this);
control pad . joingamebutton . addactionlistener(this);
control pad . cancel game button . addactionlistener(this);
control pad . exit game button . addactionlistener(this);
control pad . creatgamebutton . set enabled(false);
control pad . joingamebutton . set enabled(false);
control pad . cancelgamebutton . set enabled(false);
southPanel.add(controlpad,BorderLayout。中心);
south panel . set background(color . pink);
addWindowListener(新WindowAdapter()
{
公共void窗口关闭(WindowEvent e)
{
if(isOnChat)
{
尝试
{
chat socket . close();
}
catch(异常错误)
{
}
}
if(isOnChess || isGameConnected)
{
尝试
{
ches SPAD . chess socket . close();
}
捕捉(异常ee)
{
}
}
system . exit(0);
}
公共无效窗口激活(WindowEvent ea)
{
}
});
add(westPanel,BorderLayout。西);
添加(centerPanel,BorderLayout。中心);
add(southPanel,BorderLayout。南);
pack();
setSize(670,548);
set visible(true);
setResizable(false);
validate();
}
public boolean connectServer(String server IP,int serverPort)抛出异常
{
尝试
{
chatSocket=new Socket(serverIP,server port);
in = new data inputstream(chat socket . getinputstream());
out = new data output stream(chat socket . get output stream());
client thread client thread = new client thread(this);
client thread . start();
isOnChat = true
返回true
}
捕捉(IOException ex)
{
chat pad . chatlanerea . settext("象棋客户端:ConnectServer:无法连接,建议重启程序\ n ");
}
返回false
}
公共无效操作已执行(操作事件e)
{
if(e . getsource()= = control pad . connect button)
{
host = ches pad . host = control pad . input tip . gettext();
尝试
{
if(连接服务器(主机,端口))
{
chat pad . chatlanerea . settext(" ");
control pad . connect button . set enabled(false);
control pad . creatgamebutton . set enabled(true);
control pad . joingamebutton . set enabled(true);
Chesspad.statusText.setText("连接成功,请创建游戏或加入游戏");
}
}
catch(异常ei)
{
chat pad . chatlanerea . settext(" control pad . connect button:无法连接,建议重启程序\ n ");
}
}
if(e . getsource()= = control pad . exit game button)
{
if(isOnChat)
{
尝试
{
chat socket . close();
}
catch(异常错误)
{
}
}
if(isOnChess || isGameConnected)
{
尝试
{
ches SPAD . chess socket . close();
}
捕捉(异常ee)
{
}
}
system . exit(0);
}
if(e . getsource()= = control pad . join game button)
{
string selected user = user pad . userlist . getselecteditem();
if(selected user = = null | | selected user . starts with("[inchess]")| |
selected user . equals(chess client name))
{
Chesspad.statusText.setText("必须先选择有效用户");
}
其他
{
尝试
{
如果(!isGameConnected)
{
if(ches SPAD . connectserver(ches SPAD . host,chesspad.port))
{
isGameConnected = true
isOnChess = true
isClient = true
control pad . creatgamebutton . set enabled(false);
control pad . joingamebutton . set enabled(false);
control pad . cancelgamebutton . set enabled(true);
ches pad . chessthread . sendmessage("/join game "+user pad . userlist . getselecteditem()+" "+chess client name);
}
}
其他
{
isOnChess = true
isClient = true
control pad . creatgamebutton . set enabled(false);
control pad . joingamebutton . set enabled(false);
control pad . cancelgamebutton . set enabled(true);
ches pad . chessthread . sendmessage("/join game "+user pad . userlist . getselecteditem()+" "+chess client name);
}
}
捕捉(异常ee)
{
isGameConnected = false
isOnChess = false
isClient = false
control pad . creatgamebutton . set enabled(true);
control pad . joingamebutton . set enabled(true);
control pad . cancelgamebutton . set enabled(false);
chat pad . chatlanerea . settext(" ches pad . connectserver无法连接\ n "+ee);
}
}
}
if(e . getsource()= = control pad . creatgamebutton)
{
尝试
{
如果(!isGameConnected)
{
if(ches SPAD . connectserver(ches SPAD . host,chesspad.port))
{
isGameConnected = true
isOnChess = true
isServer = true
control pad . creatgamebutton . set enabled(false);
control pad . joingamebutton . set enabled(false);
control pad . cancelgamebutton . set enabled(true);
chess pad . chess thread . sendmessage("/creat game "+"[inchess]"+chess client name);
}
}
其他
{
isOnChess = true
isServer = true
control pad . creatgamebutton . set enabled(false);
control pad . joingamebutton . set enabled(false);
control pad . cancelgamebutton . set enabled(true);
chess pad . chess thread . sendmessage("/creat game "+"[inchess]"+chess client name);
}
}
catch(异常错误代码)
{
isGameConnected = false
isOnChess = false
isServer = false
control pad . creatgamebutton . set enabled(true);
control pad . joingamebutton . set enabled(true);
control pad . cancelgamebutton . set enabled(false);
EC . printstacktrace();
chat pad . chatlanerea . settext(" ches pad . connectserver无法连接\ n "+EC);
}
}
if(e . getsource()= = control pad . cancel game button)
{
if(isOnChess)
{
ches SPAD . chess thread . sendmessage("/give up "+chess client name);
ches SPAD . ches victory(-1 * ches SPAD . ches color);
control pad . creatgamebutton . set enabled(true);
control pad . joingamebutton . set enabled(true);
control pad . cancelgamebutton . set enabled(false);
Chesspad.statusText.setText("请创建游戏或加入游戏");
}
如果(!isOnChess)
{
control pad . creatgamebutton . set enabled(true);
control pad . joingamebutton . set enabled(true);
control pad . cancelgamebutton . set enabled(false);
Chesspad.statusText.setText("请创建游戏或加入游戏");
}
isClient = isServer = false
}
}
公共void按键(按键事件e)
{
TextField input words =(TextField)e . getsource();
if(e.getKeyCode()==KeyEvent。VK _回车)
{
If (inputpad。userchoice.getselecteditem()。equals ("everyone "))
{
尝试
{
out . write utf(input words . gettext());
input words . settext(" ");
}
catch(异常ea)
{
聊天板。chatlinearea.settext("象棋客户端:按键无法连接,建议重新连接\ n ");
user pad . user list . remove all();
input pad . user choice . remove all();
input words . settext(" ");
control pad . connect button . set enabled(true);
}
}
其他
{
尝试
{
out . write utf("/"+input pad . user choice . getselecteditem()+" "+input words . gettext());
input words . settext(" ");
}
catch(异常ea)
{
聊天板。chatlinearea.settext("象棋客户端:按键无法连接,建议重新连接\ n ");
user pad . user list . remove all();
input pad . user choice . remove all();
input words . settext(" ");
control pad . connect button . set enabled(true);
}
}
}
}
公共void键入(KeyEvent e)
{
}
公开无效密钥释放(密钥事件e)
{
}
公共静态void main(String args[])
{
chess client chess client = new chess client();
}
}
/******************************************************************************************
这就是:chessInteface.java。
******************************************************************************************/
导入Java . awt . *;
导入Java . awt . event . *;
导入Java . io . *;
导入Java . net . *;
类用户面板扩展面板
{
List userList =新列表(10);
用户面板()
{
set layout(new BorderLayout());
for(int I = 0;我& lt50;i++)
{
UserList.add(i+")。+“无用户”);
}
add(userList,BorderLayout。中心);
}
}
类别聊天板扩展面板
{
TextArea chatlanerea = new TextArea(",18,30,TextArea。滚动条_垂直_仅);
聊天板()
{
set layout(new BorderLayout());
add(chatlanerea,BorderLayout。中心);
}
}
类别控制面板扩展面板
{
标签IPlabel =新标签(“IP”,标签。左);
TextField input tip = new TextField(" localhost ",10);
Button connectButton =新建按钮(“连接主机”);
button creatgamebutton = new button("构建游戏");
Button joinGameButton=new Button("加入游戏");
button cancelgamebutton = new button("放弃游戏");
Button exitGameButton=new Button("关闭程序");
控制面板()
{
setLayout(新流程布局(流程布局。左));
set background(color . pink);
添加(IPlabel);
add(输入提示);
add(connect button);
add(creatGameButton);
add(joinGameButton);
add(cancelGameButton);
add(exitGameButton);
}
}
类别输入面板扩展面板
{
TextField input words = new TextField(",40);
Choice user Choice = new Choice();
输入面板()
{
setLayout(新流程布局(流程布局。左));
for(int I = 0;我& lt50;i++)
{
Userchoice.addition (I+")。+“无用户”);
}
userChoice.setSize(60,24);
add(user choice);
add(input words);
}
}
/**********************************************************************************************
这就是:chessPad.java。
**********************************************************************************************/
导入Java . awt . *;
导入Java . awt . event . *;
导入Java . io . *;
导入Java . net . *;
导入Java . util . *;
类chessThread扩展线程
{
chessPad chesspad
chessThread
{
this . ches SPAD = ches SPAD;
}
公共void sendMessage(字符串sndMessage)
{
尝试
{
ches SPAD . out data . write utf(snd message);
}
catch(异常ea)
{
system . out . println(" chess thread . sendmessage:"+ea);
}
}
公共void acceptMessage(字符串recMessage)
{
if(rec message . starts with("/chess "))
{
string tokenizer user token = new string tokenizer(rec message," ");
String chessToken
String[] chessOpt={"-1 ","-1 "," 0 " };
int chessOptNum = 0;
while(userToken.hasMoreTokens())
{
chestoken =(String)user token . nexttoken(" ");
if(chessOptNum & gt;=1。& ampchessOptNum & lt=3)
{
chessOpt[chessOptNum-1]= chestoken;
}
chessoptnum++;
}
chess pad . netchesspaint(integer . parse int(chessOpt[0]),integer . parse int(chessOpt[1]),integer . parse int(chessOpt[2]);
}
else if(rec message . starts with("/your name "))
{
ches SPAD . chesselfname = rec message . substring(10);
}
else if(recmessage . equals("/error "))
{
Chesspad.statusText.setText("错误:没有这个用户,请退出程序重新加入");
}
其他
{
//system . out . println(rec message);
}
}
公共无效运行()
{
字符串消息= " ";
尝试
{
while(真)
{
message = ches SPAD . in data . read utf();
acceptMessage(消息);
}
}
捕捉(IOException es)
{
}
}
}
类chessPad扩展面板实现MouseListener、ActionListener
{
int ches point _ x =-1,ches point _ y =-1,ches color = 1;
int chess black _ x[]= new int[200];
int chess black _ y[]= new int[200];
int chess white _ x[]= new int[200];
int chess white _ y[]= new int[200];
int chessBlackCount = 0,chessWhiteCount = 0;
int chessBlackWin = 0,chessWhiteWin = 0;
boolean isMouseEnabled=false,isWin=false,isInGame = false
textfieldstatustext = new textfield("请先连接服务器");
插座chessSocket
DataInputStream inData
DataOutputStream outData
String chessSelfName = null
String chessPeerName = null
字符串host = null
int port = 4331;
chess thread chess thread = new chess thread(this);
切斯巴德()
{
setSize(440,440);
set layout(null);
set background(color . pink);
addmouse listener(this);
add(status text);
statusText.setBounds(40,5,360,24);
status text . set editable(false);
}
public boolean connectServer(String server IP,int ServerPort)抛出异常
{
尝试
{
chessSocket =新套接字(ServerIP,server port);
in data = new data inputstream(chess socket . getinputstream());
out data = new data output stream(chess socket . get output stream());
chess thread . start();
返回true
}
捕捉(IOException ex)
{
Statustext。settext ("chess: connectserver:无法连接\ n ");
}
返回false
}
public void chess victory(int chescorolwin)
{
this . remove all();
for(int I = 0;我& lt= chessBlackCounti++)
{
chess black _ x[I]= 0;
chess black _ y[I]= 0;
}
for(int I = 0;我& lt= chessWhiteCounti++)
{
chess white _ x[I]= 0;
chess white _ y[I]= 0;
}
chesblackcount = 0;
chessWhiteCount = 0;
add(status text);
statusText.setBounds(40,5,360,24);
if(chescorolwin = = 1)
{ chesblackwin++;
StatusText.setText("黑棋胜,黑棋:白棋是"+Chessblack+":"+Chesswhitewin+",重新开始,等待白棋...");
}
else if(chescorolwin = =-1)
{
chesswhitewin++;
StatusText.setText("白棋胜,黑棋:白棋是"+Chessblack+":"+Chesswhitewin+",重新开始,等待黑棋...");
}
}
public void getLocation(int a,int b,int color)
{
if(color==1)
{
chesblack _ x[chesblackcount]= a * 20;
chesblack _ y[chesblackcount]= b * 20;
chesblackcount++;
}
else if(color==-1)
{
chess white _ x[chess white count]= a * 20;
chess white _ y[chess white count]= b * 20;
chesswhitecount++;
}
}
public boolean checkWin(int a,int b,int checkColor)
{
int step=1,chessLink=1,chessLinkTest=1,chess compare = 0;
if(checkColor==1)
{
chess link = 1;
for(step = 1;步骤& lt=4;step++)
{
for(chescompare = 0;chessCompare & lt= chessBlackCountchessCompare++)
{
if(((a+step)* 20 = = chess black _ x[chess compare])& amp;& amp((b * 20)= = chess black _ y[chess compare])
{
chess link = chess link+1;
if(chessLink==5)
{
返回(真);
}
}
}
if(chess link = =(chess link test+1))
chess link test++;
其他
打破;
}
for(step = 1;步骤& lt=4;step++)
{
for(chescompare = 0;chessCompare & lt= chessBlackCountchessCompare++)
{
if(((a步)* 20 = = chess black _ x[chess compare])& amp;& amp(b * 20 = = chess black _ y[chess compare])
{
chess link++;
if(chessLink==5)
{
返回(真);
}
}
}
if(chess link = =(chess link test+1))
chess link test++;
其他
打破;
}
chess link = 1;
chess link test = 1;
for(step = 1;步骤& lt=4;step++)
{
for(chescompare = 0;chessCompare & lt= chessBlackCountchessCompare++)
{
if((a* 20 = = chess black _ x[chess compare])& amp;& amp((b+step)* 20 = = chess black _ y[chess compare]))
{