导航:首页 > 源码编译 > java网络五子棋源码

java网络五子棋源码

发布时间:2022-12-27 00:29:53

java五子棋源代码判断输赢,希望帮忙指出错误并完善

可以建立一个二维数组的数据结构:
int[][] ISFIVE = {
{2,2,1,1,1,1,1,2,2},
{1,1,1,1,1,2,2,2,2},
{2,1,1,1,1,1,2,2,2},
{2,2,2,1,1,1,1,1,2},
{2,2,2,2,1,1,1,1,1}
};
中间那个就是目前下子的位置,1表示和目前子相同颜色,2表示任意。0表示必须是空子,才合格,比如
int[][] ISFOUR = { {0,1,1,1,1,0,2,2,2},
{2,0,1,1,1,1,0,2,2},
{2,2,0,1,1,1,1,0,2},
{2,2,2,0,1,1,1,1,0}

};以上的二维数组中的数组都是属于活四,必胜棋型了。按照这个方法可以描绘出所有棋型。
关于你说的斜线部分,其实变通一下,就是数组的旋转而已,比如X,Y是当前落子的坐标,它的横向 就是 int[] temp= new int[9];
for(int i=-4;i<=4;i++){
temp[i+4] = qipan[x+i][y];
}
纵向就是
for(int i=-4;i<=4;i++){
temp[i+4] = qipan[x][y+i];
}
其实规律可以加入方向因子来解决,p,q的值为[1,0]表横向,[0.1]表纵向,[1,1]和[-1,-1]表两个斜向。
for(int i = -4;i<=4;i++){
temp[i+4] = qipan[x+p*i][y+p*i]
}
这个temp数组和上面的二维数组比较,合格就是那个棋型,就能得到4个走向的棋型。我的思路大致是这样,具体AI的设计就不一一细说了。

Ⅱ 求五子棋的Java课程设计

呵呵,代码自己测试:

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.awt.Color;

public class enzit extends Applet implements ActionListener,MouseListener,MouseMotionListener,ItemListener
{
int color_Qizi=0;//旗子的颜色标识 0:白子 1:黑子
int intGame_Start=0;//游戏开始标志 0未开始 1游戏中
int intGame_Body[][]=new int[16][16]; //设置棋盘棋子状态 0 无子 1 白子 2 黑子

Button b1=new Button("游戏开始");
Button b2=new Button("重置游戏");
Label lblWin=new Label(" ");
Checkbox ckbHB[]=new Checkbox[2];
CheckboxGroup ckgHB=new CheckboxGroup();
public void init()
{
setLayout(null);

addMouseListener(this);
add(b1);
b1.setBounds(330,50,80,30);
b1.addActionListener(this);
add(b2);
b2.setBounds(330,90,80,30);
b2.addActionListener(this);
ckbHB[0]=new Checkbox("白子先",ckgHB,false);
ckbHB[0].setBounds(320,20,60,30);
ckbHB[1]=new Checkbox("黑子先",ckgHB,false);
ckbHB[1].setBounds(380,20,60,30);
add(ckbHB[0]);
add(ckbHB[1]);
ckbHB[0].addItemListener(this);
ckbHB[1].addItemListener(this);
add(lblWin);
lblWin.setBounds(330,130,80,30);

Game_start_csh();
}

public void itemStateChanged(ItemEvent e)
{
if (ckbHB[0].getState()) //选择黑子先还是白子先
{
color_Qizi=0;
}
else
{
color_Qizi=1;
}
}

public void actionPerformed(ActionEvent e)
{
Graphics g=getGraphics();
if (e.getSource()==b1)
{
Game_start();
}
else
{
Game_re();
}
}

public void mousePressed(MouseEvent e){}

public void mouseClicked(MouseEvent e)
{
Graphics g=getGraphics();
int x1,y1;
x1=e.getX();
y1=e.getY();
if (e.getX()<20 || e.getX()>300 || e.getY()<20 || e.getY()>300)
{
return;
}

if (x1%20>10)
{
x1+=20;
}

if(y1%20>10)
{
y1+=20;
}

x1=x1/20*20;
y1=y1/20*20;
set_Qizi(x1,y1);

}

public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseDragged(MouseEvent e){}
public void mouseMoved(MouseEvent e){}

public void paint(Graphics g)
{
draw_qipan(g);
}

public void set_Qizi(int x,int y) //落子
{
if (intGame_Start==0) //判断游戏未开始
{
return;
}

if (intGame_Body[x/20][y/20]!=0)
{
return;
}
Graphics g=getGraphics();

if (color_Qizi==1)//判断黑子还是白子
{
g.setColor(Color.black);
color_Qizi=0;
}
else
{
g.setColor(Color.white);
color_Qizi=1;
}

g.fillOval(x-10,y-10,20,20);

intGame_Body[x/20][y/20]=color_Qizi+1;

if (Game_win_1(x/20,y/20)) //判断输赢
{
lblWin.setText(Get_qizi_color(color_Qizi)+"赢了!");
intGame_Start=0;
}

if (Game_win_2(x/20,y/20)) //判断输赢
{
lblWin.setText(Get_qizi_color(color_Qizi)+"赢了!");
intGame_Start=0;
}

if (Game_win_3(x/20,y/20)) //判断输赢
{
lblWin.setText(Get_qizi_color(color_Qizi)+"赢了!");
intGame_Start=0;
}

if (Game_win_4(x/20,y/20)) //判断输赢
{
lblWin.setText(Get_qizi_color(color_Qizi)+"赢了!");
intGame_Start=0;
}
}

public String Get_qizi_color(int x)
{
if (x==0)
{
return "黑子";
}
else
{
return "白子";
}
}

public void draw_qipan(Graphics G) //画棋盘 15*15
{
G.setColor(Color.lightGray);
G.fill3DRect(10,10,300,300,true);
G.setColor(Color.black);
for(int i=1;i<16;i++)
{
G.drawLine(20,20*i,300,20*i);
G.drawLine(20*i,20,20*i,300);
}
}

public void Game_start() //游戏开始
{
intGame_Start=1;
Game_btn_enable(false);
b2.setEnabled(true);
}

public void Game_start_csh() //游戏开始初始化
{
intGame_Start=0;
Game_btn_enable(true);
b2.setEnabled(false);
ckbHB[0].setState(true);

for (int i=0;i<16 ;i++ )
{
for (int j=0;j<16 ;j++ )
{
intGame_Body[i][j]=0;
}
}
lblWin.setText("");
}

public void Game_re() //游戏重新开始
{
repaint();
Game_start_csh();
}

public void Game_btn_enable(boolean e) //设置组件状态
{
b1.setEnabled(e);
b2.setEnabled(e);
ckbHB[0].setEnabled(e);
ckbHB[1].setEnabled(e);
}

public boolean Game_win_1(int x,int y) //判断输赢 横
{
int x1,y1,t=1;
x1=x;
y1=y;

for (int i=1;i<5 ;i++ )
{
if (x1>15)
{
break;
}
if (intGame_Body[x1+i][y1]==intGame_Body[x][y])
{
t+=1;
}
else
{
break;
}

}

for (int i=1;i<5 ;i++ )
{
if (x1<1)
{
break;
}

if(intGame_Body[x1-i][y1]==intGame_Body[x][y])
{
t+=1;
}
else
{
break;
}
}

if (t>4)
{
return true;
}
else
{
return false;
}
}

public boolean Game_win_2(int x,int y) //判断输赢 竖
{
int x1,y1,t=1;
x1=x;
y1=y;

for (int i=1;i<5 ;i++ )
{
if (x1>15)
{
break;
}
if (intGame_Body[x1][y1+i]==intGame_Body[x][y])
{
t+=1;
}
else
{
break;
}

}

for (int i=1;i<5 ;i++ )
{
if (x1<1)
{
break;
}

if(intGame_Body[x1][y1-i]==intGame_Body[x][y])
{
t+=1;
}
else
{
break;
}
}

if (t>4)
{
return true;
}
else
{
return false;
}
}

public boolean Game_win_3(int x,int y) //判断输赢 左斜
{
int x1,y1,t=1;
x1=x;
y1=y;

for (int i=1;i<5 ;i++ )
{
if (x1>15)
{
break;
}
if (intGame_Body[x1+i][y1-i]==intGame_Body[x][y])
{
t+=1;
}
else
{
break;
}

}

for (int i=1;i<5 ;i++ )
{
if (x1<1)
{
break;
}

if(intGame_Body[x1-i][y1+i]==intGame_Body[x][y])
{
t+=1;
}
else
{
break;
}
}

if (t>4)
{
return true;
}
else
{
return false;
}
}

public boolean Game_win_4(int x,int y) //判断输赢 左斜
{
int x1,y1,t=1;
x1=x;
y1=y;

for (int i=1;i<5 ;i++ )
{
if (x1>15)
{
break;
}
if (intGame_Body[x1+i][y1+i]==intGame_Body[x][y])
{
t+=1;
}
else
{
break;
}

}

for (int i=1;i<5 ;i++ )
{
if (x1<1)
{
break;
}

if(intGame_Body[x1-i][y1-i]==intGame_Body[x][y])
{
t+=1;
}
else
{
break;
}
}

if (t>4)
{
return true;
}
else
{
return false;
}
}
}

