五子棋对战实验报告
- 格式:docx
- 大小:792.52 KB
- 文档页数:15
实验项目五子棋网络对战和聊天实验日期 20160406 实验报告要求:
一、实验目的:
学习和使用socket编程,熟练软件开发
二、实验原理:
使用socket进行网络通信,java作为编程语言
三、实验要求:
编写五子棋程序可以实现联机网络对战,并且可以进行聊天
四、实验步骤、结果(程序+注释+截图)及分析:
首先拟定编程语言与开发方案,选择java语言,考虑到java可以跨平台运行,
然后决定把这个程序拆分为客户端、服务器两个部分,每个部分再分成5个小的部分实现不同功能。
1、然后考虑使用java的swing包,创建ClientChessPanel类负责棋盘部分,包括判断输赢,使用数组chesses[i][j]记录棋盘上棋子的分布,对数组进行不同的赋值表示网格节点上无棋、黑棋、白棋;使用playChessHandler作为鼠标单击事件,单击事件调用Clientskt中的函数传送棋子坐标以及输赢信息。drawChess函数画棋子,drawGrids画网格,gameOver判断棋盘棋子分布,输赢情况。
importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
importChatOneToOneClient.Clientskt;
classClientChessPanel extends JPanel{
private static final long serialVersionUID = 1L;
private int space=20; //网格间的距离
private int grids=30; //棋盘的网格数
private int radius=space/2; //棋的半径
Clientsktskt;
//当chesses[i][j]=0,表示网格节点(i,j)上无棋
//当chesses[i][j]=1,表示网格节点(i,j)上放白棋
//当chesses[i][j]=2,表示网格节点(i,j)上放黑棋
privateint[][] chesses=new int[grids+1][grids+1];
private intcurrColor=1; //当前棋的颜色
privateMouseListenerplayChessHandler=new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(skt.reMouseGo()){
int x=e.getX();
int y=e.getY();
//放一颗棋子
if(x<=grids*space && x>=0 && y<=grids*space && y>=0)
if(chesses[round(x)][round(y)]==0){
chesses[round(x)][round(y)]=currColor;
repaint(); //刷新图形
skt.dataout("x:"+String.valueOf(round(x)));
skt.dataout("y:"+String.valueOf(round(y)));
skt.setMouseGo(false);
if(gameOver(currColor)){
skt.dataout("g:你输了");
skt.chat.clientDialog=new ClientMyDialog(skt.chat,"你赢了");
skt.chat.clientDialog.setVisible(true);
}
currColor=currColor==1?2:1; //切换棋子的颜色
}
}
}
};
public int round(float a){ //获得接近a的网格节点坐标
float f=a/space;
returnMath.round(f);
}
publicClientChessPanel(intspace,intgrids,Clientsktskt){
this.space=space;
this.grids=grids;
this.radius=space/2;
this.skt=skt;
setBackground(Color.BLUE);
setSize(space*grids,space*grids);
addMouseListener(playChessHandler);
startChess();
}
public void startChess(){
clearGrids(); //清空棋盘
currColor=1;
repaint(); //刷新图形
}
private void clearGrids(){
for(inti=0;i<=grids;i++)
for(int j=0;j<=grids;j++)
chesses[i][j]=0;
}
//画一颗棋子
private void drawChess(Graphics g,intx,inty,int color){
g.setColor(color==1?Color.GREEN:Color.BLACK);
g.fillOval(x*space-radius,y*space-radius,radius*2,radius*2);
}
//画网格
private void drawGrids(Graphics g){
g.setColor(Color.DARK_GRAY);
for(inti=0;i<=grids;i++){
g.drawLine(0,i*space,grids*space,i*space);
g.drawLine(i*space,0,i*space,grids*space);
}
}
//接收对方下的棋坐标
public void paintChess(intx,int y){
if(x<=grids*space && x>=0 && y<=grids*space && y>=0){ if(chesses[x][y]==0){
chesses[x][y]=currColor;
currColor=currColor==1?2:1; //切换棋子的颜色
skt.setMouseGo(false);
skt.setMouseGo(true);
repaint(); //刷新图形
}
}
}
//判断游戏是否结束
publicbooleangameOver(intgameOver){
int five=0;//用于判断是否有连续5个子
for(inti=0;i for(int j=0;j if(chesses[i][j]==gameOver){ five++; for(int k=1;k<5&&j if(chesses[i][j+k]==gameOver){ five++; if(five==5){ return true; } } else{ five=1; k=5; }