java网络五子棋
chessPad.java:棋盘的绘制.
chessServer.java:服务器端.
/*********************************************************************************************
①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(userNumber0 !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);
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无法关闭");
else if(recMessage.startsWith("/peer "))
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="";
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;
boolean isOnChat=false; //在聊天?
boolean isOnChess=false; //在下棋?
boolean isServer=false; //如果是下棋的主机
Panel southPanel=new Panel();
Panel northPanel=new Panel();
Panel centerPanel=new Panel();
Panel westPanel=new Panel();
Panel eastPanel=new Panel();
chessClient()
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)
chatSocket.close();
catch(Exception ed)
if(isOnChess || isGameConnected)
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();
setVisible(true);
setResizable(false);
validate();
public boolean connectServer(String serverIP,int serverPort) throws Exception
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();
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(e.getSource()==controlpad.joinGameButton)
String selectedUser=userpad.userList.getSelectedItem();
if(selectedUser==null || selectedUser.startsWith("[inchess]") ||
selectedUser.equals(chessClientName))
chesspad.statusText.setText("必须先选定一个有效用户");
if(!isGameConnected)
if(chesspad.connectServer(chesspad.host,chesspad.port))
isGameConnected=true;
isOnChess=true;
isClient=true;
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/joingame "◆userpad.userList.getSelectedItem()◆" "◆chessClientName);
isGameConnected=false;
isOnChess=false;
isClient=false;
chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"◆ee);
if(e.getSource()==controlpad.creatGameButton)
isServer=true;
chesspad.chessthread.sendMessage("/creatgame "◆"[inchess]"◆chessClientName);
catch(Exception ec)
isServer=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);
chesspad.statusText.setText("请建立游戏或者加入游戏");
if(!isOnChess)
isClient=isServer=false;
public void keyPressed(KeyEvent e)
TextField inputWords=(TextField)e.getSource();
if(e.getKeyCode()==KeyEvent.VK_ENTER)
if(inputpad.userChoice.getSelectedItem().equals("所有人"))
out.writeUTF(inputWords.getText());
inputWords.setText("");
catch(Exception ea)
chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n");
userpad.userList.removeAll();
inputpad.userChoice.removeAll();
controlpad.connectButton.setEnabled(true);
out.writeUTF("/"◆inputpad.userChoice.getSelectedItem()◆" "◆inputWords.getText());
public void keyTyped(KeyEvent e)
public void keyReleased(KeyEvent e)
public static void main(String args[])
chessClient chessClient=new chessClient();
/******************************************************************************************
下面是:chessInteface.java
******************************************************************************************/
class userPad extends Panel
List userList=new List(10);
userPad()
userList.add(i◆"."◆"没有用户");
add(userList,BorderLayout.CENTER);
class chatPad extends Panel
chatPad()
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
Choice userChoice=new Choice();
inputPad()
userChoice.addItem(i◆"."◆"没有用户");
add(userChoice);
add(inputWords);
/**********************************************************************************************
下面是:chessPad.java
class chessThread extends Thread
chessPad chesspad;
chessThread(chessPad chesspad)
this.chesspad=chesspad;
public void sendMessage(String sndMessage)
chesspad.outData.writeUTF(sndMessage);
System.out.println("chessThread.sendMessage:"◆ea);
if(recMessage.startsWith("/chess "))
String chessToken;
String[] chessOpt={"-1","-1","0"};
int chessOptNum=0;
chessToken=(String)userToken.nextToken(" ");
chessOpt[chessOptNum-1]=chessToken;
chessOptNum◆◆;
chesspad.chessSelfName=recMessage.substring(10);
chesspad.statusText.setText("错误:没有这个用户,请退出程序,重新加入");
//System.out.println(recMessage);
message=chesspad.inData.readUTF();
class chessPad extends Panel implements MouseListener,ActionListener
int chessPoint_x=-1,chessPoint_y=-1,chessColor=1;
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;
chessThread chessthread=new chessThread(this);
chessPad()
setLayout(null);
addMouseListener(this);
add(statusText);
statusText.setEditable(false);
public boolean connectServer(String ServerIP,int ServerPort) throws Exception
chessSocket=new Socket(ServerIP,ServerPort);
inData=new DataInputStream(chessSocket.getInputStream());
outData=new DataOutputStream(chessSocket.getOutputStream());
chessthread.start();
statusText.setText("chessPad:connectServer:无法连接 \n");
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;
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)
chessBlackCount◆◆;
else if(color==-1)
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(chessCompare=0;chessCompare=chessBlackCount;chessCompare◆◆)
chessLink=chessLink◆1;
return(true);
if(chessLink==(chessLinkTest◆1))
chessLinkTest◆◆;
break;
chessLink◆◆;
chessLinkTest=1;
以下是现写的 实现了两人对战 自己复制后运行把 没什么难度 类名 Games
import java.util.Scanner;
public class Games {
private String board[][];
private static String roles = "A粉丝";
//初始化数组
public void initBoard() {
board = new String[SIZE][SIZE];
for (int i = 0; i SIZE; i◆◆) {
for (int j = 0; j SIZE; j◆◆) {
// if(i==0){
// String str = "";
// str ◆= j◆" ";
// board[i][j]= str;
// }else if(i!=0j==0){
// String str = "";
// str ◆= i◆" ";
// }else{
board[i][j] = "╋";
// }
//输出棋盘
public void printBoard() {
System.out.print(board[i][j]);
System.out.println();
//判断所下棋子位置是否合理
public boolean isOk(int x, int y) {
boolean isRight = true;
//System.out.println("输入错误,请从新输入");
isRight = false;
if (board[x][y].equals("●") || board[x][y].equals("○")) {
return isRight;
//判断谁赢了
public void whoWin(Games wz) {
int xlabel;// 记录第一次找到某个棋子的x坐标
int ylabel;// 记录第一次找到某个棋子的y坐标
// ●○╋
// 判断人是否赢了
if (board[i][j].equals("○")) {
xlabel = i;
ylabel = j;
// 横向找 x坐标不变 y坐标以此加1连成字符串
String heng = "";
heng ◆= board[i][k];
if (heng.equals("○○○○○")) {
System.out.println(roles◆"赢了!您输了!");
String xia = "";
xia ◆= board[l][j];
// System.out.println(xia);
if (xia.equals("○○○○○")) {
// 斜向右下判断
String youxia = "";
youxia ◆= board[xlabel◆◆][ylabel◆◆];
if (youxia.equals("○○○○○")) {
// 判断电脑是否赢了
if (board[i][j].equals("●")) {
if (heng.equals("●●●●●")) {
System.out.println(roles◆"赢输了!您输了!");
xia ◆= board[l][ylabel];
if (xia.equals("●●●●●")) {
if (youxia.equals("●●●●●")) {
public static void main(String[] args) {
Games wz = new Games();
Scanner sc = new Scanner(System.in);
wz.initBoard();
wz.printBoard();
while (true) {
int x = sc.nextInt();
int y = sc.nextInt();
if (x == SIZE y == SIZE) {
System.out.println("程序结束");
if (x SIZE || x 0 || y SIZE | y 0) {
System.out.println("输入错误,请从新输入");
continue;
//如果roles是A粉丝 就让A粉丝下棋,否则就让B粉丝下棋.
if (wz.board[x][y].equals("╋")roles.equals("A粉丝")) {
wz.board[x][y] = "○";
//判断输赢
wz.whoWin(wz);
}else if(wz.board[x][y].equals("╋")roles.equals("B粉丝")){
wz.board[x][y] = "●";
} else {
System.out.println("此处已经有棋子,从新输入");
if(roles.equals("A粉丝")){
roles = "B粉丝";
}else if(roles.equals("B粉丝")){
roles = "A粉丝";
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;
// 保存之前下过的全部棋子的坐标
// 标识当前应该黑棋还是白棋下下一步
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.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.TYPE_INT_RGB);
// 绘制背景
// 输出标题信息
// 输出时间信息
// 绘制棋盘
// 标注点位
/*
*/
// 绘制全部棋子
if (allChess[i][j] == 1) {
// 黑子
// 白子
g.drawImage(bi, 0, 0, this);
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
public void mouseEntered(MouseEvent e) {
public void mouseExited(MouseEvent e) {
public void mousePressed(MouseEvent e) {
* System.out.println("X:"◆e.getX()); System.out.println("Y:"◆e.getY());
if (canPlay == true) {
x = e.getX();
y = e.getY();
if (allChess[x][y] == 0) {
// 判断当前要下的是什么颜色的棋子
if (isBlack == true) {
allChess[x][y] = 1;
isBlack = false;
message = "轮到白方";
isBlack = true;
message = "轮到黑方";
boolean winFlag = this.checkWin();
if (winFlag == true) {
JOptionPane.showMessageDialog(this, "游戏结束,"
◆ (allChess[x][y] == 1 ? "黑方" : "白方") ◆ "获胜!");
canPlay = false;
JOptionPane.showMessageDialog(this, "当前位置已经有棋子,请重新落子!");
/* System.out.println(e.getX() ◆ " -- " ◆ e.getY()); */
e.getY() = 100) {
int result = JOptionPane.showConfirmDialog(this, "是否重新开始游戏?");
if (result == 0) {
// 现在重新开始游戏
// 重新开始所要做的操作: 1)把棋盘清空,allChess这个数组中全部数据归0.
allChess[i][j] = 0;
message = "黑方先行";
blackTime = maxTime;
whiteTime = maxTime;
if (maxTime 0) {
t.resume();
blackMessage = "无限制";
whiteMessage = "无限制";
this.canPlay = true;
String input = JOptionPane
.showInputDialog("请输入游戏的最大时间(单位:分钟),如果输入0,表示没有时间限制:");
JOptionPane.showMessageDialog(this, "请输入正确信息,不允许输入负数!");
if (maxTime == 0) {
int result = JOptionPane.showConfirmDialog(this,
"设置完成,是否重新开始游戏?");
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(this, "请正确输入信息!");
JOptionPane.showMessageDialog(this,
"这个一个五子棋游戏程序,黑白双方轮流下棋,当某一方连到五子时,游戏结束.");
int result = JOptionPane.showConfirmDialog(this, "是否确认认输?");
if (isBlack) {
JOptionPane.showMessageDialog(this, "黑方已经认输,游戏结束!");
JOptionPane.showMessageDialog(this, "白方已经认输,游戏结束!");
"本游戏由MLDN制作,有相关问题可以访问");
JOptionPane.showMessageDialog(this, "游戏结束");
public void mouseReleased(MouseEvent e) {
private boolean checkWin() {
boolean flag = false;
// 保存共有相同颜色多少棋子相连
int count = 1;
int color = allChess[x][y];
* if (color == allChess[x◆1][y]) { count◆◆; if (color ==
* 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 = this.checkCount(1, 0, color);
flag = true;
// 判断纵向
count = this.checkCount(0, 1, color);
// 判断右上、左下
count = this.checkCount(1, -1, color);
// 判断右下、左上
count = this.checkCount(1, 1, color);
return flag;
// 判断棋子连接的数量
private int checkCount(int xChange, int yChange, int color) {
int tempX = xChange;
int tempY = yChange;
color == allChess[x ◆ xChange][y ◆ yChange]) {
count◆◆;
if (xChange != 0)
xChange◆◆;
if (yChange != 0) {
if (yChange 0)
yChange◆◆;
else {
yChange--;
xChange = tempX;
yChange = tempY;
color == allChess[x - xChange][y - yChange]) {
return count;
public void run() {
// 判断是否有时间限制
blackTime--;
if (blackTime == 0) {
JOptionPane.showMessageDialog(this, "黑方超时,游戏结束!");
whiteTime--;
if (whiteTime == 0) {
JOptionPane.showMessageDialog(this, "白方超时,游戏结束!");
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(blackTime ◆ " -- " ◆ whiteTime);
以上就是土嘎嘎小编为大家整理的java五子棋的一些代码相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!