Ⅲ 跪求JAVA五子棋源代码

很sb的电脑五子棋:
import java.io.*;
import java.util.*;

public class Gobang {
// 定义一个二维数组来充当棋盘
private String[][] board;
// 定义棋盘的大小
private static int BOARD_SIZE = 15;

public void initBoard() {
// 初始化棋盘数组
board = new String[BOARD_SIZE][BOARD_SIZE];
// 把每个元素赋为"╋",用于在控制台画出棋盘
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
// windows是一行一行来打印的。坐标值为(行值, 列值)
board[i][j] = "╋";
}
}
}

// 在控制台输出棋盘的方法
public void printBoard() {
// 打印每个数组元素
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
// 打印数组元素后不换行
System.out.print(board[i][j]);
}
// 每打印完一行数组元素后输出一个换行符
System.out.print("\n");
}
}

// 该方法处理电脑下棋:随机生成2个整数,作为电脑下棋的坐标,赋给board数组。
private void compPlay() {
// 构造一个随机数生成器
Random rnd = new Random();
// Random类的nextInt(int n))方法:随机地生成并返回指定范围中的一个 int 值,
// 即:在此随机数生成器序列中 0(包括)和 n(不包括)之间均匀分布的一个int值。
int compXPos = rnd.nextInt(15);
int compYPos = rnd.nextInt(15);
// 保证电脑下的棋的坐标上不能已经有棋子(通过判断对应数组元素只能是"╋"来确定)
while (board[compXPos][compYPos].equals("╋") == false) {
compXPos = rnd.nextInt(15);
compYPos = rnd.nextInt(15);
}
System.out.println(compXPos);
System.out.println(compYPos);
// 把对应的数组元素赋为"○"。
board[compXPos][compYPos] = "○";
}

// 该方法用于判断胜负:进行四次循环扫描,判断横、竖、左斜、右斜是否有5个棋连在一起
private boolean judgeWin() {
// flag表示是否可以断定赢/输
boolean flag = false;
// joinEle:将每一个横/竖/左斜/右斜行中的元素连接起来得到的一个字符串
String joinEle;
// 进行横行扫描
for (int i = 0; i < BOARD_SIZE; i++) {
// 每扫描一行前,将joinEle清空
joinEle = "";
for (int j = 0; j < BOARD_SIZE; j++) {
joinEle += board[i][j];
}
// String类的contains方法:当且仅当该字符串包含指定的字符序列时,返回true。
if (joinEle.contains("●●●●●")) {
System.out.println("您赢啦!");
flag = true;
// 停止往下继续执行,提前返回flag。
// 如果执行了这个return,就直接返回该方法的调用处;
// 不会再执行后面的任何语句,包括最后那个return语句。
// (而break仅仅是完全跳出这个for循环,还会继续执行下面的for循环。)
return flag;
} else if (joinEle.contains("○○○○○")) {
System.out.println("您输啦!");
flag = true;
// 提前返回flag
return flag;
}
}
// 进行竖行扫描
for (int i = 0; i < BOARD_SIZE; i++) {
joinEle = "";
for (int j = 0; j < BOARD_SIZE; j++) {
// 竖行的元素是它们的列值相同
joinEle += board[j][i];
}
if (joinEle.contains("●●●●●")) {
System.out.println("您赢啦!");
flag = true;
return flag;
} else if (joinEle.contains("○○○○○")) {
System.out.println("您输啦!");
flag = true;
return flag;
}
}
// 进行左斜行扫描
for (int i = -(BOARD_SIZE - 2); i < BOARD_SIZE - 1; i++) {
joinEle = "";
for (int j = 0; j < BOARD_SIZE; j++) {
int line = i + j;
// 只截取坐标值没有越界的点
if (line >= 0 && line < 15) {
joinEle += board[j][line];
}
}
if (joinEle.contains("●●●●●")) {
System.out.println("您赢啦!");
flag = true;
return flag;
} else if (joinEle.contains("○○○○○")) {
System.out.println("您输啦!");
flag = true;
return flag;
}
}
// 进行右斜行扫描
for (int i = 1; i < 2 * (BOARD_SIZE - 1); i++) {
joinEle = "";
for (int j = 0; j < BOARD_SIZE; j++) {
int line = i - j;
if (line >= 0 && line < 15) {
joinEle += board[j][line];
}
}
if (joinEle.contains("●●●●●")) {
System.out.println("您赢啦!");
flag = true;
return flag;
} else if (joinEle.contains("○○○○○")) {
System.out.println("您输啦!");
flag = true;
// 最后这个return可省略
}
}
// 确保该方法有返回值(如果上面条件都不满足时)
return flag;
}

public static void main(String[] args) throws Exception, IOException {
Gobang gb = new Gobang();
gb.initBoard();
gb.printBoard();
// BufferedReader类:带缓存的读取器————从字符输入流中读取文本,并缓存字符。可用于高效读取字符、数组和行。
// 最好用它来包装所有其 read() 操作可能开销很高的 Reader(如 FileReader 和 InputStreamReader)。
// 下面构造一个读取器对象。
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 定义输入字符串
String inputStr = null;
// br.readLine():每当在键盘上输入一行内容按回车,刚输入的内容将被br(读取器对象)读取到。
// BufferedReader类的readLine方法:读取一个文本行。
// 初始状态由于无任何输入,br.readLine()会抛出异常。因而main方法要捕捉异常。
while ((inputStr = br.readLine()) != null) {
// 将用户输入的字符串以逗号(,)作为分隔符,分隔成2个字符串。
// String类的split方法,将会返回一个拆分后的字符串数组。
String[] posStrArr = inputStr.split(",");
// 将2个字符串转换成用户下棋的坐标
int xPos = Integer.parseInt(posStrArr[0]);
int yPos = Integer.parseInt(posStrArr[1]);
// 校验用户下棋坐标的有效性,只能是数字,不能超出棋盘范围
if (xPos > 15 || xPos < 1 || yPos > 15 || yPos < 1) {
System.out.println("您下棋的坐标值应在1到15之间,请重新输入!");
continue;
}
// 保证用户下的棋的坐标上不能已经有棋子(通过判断对应数组元素只能是"╋"来确定)
// String类的equals方法:比较字符串和指定对象是否相等。结果返回true或false。
if (gb.board[xPos - 1][yPos - 1].equals("╋")) {
// 把对应的数组元素赋为"●"。
gb.board[xPos - 1][yPos - 1] = "●";
} else {
System.out.println("您下棋的点已有棋子,请重新输入!");
continue;
}
// 电脑下棋
gb.compPlay();
gb.printBoard();
// 每次下棋后,看是否可以断定赢/输了
if (gb.judgeWin() == false) {
System.out.println("请输入您下棋的坐标,应以x,y的格式:");
} else {
// 完全跳出这个while循环,结束下棋
break;
}
}
}
}

Ⅳ 求java编写的五子棋代码,要有电脑AI的

java网络五子棋

下面的源代码分为4个文件;
chessClient.java:客户端主程序。
chessInterface.java:客户端的界面。
chessPad.java:棋盘的绘制。
chessServer.java:服务器端。
可同时容纳50个人同时在线下棋,聊天。
没有加上详细注释,不过绝对可以运行,j2sdk1.4下通过。

/*********************************************************************************************
1.chessClient.java
**********************************************************************************************/

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

class clientThread extends Thread
{
chessClient chessclient;

clientThread(chessClient chessclient)
{
this.chessclient=chessclient;
}

public void acceptMessage(String recMessage)
{
if(recMessage.startsWith("/userlist "))
{
StringTokenizer userToken=new StringTokenizer(recMessage," ");
int userNumber=0;

chessclient.userpad.userList.removeAll();
chessclient.inputpad.userChoice.removeAll();
chessclient.inputpad.userChoice.addItem("所有人");
while(userToken.hasMoreTokens())
{
String user=(String)userToken.nextToken(" ");
if(userNumber>0 && !user.startsWith("[inchess]"))
{
chessclient.userpad.userList.add(user);
chessclient.inputpad.userChoice.addItem(user);
}

userNumber++;
}
chessclient.inputpad.userChoice.select("所有人");
}
else if(recMessage.startsWith("/yourname "))
{
chessclient.chessClientName=recMessage.substring(10);
chessclient.setTitle("Java五子棋客户端 "+"用户名:"+chessclient.chessClientName);
}
else if(recMessage.equals("/reject"))
{
try
{
chessclient.chesspad.statusText.setText("不能加入游戏");
chessclient.controlpad.cancelGameButton.setEnabled(false);
chessclient.controlpad.joinGameButton.setEnabled(true);
chessclient.controlpad.creatGameButton.setEnabled(true);
}
catch(Exception ef)
{
chessclient.chatpad.chatLineArea.setText("chessclient.chesspad.chessSocket.close无法关闭");
}
chessclient.controlpad.joinGameButton.setEnabled(true);
}
else if(recMessage.startsWith("/peer "))
{
chessclient.chesspad.chessPeerName=recMessage.substring(6);
if(chessclient.isServer)
{
chessclient.chesspad.chessColor=1;
chessclient.chesspad.isMouseEnabled=true;
chessclient.chesspad.statusText.setText("请黑棋下子");
}
else if(chessclient.isClient)
{
chessclient.chesspad.chessColor=-1;
chessclient.chesspad.statusText.setText("已加入游戏,等待对方下子...");
}

}
else if(recMessage.equals("/youwin"))
{
chessclient.isOnChess=false;
chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor);
chessclient.chesspad.statusText.setText("对方退出,请点放弃游戏退出连接");
chessclient.chesspad.isMouseEnabled=false;
}
else if(recMessage.equals("/OK"))
{
chessclient.chesspad.statusText.setText("创建游戏成功,等待别人加入...");
}
else if(recMessage.equals("/error"))
{
chessclient.chatpad.chatLineArea.append("传输错误:请退出程序,重新加入 \n");
}
else
{
chessclient.chatpad.chatLineArea.append(recMessage+"\n");
chessclient.chatpad.chatLineArea.setCaretPosition(
chessclient.chatpad.chatLineArea.getText().length());
}
}

public void run()
{
String message="";
try
{
while(true)
{
message=chessclient.in.readUTF();
acceptMessage(message);
}
}
catch(IOException es)
{
}
}

}

public class chessClient extends Frame implements ActionListener,KeyListener
{
userPad userpad=new userPad();
chatPad chatpad=new chatPad();
controlPad controlpad=new controlPad();
chessPad chesspad=new chessPad();
inputPad inputpad=new inputPad();

Socket chatSocket;
DataInputStream in;
DataOutputStream out;
String chessClientName=null;
String host=null;
int port=4331;

boolean isOnChat=false; //在聊天?
boolean isOnChess=false; //在下棋?
boolean isGameConnected=false; //下棋的客户端连接?
boolean isServer=false; //如果是下棋的主机
boolean isClient=false; //如果是下棋的客户端

Panel southPanel=new Panel();
Panel northPanel=new Panel();
Panel centerPanel=new Panel();
Panel westPanel=new Panel();
Panel eastPanel=new Panel();

chessClient()
{
super("Java五子棋客户端");
setLayout(new BorderLayout());
host=controlpad.inputIP.getText();

westPanel.setLayout(new BorderLayout());
westPanel.add(userpad,BorderLayout.NORTH);
westPanel.add(chatpad,BorderLayout.CENTER);
westPanel.setBackground(Color.pink);

inputpad.inputWords.addKeyListener(this);
chesspad.host=controlpad.inputIP.getText();

centerPanel.add(chesspad,BorderLayout.CENTER);
centerPanel.add(inputpad,BorderLayout.SOUTH);
centerPanel.setBackground(Color.pink);

controlpad.connectButton.addActionListener(this);
controlpad.creatGameButton.addActionListener(this);
controlpad.joinGameButton.addActionListener(this);
controlpad.cancelGameButton.addActionListener(this);
controlpad.exitGameButton.addActionListener(this);

controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(false);

southPanel.add(controlpad,BorderLayout.CENTER);
southPanel.setBackground(Color.pink);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
if(isOnChat)
{
try
{
chatSocket.close();
}
catch(Exception ed)
{
}
}
if(isOnChess || isGameConnected)
{
try
{
chesspad.chessSocket.close();
}
catch(Exception ee)
{
}
}
System.exit(0);
}
public void windowActivated(WindowEvent ea)
{

}
});

add(westPanel,BorderLayout.WEST);
add(centerPanel,BorderLayout.CENTER);
add(southPanel,BorderLayout.SOUTH);

pack();
setSize(670,548);
setVisible(true);
setResizable(false);
validate();
}

public boolean connectServer(String serverIP,int serverPort) throws Exception
{
try
{
chatSocket=new Socket(serverIP,serverPort);
in=new DataInputStream(chatSocket.getInputStream());
out=new DataOutputStream(chatSocket.getOutputStream());

clientThread clientthread=new clientThread(this);
clientthread.start();
isOnChat=true;
return true;
}
catch(IOException ex)
{
chatpad.chatLineArea.setText("chessClient:connectServer:无法连接,建议重新启动程序 \n");
}
return false;
}

public void actionPerformed(ActionEvent e)
{
if(e.getSource()==controlpad.connectButton)
{
host=chesspad.host=controlpad.inputIP.getText();
try
{
if(connectServer(host,port))
{
chatpad.chatLineArea.setText("");
controlpad.connectButton.setEnabled(false);
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
chesspad.statusText.setText("连接成功,请创建游戏或加入游戏");
}

}
catch(Exception ei)
{
chatpad.chatLineArea.setText("controlpad.connectButton:无法连接,建议重新启动程序 \n");
}
}
if(e.getSource()==controlpad.exitGameButton)
{
if(isOnChat)
{
try
{
chatSocket.close();
}
catch(Exception ed)
{
}
}
if(isOnChess || isGameConnected)
{
try
{
chesspad.chessSocket.close();
}
catch(Exception ee)
{
}
}
System.exit(0);

}
if(e.getSource()==controlpad.joinGameButton)
{
String selectedUser=userpad.userList.getSelectedItem();
if(selectedUser==null || selectedUser.startsWith("[inchess]") ||
selectedUser.equals(chessClientName))
{
chesspad.statusText.setText("必须先选定一个有效用户");
}
else
{
try
{
if(!isGameConnected)
{
if(chesspad.connectServer(chesspad.host,chesspad.port))
{
isGameConnected=true;
isOnChess=true;
isClient=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName);
}
}
else
{
isOnChess=true;
isClient=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName);
}

}
catch(Exception ee)
{
isGameConnected=false;
isOnChess=false;
isClient=false;
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"+ee);
}

}
}
if(e.getSource()==controlpad.creatGameButton)
{
try
{
if(!isGameConnected)
{
if(chesspad.connectServer(chesspad.host,chesspad.port))
{
isGameConnected=true;
isOnChess=true;
isServer=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName);
}
}
else
{
isOnChess=true;
isServer=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName);
}
}
catch(Exception ec)
{
isGameConnected=false;
isOnChess=false;
isServer=false;
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
ec.printStackTrace();
chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"+ec);
}

}
if(e.getSource()==controlpad.cancelGameButton)
{
if(isOnChess)
{
chesspad.chessthread.sendMessage("/giveup "+chessClientName);
chesspad.chessVictory(-1*chesspad.chessColor);
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chesspad.statusText.setText("请建立游戏或者加入游戏");
}
if(!isOnChess)
{
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chesspad.statusText.setText("请建立游戏或者加入游戏");
}
isClient=isServer=false;
}

}

public void keyPressed(KeyEvent e)
{
TextField inputWords=(TextField)e.getSource();

if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
if(inputpad.userChoice.getSelectedItem().equals("所有人"))
{
try
{
out.writeUTF(inputWords.getText());
inputWords.setText("");
}
catch(Exception ea)
{
chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n");
userpad.userList.removeAll();
inputpad.userChoice.removeAll();
inputWords.setText("");
controlpad.connectButton.setEnabled(true);
}
}
else
{
try
{
out.writeUTF("/"+inputpad.userChoice.getSelectedItem()+" "+inputWords.getText());
inputWords.setText("");
}
catch(Exception ea)
{
chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n");
userpad.userList.removeAll();
inputpad.userChoice.removeAll();
inputWords.setText("");
controlpad.connectButton.setEnabled(true);
}
}
}

}

public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}

public static void main(String args[])
{
chessClient chessClient=new chessClient();
}
}

/******************************************************************************************
下面是:chessInteface.java
******************************************************************************************/

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

class userPad extends Panel
{
List userList=new List(10);

userPad()
{
setLayout(new BorderLayout());

for(int i=0;i<50;i++)
{
userList.add(i+"."+"没有用户");
}
add(userList,BorderLayout.CENTER);

}

}

class chatPad extends Panel
{
TextArea chatLineArea=new TextArea("",18,30,TextArea.SCROLLBARS_VERTICAL_ONLY);

chatPad()
{
setLayout(new BorderLayout());

add(chatLineArea,BorderLayout.CENTER);
}

}

class controlPad extends Panel
{
Label IPlabel=new Label("IP",Label.LEFT);
TextField inputIP=new TextField("localhost",10);
Button connectButton=new Button("连接主机");
Button creatGameButton=new Button("建立游戏");
Button joinGameButton=new Button("加入游戏");
Button cancelGameButton=new Button("放弃游戏");
Button exitGameButton=new Button("关闭程序");

controlPad()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
setBackground(Color.pink);

add(IPlabel);
add(inputIP);
add(connectButton);
add(creatGameButton);
add(joinGameButton);
add(cancelGameButton);
add(exitGameButton);
}

}

class inputPad extends Panel
{
TextField inputWords=new TextField("",40);
Choice userChoice=new Choice();

inputPad()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
for(int i=0;i<50;i++)
{
userChoice.addItem(i+"."+"没有用户");
}
userChoice.setSize(60,24);
add(userChoice);
add(inputWords);
}
}

/**********************************************************************************************
下面是:chessPad.java
**********************************************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

class chessThread extends Thread
{
chessPad chesspad;

chessThread(chessPad chesspad)
{
this.chesspad=chesspad;
}

public void sendMessage(String sndMessage)
{
try
{
chesspad.outData.writeUTF(sndMessage);
}
catch(Exception ea)
{
System.out.println("chessThread.sendMessage:"+ea);
}
}

public void acceptMessage(String recMessage)
{
if(recMessage.startsWith("/chess "))
{
StringTokenizer userToken=new StringTokenizer(recMessage," ");
String chessToken;
String[] chessOpt={"-1","-1","0"};
int chessOptNum=0;

while(userToken.hasMoreTokens())
{
chessToken=(String)userToken.nextToken(" ");
if(chessOptNum>=1 && chessOptNum<=3)
{
chessOpt[chessOptNum-1]=chessToken;

}
chessOptNum++;
}
chesspad.netChessPaint(Integer.parseInt(chessOpt[0]),Integer.parseInt(chessOpt[1]),Integer.parseInt(chessOpt[2]));

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

public void run()
{
String message="";
try
{
while(true)
{
message=chesspad.inData.readUTF();
acceptMessage(message);
}
}
catch(IOException es)
{
}
}

}

class chessPad extends Panel implements MouseListener,ActionListener
{
int chessPoint_x=-1,chessPoint_y=-1,chessColor=1;
int chessBlack_x[]=new int[200];
int chessBlack_y[]=new int[200];
int chessWhite_x[]=new int[200];
int chessWhite_y[]=new int[200];
int chessBlackCount=0,chessWhiteCount=0;
int chessBlackWin=0,chessWhiteWin=0;
boolean isMouseEnabled=false,isWin=false,isInGame=false;
TextField statusText=new TextField("请先连接服务器");

Socket chessSocket;
DataInputStream inData;
DataOutputStream outData;

String chessSelfName=null;
String chessPeerName=null;
String host=null;
int port=4331;
chessThread chessthread=new chessThread(this);

chessPad()
{
setSize(440,440);
setLayout(null);
setBackground(Color.pink);
addMouseListener(this);
add(statusText);
statusText.setBounds(40,5,360,24);
statusText.setEditable(false);
}

public boolean connectServer(String ServerIP,int ServerPort) throws Exception
{
try
{
chessSocket=new Socket(ServerIP,ServerPort);
inData=new DataInputStream(chessSocket.getInputStream());
outData=new DataOutputStream(chessSocket.getOutputStream());
chessthread.start();
return true;
}
catch(IOException ex)
{
statusText.setText("chessPad:connectServer:无法连接 \n");
}
return false;
}

public void chessVictory(int chessColorWin)
{
this.removeAll();
for(int i=0;i<=chessBlackCount;i++)
{
chessBlack_x[i]=0;
chessBlack_y[i]=0;
}
for(int i=0;i<=chessWhiteCount;i++)
{
chessWhite_x[i]=0;
chessWhite_y[i]=0;
}
chessBlackCount=0;
chessWhiteCount=0;
add(statusText);
statusText.setBounds(40,5,360,24);

if(chessColorWin==1)
{ chessBlackWin++;
statusText.setText("黑棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待白棋下子...");
}
else if(chessColorWin==-1)
{
chessWhiteWin++;
statusText.setText("白棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待黑棋下子...");
}
}

public void getLocation(int a,int b,int color)
{

if(color==1)
{
chessBlack_x[chessBlackCount]=a*20;
chessBlack_y[chessBlackCount]=b*20;
chessBlackCount++;
}
else if(color==-1)
{
chessWhite_x[chessWhiteCount]=a*20;
chessWhite_y[chessWhiteCount]=b*20;
chessWhiteCount++;
}
}

public boolean checkWin(int a,int b,int checkColor)
{
int step=1,chessLink=1,chessLinkTest=1,chessCompare=0;
if(checkColor==1)
{
chessLink=1;
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a+step)*20==chessBlack_x[chessCompare]) && ((b*20)==chessBlack_y[chessCompare]))
{
chessLink=chessLink+1;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a-step)*20==chessBlack_x[chessCompare]) && (b*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
chessLink=1;
chessLinkTest=1;
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if((a*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if((a*20==chessBlack_x[chessCompare]) && ((b-step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
chessLink=1;
chessLinkTest=1;
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a-step)*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a+step)*20==chessBlack_x[chessCompare]) && ((b-step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
chessLink=1;
chessLinkTest=1;
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a+step)*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a-step)*20==chessBlack_x[chessCompare]) && ((b-step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}

Ⅳ JAVA设计的五子棋源程序

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
import java.util.*;
class PaintPanel extends JPanel {
ArrayList Items = new ArrayList();

public PaintPanel() {
setLayout(new BorderLayout());
ButtonPanel buttonPanel = new ButtonPanel();
add(buttonPanel, BorderLayout.SOUTH);
addMouseListener(new MouseHandler());
}

public void paintComponent(Graphics g) {
int startX = 50;
int startY = 50;
boolean isMy = false;
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;

for(int i=0; i<16; i++) {
g2.draw(new Line2D.Double(startX, startY+20*i, startX+300, startY+20*i));
g2.draw(new Line2D.Double(startX+20*i, startY, startX+20*i, startY+300));
}
for(int i=0; i<Items.size(); i++) {
isMy = !isMy;
if(isMy)
g2.setColor(Color.BLACK);
else
g2.setColor(Color.WHITE);
g2.fill((Ellipse2D)Items.get(i));
}
}
void myRepaint() {
repaint();
}
private class MouseHandler extends MouseAdapter {
public void mousePressed(MouseEvent event) {
int x = event.getX();
int y = event.getY();
paintItem(x, y);
repaint();
}
void paintItem(int x, int y) {
if(x > 50 && x < 350 && y >50 && y < 350) {
int X = x / 20;
int Y = y / 20;
int centerX = X*20 + 10;
int centerY = Y*20 + 10;
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrameFromCenter(centerX, centerY, centerX+8, centerY+8);
Items.add(ellipse);
}
}
}
private class ButtonPanel extends JPanel {
public ButtonPanel() {
JButton reset = new JButton("Reset");
add(reset);
JButton quit = new JButton("Quit");
add(quit);

ResetEvent listenerR = new ResetEvent();
reset.addMouseListener(listenerR);
QuitEvent listenerQ = new QuitEvent();
quit.addMouseListener(listenerQ);
}

private class QuitEvent
extends MouseAdapter {
public void mouseClicked(MouseEvent event) {
System.exit(1);
}
}

private class ResetEvent
extends MouseAdapter {
public void mouseClicked(MouseEvent event) {
Items.clear();
myRepaint();
}
}
}
}

class GameFrame extends JFrame {
public GameFrame() {
setTitle("A Little Game");
setSize(400, 500);
setResizable(false);

PaintPanel panel = new PaintPanel();
getContentPane().add(panel);
}
} public class Game {
public static void main(String[] args) {
GameFrame frame = new GameFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
//有缺陷,需要更加完善

Ⅵ JAVA五子棋程序代码分析(1)

楼主要是觉得看的不舒服可以拷到记事本里看~ import java.applet.*; import java.awt.*; import java.awt.event.*; import java.applet.Applet; import java.awt.Color; //这一段import就不说了,下面要用到的就import进来 public class wuziqi extends Applet implements ActionListener,MouseListener,MouseMotionListener,ItemListener //继承Applet表明是个applet,后面的接口必须要实现每个接口的所有方法 { int color_Qizi=0;//旗子的颜色标识 0:白子 1:黑子 int intGame_Start=0;//游戏开始标志 0未开始 1游戏中 int intGame_Body[][]=new int[16][16]; //设置棋盘棋子状态 0 无子 1 白子 2 黑子 Button b1=new Button("游戏开始"); Button b2=new Button("重置游戏"); //两个按钮 Label lblWin=new Label(" "); //这个label用来显示最后输赢信息的,先留空 Checkbox ckbHB[]=new Checkbox[2]; //用来表明选择黑气或白棋先走的checkbox CheckboxGroup ckgHB=new CheckboxGroup(); //两个checkbox必须放在同一个checkboxgroup里才能做到单选 public void init() //初始化,堆砌界面 { setLayout(null); //不设布局管理器 addMouseListener(this); //将本类作为鼠标事件的接口响应鼠标动作 add(b1); //将事先定义好的第一个按钮添加入界面 b1.setBounds(330,50,80,30); //设置第一个按钮左上角的位置和大小 b1.addActionListener(this); //将本类作为按钮事件的接口响应按钮动作 add(b2); //将事先定义好的第二个按钮添加进去 b2.setBounds(330,90,80,30); /设置第二个按钮左上角的位置和大小 b2.addActionListener(this); //将本类作为按钮事件的接口响应按钮动作 ckbHB[0]=new Checkbox("白子先",ckgHB,false); //new一个checkbox ckbHB[0].setBounds(320,20,60,30); //设置左上角位置和大小 ckbHB[1]=new Checkbox("黑子先",ckgHB,false); //new第二个checkbox ckbHB[1].setBounds(380,20,60,30); //设置左上角位置和大小 add(ckbHB[0]); //将第一个checkbox加入界面 add(ckbHB[1]); //将第二个checkbox加入界面 ckbHB[0].addItemListener(this); //将本类作为其事件接口来响应选中动作 ckbHB[1].addItemListener(this); //将本类作为其事件接口来响应选中动作 add(lblWin); //将标签加入界面 lblWin.setBounds(330,130,80,30); //设置标签的左上角位置和大小 Game_start_csh(); //调用游戏初始化 } public void itemStateChanged(ItemEvent e) //ItemListener接口中的方法,必须要有 { if (ckbHB[0].getState()) //选择黑子先还是白子先 { color_Qizi=0; //白棋先 } else { color_Qizi=1; //黑棋先 } } public void actionPerformed(ActionEvent e) //ActionListener接口中的方法,也是必须的 { Graphics g=getGraphics(); //这句话貌似可以去掉,g是用来画图或者画界面的 if (e.getSource()==b1) //如果动作的来源是第一个按钮 { Game_start(); //游戏开始 } else //否则 { Game_re(); //游戏重新开始 } } public void mousePressed(MouseEvent e){} //MouseListener接口中的方法,用不到所以留个空,但一定要有 public void mouseClicked(MouseEvent e) //鼠标单击时 { Graphics g=getGraphics(); //获得画笔 int x1,y1; x1=e.getX(); //单击处的x坐标 y1=e.getY(); //单击处的y坐标 if (e.getX()<20 || e.getX()>300 || e.getY()<20 || e.getY()>300) //在棋盘范围之外 { return; //则这是不能走棋的,直接返回 } //下面这两个if和两个赋值的作用是将x和y坐标根据舍入原则修改成棋盘上格子的坐标 if (x1%20>10) { x1+=20; } if(y1%20>10) { y1+=20; } x1=x1/20*20; y1=y1/20*20; set_Qizi(x1,y1); //在棋盘上画上一个棋子 } public void mouseEntered(MouseEvent e){} //MouseListener接口中的方法,用不到所以留个空,但一定要有 public void mouseExited(MouseEvent e){} //MouseListener接口中的方法,用不到所以留个空,但一定要有 public void mouseReleased(MouseEvent e){} //MouseListener接口中的方法,用不到所以留个空,但一定要有 public void mouseDragged(MouseEvent e){} //MouseListener接口中的方法,用不到所以留个空,但一定要有 public void mouseMoved(MouseEvent e){} //MouseListener接口中的方法,用不到所以留个空,但一定要有 public void paint(Graphics g) //重绘和applet程序装载的时候会调用这个绘制的过程 { draw_qipan(g); //画棋盘 }

Ⅶ 求一个简单的JAVA五子棋代码!! 网上复制的别来了!

我有一个,刚刚做的。可以实现人机对战,人人对战,悔棋,禁手等操作。机器方主要采用的是a-b剪枝算法。功能很强大,代码很多。

Ⅷ 用JAVA做五子棋源代码

java网络五子棋

下面的源代码分为4个文件;
chessClient.java:客户端主程序。
chessInterface.java:客户端的界面。
chessPad.java:棋盘的绘制。
chessServer.java:服务器端。
可同时容纳50个人同时在线下棋,聊天。
没有加上详细注释,不过绝对可以运行,j2sdk1.4下通过。

/*********************************************************************************************
1.chessClient.java
**********************************************************************************************/

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

class clientThread extends Thread
{
chessClient chessclient;

clientThread(chessClient chessclient)
{
this.chessclient=chessclient;
}

public void acceptMessage(String recMessage)
{
if(recMessage.startsWith("/userlist "))
{
StringTokenizer userToken=new StringTokenizer(recMessage," ");
int userNumber=0;

chessclient.userpad.userList.removeAll();
chessclient.inputpad.userChoice.removeAll();
chessclient.inputpad.userChoice.addItem("所有人");
while(userToken.hasMoreTokens())
{
String user=(String)userToken.nextToken(" ");
if(userNumber>0 && !user.startsWith("[inchess]"))
{
chessclient.userpad.userList.add(user);
chessclient.inputpad.userChoice.addItem(user);
}

userNumber++;
}
chessclient.inputpad.userChoice.select("所有人");
}
else if(recMessage.startsWith("/yourname "))
{
chessclient.chessClientName=recMessage.substring(10);
chessclient.setTitle("Java五子棋客户端 "+"用户名:"+chessclient.chessClientName);
}
else if(recMessage.equals("/reject"))
{
try
{
chessclient.chesspad.statusText.setText("不能加入游戏");
chessclient.controlpad.cancelGameButton.setEnabled(false);
chessclient.controlpad.joinGameButton.setEnabled(true);
chessclient.controlpad.creatGameButton.setEnabled(true);
}
catch(Exception ef)
{
chessclient.chatpad.chatLineArea.setText("chessclient.chesspad.chessSocket.close无法关闭");
}
chessclient.controlpad.joinGameButton.setEnabled(true);
}
else if(recMessage.startsWith("/peer "))
{
chessclient.chesspad.chessPeerName=recMessage.substring(6);
if(chessclient.isServer)
{
chessclient.chesspad.chessColor=1;
chessclient.chesspad.isMouseEnabled=true;
chessclient.chesspad.statusText.setText("请黑棋下子");
}
else if(chessclient.isClient)
{
chessclient.chesspad.chessColor=-1;
chessclient.chesspad.statusText.setText("已加入游戏,等待对方下子...");
}

}
else if(recMessage.equals("/youwin"))
{
chessclient.isOnChess=false;
chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor);
chessclient.chesspad.statusText.setText("对方退出,请点放弃游戏退出连接");
chessclient.chesspad.isMouseEnabled=false;
}
else if(recMessage.equals("/OK"))
{
chessclient.chesspad.statusText.setText("创建游戏成功,等待别人加入...");
}
else if(recMessage.equals("/error"))
{
chessclient.chatpad.chatLineArea.append("传输错误:请退出程序,重新加入 \n");
}
else
{
chessclient.chatpad.chatLineArea.append(recMessage+"\n");
chessclient.chatpad.chatLineArea.setCaretPosition(
chessclient.chatpad.chatLineArea.getText().length());
}
}

public void run()
{
String message="";
try
{
while(true)
{
message=chessclient.in.readUTF();
acceptMessage(message);
}
}
catch(IOException es)
{
}
}

}

public class chessClient extends Frame implements ActionListener,KeyListener
{
userPad userpad=new userPad();
chatPad chatpad=new chatPad();
controlPad controlpad=new controlPad();
chessPad chesspad=new chessPad();
inputPad inputpad=new inputPad();

Socket chatSocket;
DataInputStream in;
DataOutputStream out;
String chessClientName=null;
String host=null;
int port=4331;

boolean isOnChat=false; //在聊天?
boolean isOnChess=false; //在下棋?
boolean isGameConnected=false; //下棋的客户端连接?
boolean isServer=false; //如果是下棋的主机
boolean isClient=false; //如果是下棋的客户端

Panel southPanel=new Panel();
Panel northPanel=new Panel();
Panel centerPanel=new Panel();
Panel westPanel=new Panel();
Panel eastPanel=new Panel();

chessClient()
{
super("Java五子棋客户端");
setLayout(new BorderLayout());
host=controlpad.inputIP.getText();

westPanel.setLayout(new BorderLayout());
westPanel.add(userpad,BorderLayout.NORTH);
westPanel.add(chatpad,BorderLayout.CENTER);
westPanel.setBackground(Color.pink);

inputpad.inputWords.addKeyListener(this);
chesspad.host=controlpad.inputIP.getText();

centerPanel.add(chesspad,BorderLayout.CENTER);
centerPanel.add(inputpad,BorderLayout.SOUTH);
centerPanel.setBackground(Color.pink);

controlpad.connectButton.addActionListener(this);
controlpad.creatGameButton.addActionListener(this);
controlpad.joinGameButton.addActionListener(this);
controlpad.cancelGameButton.addActionListener(this);
controlpad.exitGameButton.addActionListener(this);

controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(false);

southPanel.add(controlpad,BorderLayout.CENTER);
southPanel.setBackground(Color.pink);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
if(isOnChat)
{
try
{
chatSocket.close();
}
catch(Exception ed)
{
}
}
if(isOnChess || isGameConnected)
{
try
{
chesspad.chessSocket.close();
}
catch(Exception ee)
{
}
}
System.exit(0);
}
public void windowActivated(WindowEvent ea)
{

}
});

add(westPanel,BorderLayout.WEST);
add(centerPanel,BorderLayout.CENTER);
add(southPanel,BorderLayout.SOUTH);

pack();
setSize(670,548);
setVisible(true);
setResizable(false);
validate();
}

public boolean connectServer(String serverIP,int serverPort) throws Exception
{
try
{
chatSocket=new Socket(serverIP,serverPort);
in=new DataInputStream(chatSocket.getInputStream());
out=new DataOutputStream(chatSocket.getOutputStream());

clientThread clientthread=new clientThread(this);
clientthread.start();
isOnChat=true;
return true;
}
catch(IOException ex)
{
chatpad.chatLineArea.setText("chessClient:connectServer:无法连接,建议重新启动程序 \n");
}
return false;
}

public void actionPerformed(ActionEvent e)
{
if(e.getSource()==controlpad.connectButton)
{
host=chesspad.host=controlpad.inputIP.getText();
try
{
if(connectServer(host,port))
{
chatpad.chatLineArea.setText("");
controlpad.connectButton.setEnabled(false);
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
chesspad.statusText.setText("连接成功,请创建游戏或加入游戏");
}

}
catch(Exception ei)
{
chatpad.chatLineArea.setText("controlpad.connectButton:无法连接,建议重新启动程序 \n");
}
}
if(e.getSource()==controlpad.exitGameButton)
{
if(isOnChat)
{
try
{
chatSocket.close();
}
catch(Exception ed)
{
}
}
if(isOnChess || isGameConnected)
{
try
{
chesspad.chessSocket.close();
}
catch(Exception ee)
{
}
}
System.exit(0);

}
if(e.getSource()==controlpad.joinGameButton)
{
String selectedUser=userpad.userList.getSelectedItem();
if(selectedUser==null || selectedUser.startsWith("[inchess]") ||
selectedUser.equals(chessClientName))
{
chesspad.statusText.setText("必须先选定一个有效用户");
}
else
{
try
{
if(!isGameConnected)
{
if(chesspad.connectServer(chesspad.host,chesspad.port))
{
isGameConnected=true;
isOnChess=true;
isClient=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName);
}
}
else
{
isOnChess=true;
isClient=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName);
}

}
catch(Exception ee)
{
isGameConnected=false;
isOnChess=false;
isClient=false;
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"+ee);
}

}
}
if(e.getSource()==controlpad.creatGameButton)
{
try
{
if(!isGameConnected)
{
if(chesspad.connectServer(chesspad.host,chesspad.port))
{
isGameConnected=true;
isOnChess=true;
isServer=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName);
}
}
else
{
isOnChess=true;
isServer=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName);
}
}
catch(Exception ec)
{
isGameConnected=false;
isOnChess=false;
isServer=false;
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
ec.printStackTrace();
chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"+ec);
}

}
if(e.getSource()==controlpad.cancelGameButton)
{
if(isOnChess)
{
chesspad.chessthread.sendMessage("/giveup "+chessClientName);
chesspad.chessVictory(-1*chesspad.chessColor);
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chesspad.statusText.setText("请建立游戏或者加入游戏");
}
if(!isOnChess)
{
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chesspad.statusText.setText("请建立游戏或者加入游戏");
}
isClient=isServer=false;
}

}

public void keyPressed(KeyEvent e)
{
TextField inputWords=(TextField)e.getSource();

if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
if(inputpad.userChoice.getSelectedItem().equals("所有人"))
{
try
{
out.writeUTF(inputWords.getText());
inputWords.setText("");
}
catch(Exception ea)
{
chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n");
userpad.userList.removeAll();
inputpad.userChoice.removeAll();
inputWords.setText("");
controlpad.connectButton.setEnabled(true);
}
}
else
{
try
{
out.writeUTF("/"+inputpad.userChoice.getSelectedItem()+" "+inputWords.getText());
inputWords.setText("");
}
catch(Exception ea)
{
chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n");
userpad.userList.removeAll();
inputpad.userChoice.removeAll();
inputWords.setText("");
controlpad.connectButton.setEnabled(true);
}
}
}

}

public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}

public static void main(String args[])
{
chessClient chessClient=new chessClient();
}
}

/******************************************************************************************
下面是:chessInteface.java
******************************************************************************************/

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

class userPad extends Panel
{
List userList=new List(10);

userPad()
{
setLayout(new BorderLayout());

for(int i=0;i<50;i++)
{
userList.add(i+"."+"没有用户");
}
add(userList,BorderLayout.CENTER);

}

}

class chatPad extends Panel
{
TextArea chatLineArea=new TextArea("",18,30,TextArea.SCROLLBARS_VERTICAL_ONLY);

chatPad()
{
setLayout(new BorderLayout());

add(chatLineArea,BorderLayout.CENTER);
}

}

class controlPad extends Panel
{
Label IPlabel=new Label("IP",Label.LEFT);
TextField inputIP=new TextField("localhost",10);
Button connectButton=new Button("连接主机");
Button creatGameButton=new Button("建立游戏");
Button joinGameButton=new Button("加入游戏");
Button cancelGameButton=new Button("放弃游戏");
Button exitGameButton=new Button("关闭程序");

controlPad()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
setBackground(Color.pink);

add(IPlabel);
add(inputIP);
add(connectButton);
add(creatGameButton);
add(joinGameButton);
add(cancelGameButton);
add(exitGameButton);
}

}

class inputPad extends Panel
{
TextField inputWords=new TextField("",40);
Choice userChoice=new Choice();

inputPad()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
for(int i=0;i<50;i++)
{
userChoice.addItem(i+"."+"没有用户");
}
userChoice.setSize(60,24);
add(userChoice);
add(inputWords);
}
}

/**********************************************************************************************
下面是:chessPad.java
**********************************************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

class chessThread extends Thread
{
chessPad chesspad;

chessThread(chessPad chesspad)
{
this.chesspad=chesspad;
}

public void sendMessage(String sndMessage)
{
try
{
chesspad.outData.writeUTF(sndMessage);
}
catch(Exception ea)
{
System.out.println("chessThread.sendMessage:"+ea);
}
}

public void acceptMessage(String recMessage)
{
if(recMessage.startsWith("/chess "))
{
StringTokenizer userToken=new StringTokenizer(recMessage," ");
String chessToken;
String[] chessOpt={"-1","-1","0"};
int chessOptNum=0;

while(userToken.hasMoreTokens())
{
chessToken=(String)userToken.nextToken(" ");
if(chessOptNum>=1 && chessOptNum<=3)
{
chessOpt[chessOptNum-1]=chessToken;

}
chessOptNum++;
}
chesspad.netChessPaint(Integer.parseInt(chessOpt[0]),Integer.parseInt(chessOpt[1]),Integer.parseInt(chessOpt[2]));

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

public void run()
{
String message="";
try
{
while(true)
{
message=chesspad.inData.readUTF();
acceptMessage(message);
}
}
catch(IOException es)
{
}
}

}

class chessPad extends Panel implements MouseListener,ActionListener
{
int chessPoint_x=-1,chessPoint_y=-1,chessColor=1;
int chessBlack_x[]=new int[200];
int chessBlack_y[]=new int[200];
int chessWhite_x[]=new int[200];
int chessWhite_y[]=new int[200];
int chessBlackCount=0,chessWhiteCount=0;
int chessBlackWin=0,chessWhiteWin=0;
boolean isMouseEnabled=false,isWin=false,isInGame=false;
TextField statusText=new TextField("请先连接服务器");

Socket chessSocket;
DataInputStream inData;
DataOutputStream outData;

String chessSelfName=null;
String chessPeerName=null;
String host=null;
int port=4331;
chessThread chessthread=new chessThread(this);

chessPad()
{
setSize(440,440);
setLayout(null);
setBackground(Color.pink);
addMouseListener(this);
add(statusText);
statusText.setBounds(40,5,360,24);
statusText.setEditable(false);
}

public boolean connectServer(String ServerIP,int ServerPort) throws Exception
{
try
{
chessSocket=new Socket(ServerIP,ServerPort);
inData=new DataInputStream(chessSocket.getInputStream());
outData=new DataOutputStream(chessSocket.getOutputStream());
chessthread.start();
return true;
}
catch(IOException ex)
{
statusText.setText("chessPad:connectServer:无法连接 \n");
}
return false;
}

public void chessVictory(int chessColorWin)
{
this.removeAll();
for(int i=0;i<=chessBlackCount;i++)
{
chessBlack_x[i]=0;
chessBlack_y[i]=0;
}
for(int i=0;i<=chessWhiteCount;i++)
{
chessWhite_x[i]=0;
chessWhite_y[i]=0;
}
chessBlackCount=0;
chessWhiteCount=0;
add(statusText);
statusText.setBounds(40,5,360,24);

if(chessColorWin==1)
{ chessBlackWin++;
statusText.setText("黑棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待白棋下子...");
}
else if(chessColorWin==-1)
{
chessWhiteWin++;
statusText.setText("白棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待黑棋下子...");
}
}

public void getLocation(int a,int b,int color)
{

if(color==1)
{
chessBlack_x[chessBlackCount]=a*20;
chessBlack_y[chessBlackCount]=b*20;
chessBlackCount++;
}
else if(color==-1)
{
chessWhite_x[chessWhiteCount]=a*20;
chessWhite_y[chessWhiteCount]=b*20;
chessWhiteCount++;
}
}

public boolean checkWin(int a,int b,int checkColor)
{
int step=1,chessLink=1,chessLinkTest=1,chessCompare=0;
if(checkColor==1)
{
chessLink=1;
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a+step)*20==chessBlack_x[chessCompare]) && ((b*20)==chessBlack_y[chessCompare]))
{
chessLink=chessLink+1;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a-step)*20==chessBlack_x[chessCompare]) && (b*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
chessLink=1;
chessLinkTest=1;
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if((a*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if((a*20==chessBlack_x[chessCompare]) && ((b-step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
chessLink=1;
chessLinkTest=1;
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a-step)*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a+step)*20==chessBlack_x[chessCompare]) && ((b-step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
chessLink=1;
chessLinkTest=1;
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a+step)*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a-step)*20==chessBlack_x[chessCompare]) && ((b-step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}

Ⅸ 急!!! Java五子棋源代码注释

package org.liky.game.frame;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class FiveChessFrame extends JFrame implements MouseListener, Runnable {

// 取得屏幕的宽度
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
// 取得屏幕的高度
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
// 背景图片
BufferedImage bgImage = null;
// 保存棋子的坐标
int x = 0;
int y = 0;
// 保存之前下过的全部棋子的坐标
// 其中数据内容 0: 表示这个点并没有棋子, 1: 表示这个点是黑子, 2:表示这个点是白子
int[][] allChess = new int[19][19];
// 标识当前应该黑棋还是白棋下下一步
boolean isBlack = true;
// 标识当前游戏是否可以继续
boolean canPlay = true;
// 保存显示的提示信息
String message = "黑方先行";
// 保存最多拥有多少时间(秒)
int maxTime = 0;
// 做倒计时的线程类
Thread t = new Thread(this);
// 保存黑方与白方的剩余时间
int blackTime = 0;
int whiteTime = 0;
// 保存双方剩余时间的显示信息
String blackMessage = "无限制";
String whiteMessage = "无限制";

public FiveChessFrame() {
// 设置标题
this.setTitle("五子棋");
// 设置窗体大小
this.setSize(500, 500);
// 设置窗体出现位置
this.setLocation((width - 500) / 2, (height - 500) / 2);
// 将窗体设置为大小不可改变
this.setResizable(false);
// 将窗体的关闭方式设置为默认关闭后程序结束
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 为窗体加入监听器
this.addMouseListener(this);
// 将窗体显示出来
this.setVisible(true);

t.start();
t.suspend();

// 刷新屏幕,防止开始游戏时出现无法显示的情况.
this.repaint();
String imagePath = "" ;
try {
imagePath = System.getProperty("user.dir")+"/bin/image/background.jpg" ;
bgImage = ImageIO.read(new File(imagePath.replaceAll("\\\\", "/")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void paint(Graphics g) {
// 双缓冲技术防止屏幕闪烁
BufferedImage bi = new BufferedImage(500, 500,
BufferedImage.TYPE_INT_RGB);
Graphics g2 = bi.createGraphics();
g2.setColor(Color.BLACK);
// 绘制背景
g2.drawImage(bgImage, 1, 20, this);
// 输出标题信息
g2.setFont(new Font("黑体", Font.BOLD, 20));
g2.drawString("游戏信息:" + message, 130, 60);
// 输出时间信息
g2.setFont(new Font("宋体", 0, 14));
g2.drawString("黑方时间:" + blackMessage, 30, 470);
g2.drawString("白方时间:" + whiteMessage, 260, 470);

// 绘制棋盘
for (int i = 0; i < 19; i++) {
g2.drawLine(10, 70 + 20 * i, 370, 70 + 20 * i);
g2.drawLine(10 + 20 * i, 70, 10 + 20 * i, 430);
}

// 标注点位
g2.fillOval(68, 128, 4, 4);
g2.fillOval(308, 128, 4, 4);
g2.fillOval(308, 368, 4, 4);
g2.fillOval(68, 368, 4, 4);
g2.fillOval(308, 248, 4, 4);
g2.fillOval(188, 128, 4, 4);
g2.fillOval(68, 248, 4, 4);
g2.fillOval(188, 368, 4, 4);
g2.fillOval(188, 248, 4, 4);

/*
* //绘制棋子 x = (x - 10) / 20 * 20 + 10 ; y = (y - 70) / 20 * 20 + 70 ;
* //黑子 g.fillOval(x - 7, y - 7, 14, 14); //白子 g.setColor(Color.WHITE) ;
* g.fillOval(x - 7, y - 7, 14, 14); g.setColor(Color.BLACK) ;
* g.drawOval(x - 7, y - 7, 14, 14);
*/

// 绘制全部棋子
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
if (allChess[i][j] == 1) {
// 黑子
int tempX = i * 20 + 10;
int tempY = j * 20 + 70;
g2.fillOval(tempX - 7, tempY - 7, 14, 14);
}
if (allChess[i][j] == 2) {
// 白子
int tempX = i * 20 + 10;
int tempY = j * 20 + 70;
g2.setColor(Color.WHITE);
g2.fillOval(tempX - 7, tempY - 7, 14, 14);
g2.setColor(Color.BLACK);
g2.drawOval(tempX - 7, tempY - 7, 14, 14);
}
}
}
g.drawImage(bi, 0, 0, this);
}

public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub

}

public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub

}

public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub

}

public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
/*
* System.out.println("X:"+e.getX()); System.out.println("Y:"+e.getY());
*/
if (canPlay == true) {
x = e.getX();
y = e.getY();
if (x >= 10 && x <= 370 && y >= 70 && y <= 430) {
x = (x - 10) / 20;
y = (y - 70) / 20;
if (allChess[x][y] == 0) {
// 判断当前要下的是什么颜色的棋子
if (isBlack == true) {
allChess[x][y] = 1;
isBlack = false;
message = "轮到白方";
} else {
allChess[x][y] = 2;
isBlack = true;
message = "轮到黑方";
}
// 判断这个棋子是否和其他的棋子连成5连,即判断游戏是否结束
boolean winFlag = this.checkWin();
if (winFlag == true) {
JOptionPane.showMessageDialog(this, "游戏结束,"
+ (allChess[x][y] == 1 ? "黑方" : "白方") + "获胜!");
canPlay = false;
}
} else {
JOptionPane.showMessageDialog(this, "当前位置已经有棋子,请重新落子!");
}
this.repaint();
}
}
/* System.out.println(e.getX() + " -- " + e.getY()); */
// 点击 开始游戏 按钮
if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 70
&& e.getY() <= 100) {
int result = JOptionPane.showConfirmDialog(this, "是否重新开始游戏?");
if (result == 0) {
// 现在重新开始游戏
// 重新开始所要做的操作: 1)把棋盘清空,allChess这个数组中全部数据归0.
// 2) 将 游戏信息: 的显示改回到开始位置
// 3) 将下一步下棋的改为黑方
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
allChess[i][j] = 0;
}
}
// 另一种方式 allChess = new int[19][19];
message = "黑方先行";
isBlack = true;
blackTime = maxTime;
whiteTime = maxTime;
if (maxTime > 0) {
blackMessage = maxTime / 3600 + ":"
+ (maxTime / 60 - maxTime / 3600 * 60) + ":"
+ (maxTime - maxTime / 60 * 60);
whiteMessage = maxTime / 3600 + ":"
+ (maxTime / 60 - maxTime / 3600 * 60) + ":"
+ (maxTime - maxTime / 60 * 60);
t.resume();
} else {
blackMessage = "无限制";
whiteMessage = "无限制";
}
this.canPlay = true;
this.repaint();

}
}
// 点击 游戏设置 按钮
if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 120
&& e.getY() <= 150) {
String input = JOptionPane
.showInputDialog("请输入游戏的最大时间(单位:分钟),如果输入0,表示没有时间限制:");
try {
maxTime = Integer.parseInt(input) * 60;
if (maxTime < 0) {
JOptionPane.showMessageDialog(this, "请输入正确信息,不允许输入负数!");
}
if (maxTime == 0) {
int result = JOptionPane.showConfirmDialog(this,
"设置完成,是否重新开始游戏?");
if (result == 0) {
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
allChess[i][j] = 0;
}
}
// 另一种方式 allChess = new int[19][19];
message = "黑方先行";
isBlack = true;
blackTime = maxTime;
whiteTime = maxTime;
blackMessage = "无限制";
whiteMessage = "无限制";
this.canPlay = true;
this.repaint();
}
}
if (maxTime > 0) {
int result = JOptionPane.showConfirmDialog(this,
"设置完成,是否重新开始游戏?");
if (result == 0) {
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
allChess[i][j] = 0;
}
}
// 另一种方式 allChess = new int[19][19];
message = "黑方先行";
isBlack = true;
blackTime = maxTime;
whiteTime = maxTime;
blackMessage = maxTime / 3600 + ":"
+ (maxTime / 60 - maxTime / 3600 * 60) + ":"
+ (maxTime - maxTime / 60 * 60);
whiteMessage = maxTime / 3600 + ":"
+ (maxTime / 60 - maxTime / 3600 * 60) + ":"
+ (maxTime - maxTime / 60 * 60);
t.resume();
this.canPlay = true;
this.repaint();
}
}
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(this, "请正确输入信息!");
}
}
// 点击 游戏说明 按钮
if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 170
&& e.getY() <= 200) {
JOptionPane.showMessageDialog(this,
"这个一个五子棋游戏程序,黑白双方轮流下棋,当某一方连到五子时,游戏结束。");
}
// 点击 认输 按钮
if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 270
&& e.getY() <= 300) {
int result = JOptionPane.showConfirmDialog(this, "是否确认认输?");
if (result == 0) {
if (isBlack) {
JOptionPane.showMessageDialog(this, "黑方已经认输,游戏结束!");
} else {
JOptionPane.showMessageDialog(this, "白方已经认输,游戏结束!");
}
canPlay = false;
}
}
// 点击 关于 按钮
if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 320
&& e.getY() <= 350) {
JOptionPane.showMessageDialog(this,
"本游戏由MLDN制作,有相关问题可以访问www.mldn.cn");
}
// 点击 退出 按钮
if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 370
&& e.getY() <= 400) {
JOptionPane.showMessageDialog(this, "游戏结束");
System.exit(0);
}
}

public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub

}

private boolean checkWin() {
boolean flag = false;
// 保存共有相同颜色多少棋子相连
int count = 1;
// 判断横向是否有5个棋子相连,特点 纵坐标 是相同, 即allChess[x][y]中y值是相同
int color = allChess[x][y];
/*
* if (color == allChess[x+1][y]) { count++; if (color ==
* allChess[x+2][y]) { count++; if (color == allChess[x+3][y]) {
* count++; } } }
*/
// 通过循环来做棋子相连的判断
/*
* int i = 1; while (color == allChess[x + i][y + 0]) { count++; i++; }
* i = 1; while (color == allChess[x - i][y - 0]) { count++; i++; } if
* (count >= 5) { flag = true; } // 纵向的判断 int i2 = 1 ; int count2 = 1 ;
* while (color == allChess[x + 0][y + i2]) { count2++; i2++; } i2 = 1;
* while (color == allChess[x - 0][y - i2]) { count2++; i2++; } if
* (count2 >= 5) { flag = true ; } // 斜方向的判断(右上 + 左下) int i3 = 1 ; int
* count3 = 1 ; while (color == allChess[x + i3][y - i3]) { count3++;
* i3++; } i3 = 1; while (color == allChess[x - i3][y + i3]) { count3++;
* i3++; } if (count3 >= 5) { flag = true ; } // 斜方向的判断(右下 + 左上) int i4 =
* 1 ; int count4 = 1 ; while (color == allChess[x + i4][y + i4]) {
* count4++; i4++; } i4 = 1; while (color == allChess[x - i4][y - i4]) {
* count4++; i4++; } if (count4 >= 5) { flag = true ; }
*/

// 判断横向
count = this.checkCount(1, 0, color);
if (count >= 5) {
flag = true;
} else {
// 判断纵向
count = this.checkCount(0, 1, color);
if (count >= 5) {
flag = true;
} else {
// 判断右上、左下
count = this.checkCount(1, -1, color);
if (count >= 5) {
flag = true;
} else {
// 判断右下、左上
count = this.checkCount(1, 1, color);
if (count >= 5) {
flag = true;
}
}
}
}

return flag;
}

// 判断棋子连接的数量
private int checkCount(int xChange, int yChange, int color) {
int count = 1;
int tempX = xChange;
int tempY = yChange;
while (x + xChange >= 0 && x + xChange <= 18 && y + yChange >= 0
&& y + yChange <= 18
&& color == allChess[x + xChange][y + yChange]) {
count++;
if (xChange != 0)
xChange++;
if (yChange != 0) {
if (yChange > 0)
yChange++;
else {
yChange--;
}
}
}
xChange = tempX;
yChange = tempY;
while (x - xChange >= 0 && x - xChange <= 18 && y - yChange >= 0
&& y - yChange <= 18
&& color == allChess[x - xChange][y - yChange]) {
count++;
if (xChange != 0)
xChange++;
if (yChange != 0) {
if (yChange > 0)
yChange++;
else {
yChange--;
}
}
}
return count;
}

public void run() {
// TODO Auto-generated method stub
// 判断是否有时间限制
if (maxTime > 0) {
while (true) {
if (isBlack) {
blackTime--;
if (blackTime == 0) {
JOptionPane.showMessageDialog(this, "黑方超时,游戏结束!");
}
} else {
whiteTime--;
if (whiteTime == 0) {
JOptionPane.showMessageDialog(this, "白方超时,游戏结束!");
}
}
blackMessage = blackTime / 3600 + ":"
+ (blackTime / 60 - blackTime / 3600 * 60) + ":"
+ (blackTime - blackTime / 60 * 60);
whiteMessage = whiteTime / 3600 + ":"
+ (whiteTime / 60 - whiteTime / 3600 * 60) + ":"
+ (whiteTime - whiteTime / 60 * 60);
this.repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(blackTime + " -- " + whiteTime);
}
}
}

}

阅读全文

与java网络五子棋源码相关的资料

热点内容
证券技术分析pdf 浏览:777
linux命令连接oracle 浏览:200
垫江停车收费桩怎么上App 浏览:133
好兴动app还款怎么登录不上去了 浏览:665
郑州云服务器托管 浏览:722
服务器地址跟踪 浏览:980
免费google云服务器 浏览:516
摘译和编译的英文 浏览:359
热泵压缩机选型 浏览:121
op手机微信加密如何解除 浏览:386
如何在王牌战争找到高爆率服务器 浏览:13
江浙小学语文辅导课用什么APP 浏览:99
新梦幻大陆服务器地址 浏览:241
网吧服务器怎么更换壁纸 浏览:530
linux命令方法 浏览:332
linux下载freetype 浏览:123
程序员入驻平台 浏览:327
程序员大战外挂 浏览:745
html实例教程pdf 浏览:157
linux命令开放所有权限 浏览:575