基于Java的五子棋游戏的设计
java课程设计之基于Java的五子棋游戏的设计,提供java源代码下载(java课程设计网原创)

Java的五子棋游戏 每个功能类我贴一下:
package com.test.wzq;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.io.IOException;
import javax.swing.JPanel;
/**
* @author 原创 java课程设计网 http://www.javakcsj.com/
* @date2018-7-31
*/
public class BoardPanel extends JPanel {
private static Image white = null;
private static Image black = null;
private static int xp; // 棋子 X坐标
private static int yp; // 棋子Y坐标
private Cursor handCursor;
private Cursor defaultCursor;
protected static int board[][]; // 棋型表
private int color = 1; // 棋子颜色 1=black 2=white
int STEPCOUNTER = 0;
int BASE = 5;
int DEEPTH = 3;
int MINDEEPTH = 3;
int MAX1 = 5;
long INVALID = 9000000;
int chessBoard[][];
// x/y 方向标识符
String line = "a b c d e f g h i j k l m n o";
char[] rowNum1 = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] rowNum2 = { '1', '0', '1', '1', '1', '2', '1', '3', '1', '4', '1',
'5' };
public BoardPanel() {
// this.wzq=wz;
try {
handCursor = new Cursor(12);
defaultCursor = new Cursor(0);
board = new int[15][15];
// black = wzq.black;
// white = wzq.white;
// this.setBackground(Color.yellow);
// this.setForeground(Color.BLUE);
// this.setBorder(BorderFactory.createLoweredBevelBorder());
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
public void paint(Graphics gc) {
super.paint(gc);
// this.setBackground(Color.gray);
// this.invalidate();
gc.setColor(Color.blue);
// gc.setColor(new Color(255, 255, 240));
// 画横向标识符
gc.drawString(line, 25, 15);
// 画竖向标识符
for (int i = 0; i < 9; i++) {
gc.drawChars(rowNum1, i, 1, 10, 35 + i * 30);
}
for (int i = 9, j = 0; i < 15; i++, j += 2) {
gc.drawChars(rowNum2, j, 2, 10, 35 + i * 30);
}
// 画棋盘
for (int i = 0; i < 15; i++) {
gc.drawLine(30, 30 + i * 30, 450, 30 + i * 30); // 行
gc.drawLine(30 + i * 30, 30, 30 + i * 30, 450); // 列
}
gc.drawLine(25, 25, 455, 25);
gc.drawLine(25, 25, 25, 455);
gc.drawLine(25, 455, 455, 455);
gc.drawLine(455, 25, 455, 455);
// 面板初始化
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
xp = 16 + i * 30;
yp = 16 + j * 30;
if (board[i][j] == 1) {
gc.setColor(Color.black);
gc.fillOval(xp, yp, 28, 28);
// gc.drawImage(black, 16 + i * 30, 16 + j * 30, this);
}
if (board[i][j] == 2) {
gc.setColor(Color.white);
gc.fillOval(xp, yp, 28, 28);
// gc.drawImage(white, 16 + i * 30, 16 + j * 30, this);
}
}
}
}
private void jbInit() throws Exception {
this.addMouseMotionListener(new ChessWZQ_this_mouseMotionAdapter(this));
this.addMouseListener(new ChessWZQ_this_mouseAdapter(this));
}
public int getColor() {
return color;
}
public void setColor(int cr) {
color = cr;
}
/**
* 更新时清空面板
*/
public void clearBoard() {
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++)
board[i][j] = 0;
}
repaint();
}
void this_mouseClicked(MouseEvent e) {
int x = 0, y = 0;
if (color == 0) {
return;
}
x = e.getX();
y = e.getY();
if (x > 20 && x < 460 && y > 20 && y < 460
&& (x % 30 < 10 || x % 30 > 20) && (y % 30 < 10 || y % 30 > 20)) {
if (ChessWZQ.beginFlag == false) {
ChessWZQ.label6.setText("You may not do that");
return;
}
xp = x / 30 * 30 - 14;
yp = y / 30 * 30 - 14;
if (x % 30 > 20) {
xp += 30;
}
if (y % 30 > 20) {
yp += 30;
}
x = xp / 30;
y = yp / 30;
if (board[x][y] != 0) {
return;
}
// 客户端面板
board[xp / 30][yp / 30] = color;
Graphics g = this.getGraphics();
if (color == 1) {// 黑棋
g.setColor(Color.black);
}
if (color == 2) {// 白棋
g.setColor(Color.white);
}
g.fillOval(xp, yp, 28, 28);
ChessWZQ.beginFlag = false;
// 设定坐标(x,y)
// x=xp/30;y=yp/30;
if (ChessWZQ.ptocFlag == false) {
Message msg = new Message();
msg.color = color;
msg.coordinateX = x;
msg.coordinateY = y;
msg.type = 2; // 下棋
// 给服务端发消息
try {
ChessWZQ.out.writeObject(msg);
} catch (IOException ee) {
ee.printStackTrace();
}
}
char cc = (char) (x + 65);
ChessWZQ.label6.setText("put on ( " + cc + " , " + (y + 1) + " )");
// / 电脑下子
if (ChessWZQ.ptocFlag == true) {
if (judge(xp / 30, yp / 30, color) == true) {
// System.out.println("people win");
Message ms = new Message();
ms.type = 20;
strToCharArray("You", ms.msg);
try {
ChessWZQ.out.writeObject(ms);
} catch (IOException er) {
er.printStackTrace();
}
}
ChessWZQ.beginFlag = false;
int position = 0, bestX = 0, bestY = 0;
Analyse aa = new Analyse(BoardPanel.board);
position = aa.computerDo();
bestY = position % 100 - 1;
bestX = position / 100 - 1;
updateBoard(bestX, bestY);
drawChess(bestX, bestY);
ChessWZQ.beginFlag = true; // 人下子
cc = (char) (bestX + 65);
ChessWZQ.label6.setText("put on ( " + cc + " , " + (bestY + 1)
+ " )");
if (judge(bestX, bestY, ChessWZQ.cColor) == true) {
// System.out.println("computer win");
Message msg = new Message();
msg.type = 20;
strToCharArray("Computer", msg.msg);
try {
ChessWZQ.out.writeObject(msg);
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
}
// 字符串转换成数组,并以‘/0‘结束
public void strToCharArray(String str, char[] arr) {
int i;
for (i = 0; i < str.length() && i < 49; i++) {
arr[i] = str.charAt(i);
}
arr[i] = '\0';
}
/**
* 返回棋子坐标
*/
protected int getXP() {
return xp / 30;
}
protected int getYP() {
return yp / 30;
}
/**
* 下棋,并在面板(x,y)上显示 画棋子
*/
public void drawChess(int x, int y) {
Graphics g = this.getGraphics();
char cc = (char) (x + 65);
int temp = y + 1;
x = x * 30 + 16;
y = y * 30 + 16;
if (color == 1)
g.setColor(Color.white);
else
g.setColor(Color.black);
g.fillOval(x, y, 28, 28);
ChessWZQ.label6.setText("Player put on ( " + cc + " , " + temp + " )");
}
/**
* B下棋子时更新面板 B棋子的X坐标 B棋子的Y坐标
*/
public void updateBoard(int x, int y) {
int tcolor = 0;
if (color == 1)
tcolor = 2;
else
tcolor = 1;
board[x][y] = tcolor;
}
public char intToChar(int x) {
char temp = '\0';
if (x >= 0 && x <= 9)
temp = (char) (48 + x);
else if (x >= 10 && x <= 15) {
temp = (char) (55 + x);
}
return temp;
}
/**
* 鼠标移动事件
*/
void this_mouseMoved(MouseEvent e) {
int x = 0, y = 0;
x = e.getX();
y = e.getY();
if (x > 20 && x < 460 && y > 20 && y < 460
&& (x % 30 < 10 || x % 30 > 20) && (y % 30 < 10 || y % 30 > 20)) {
this.setCursor(handCursor); // 手状光标
} else {
this.setCursor(defaultCursor);
}
}
/**
* 判断是否有人获胜
*/
protected boolean judge(int x, int y, int clr) {
int i = 0, j = 0, count = 0;
// x方向
for (i = 0, count = 0; x - i >= 0 && i < 5; i++) {
if (clr == board[x - i][y]) {
count++;
} else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
for (i = 1; x + i < 15 && i < 5; i++) {
if (clr == board[x + i][y]) {
count++;
} else {
break;
}
if (count == 5)
return true;
}
// y 方向
for (i = 0, count = 0; y - i >= 0 && i < 5; i++) {
if (clr == board[x][y - i]) {
count++;
} else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
for (i = 1; y + i < 15 && i < 5; i++) {
if (clr == board[x][y + i]) {
count++;
} else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
// '\' 方向
for (i = 0, count = 0; x - i >= 0 && y - i >= 0 && i < 5; i++) {
if (clr == board[x - i][y - i]) {
count++;
} else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
for (i = 1; x + i < 15 && y + i < 15 && i < 5; i++) {
if (clr == board[x + i][y + i]) {
count++;
} else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5) {
return true;
}
}
// '/' 方向
for (i = 0, count = 0; x + i < 15 && y - i >= 0 && i < 5; i++) {
if (clr == board[x + i][y - i]) {
count++;
} else {
count = 0;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
for (i = 1; x - i >= 0 && y + i < 15 && i < 5; i++) {
if (clr == board[x - i][y + i]) {
count++;
} else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5) {
return true;
}
}
return false;
}
class Queue {
int position;
long mark;
};
class Analyse {
Analyse(int chessc[][]) {
int i, j;
chessBoard = new int[17][17];
for (i = 0; i <= 16; i++) {
for (j = 0; j <= 16; j++) {
if (i == 0 || j == 0 || i == 16 || j == 16) {
chessBoard[i][j] = 4;
} else {
chessBoard[i][j] = chessc[i - 1][j - 1];
}
}
}
}
private long pow(int base, int pow) {
int i;
long result = 1;
for (i = 1; i <= pow; i++) {
result *= base;
}
return result;
}
/**
* 方向
*/
private long analyseUd(int x, int y, int side) {
int tt[][] = new int[17][17];
int i, j;
int tempx, tempy;
long mark = 0;
int base = BASE;
int uppersign = 0;
int downsign = 0;
int c_count = 1;
for (i = 0; i < 17; i++) {
for (j = 0; j < 17; j++) {
tt[i][j] = chessBoard[i][j];
}
}
tt[y][x] = side;
// 上下
tempx = x;
tempy = y;
if (tt[tempy - 1][tempx] != side) {
if (tt[tempy - 1][tempx] == 0) {
uppersign = 1;
}
if (tt[tempy - 1][tempx] != 0) {
uppersign = 0;
}
} else {
tempy -= 1;
while (tt[tempy][tempx] == side) {
c_count += 1;
tempy--;
}
if (tt[tempy][tempx] == 0) {
uppersign = 1;
}
if (tt[tempy][tempx] != 0) {
uppersign = 0;
}
}
tempx = x;
tempy = y;
if (tt[tempy + 1][tempx] != side) {
if (tt[tempy + 1][tempx] == 0) {
downsign = 1;
}
if (tt[tempy + 1][tempx] != 0) {
downsign = 0;
}
} else {
tempy += 1;
while (tt[tempy][tempx] == side) {
c_count += 1;
tempy++;
}
if (tt[tempy][tempx] == 0) {
downsign = 1;
}
if (tt[tempy][tempx] != 0) {
downsign = 0;
}
}
mark += pow(base, c_count);
if ((uppersign + downsign) > 0) {
if ((uppersign + downsign) == 2) {
mark *= (uppersign + downsign);
}
if ((uppersign + downsign) == 1) {
mark = mark / 2;
}
} else if (c_count == 5) {
mark *= 4;
} else {
mark = 0;
}
if (c_count == 5) {
mark += INVALID;
}
return mark;
}
private long analyseLr(int x, int y, int side) {
int tt[][] = new int[17][17];
int i, j, tx, ty;
long mark = 0;
int base = BASE, uppersign = 0, downsign = 0, c_count = 1;
for (i = 0; i < 17; i++) {
for (j = 0; j < 17; j++) {
tt[i][j] = chessBoard[i][j];
}
}
tt[y][x] = side;
// 左边和右边
tx = x;
ty = y;
if (tt[ty][tx - 1] != side) {
if (tt[ty][tx - 1] == 0) {
uppersign = 1;
}
if (tt[ty][tx - 1] != 0) {
uppersign = 0;
}
} else {
tx -= 1;
while (tt[ty][tx] == side) {
c_count += 1;
tx--;
}
if (tt[ty][tx] == 0) {
uppersign = 1;
}
if (tt[ty][tx] != 0) {
uppersign = 0;
}
}
tx = x;
ty = y;
if (tt[ty][tx + 1] != side) {
if (tt[ty][tx + 1] == 0) {
downsign = 1;
}
if (tt[ty][tx + 1] != 0) {
downsign = 0;
}
} else {
tx += 1;
while (tt[ty][tx] == side) {
c_count += 1;
tx++;
}
if (tt[ty][tx] == 0) {
downsign = 1;
}
if (tt[ty][tx] != 0) {
downsign = 0;
}
}
mark += pow(base, c_count);
if ((uppersign + downsign) > 0) {
if ((uppersign + downsign) == 2) {
mark *= (uppersign + downsign);
}
if ((uppersign + downsign) == 1) {
mark = mark / 2;
}
} else if (c_count == 5) {
mark *= 4;
} else {
mark = 0;
}
if (c_count == 5) {
mark += INVALID;
}
return mark;
}
private long analyseLdru(int x, int y, int side) {
int tt[][] = new int[17][17];
int i, j;
int tx, ty;
long mark = 0;
int base = BASE;
int uppersign = 0;
int downsign = 0;
int c_count = 1;
for (i = 0; i < 17; i++) {
for (j = 0; j < 17; j++) {
tt[i][j] = chessBoard[i][j];
}
}
tt[y][x] = side;
/* 左下和右上 */
tx = x;
ty = y;
if (tt[ty - 1][tx - 1] != side) {
if (tt[ty - 1][tx - 1] == 0) {
uppersign = 1;
}
if (tt[ty - 1][tx - 1] != 0) {
uppersign = 0;
}
} else {
tx -= 1;
ty -= 1;
while (tt[ty][tx] == side) {
c_count += 1;
tx--;
ty--;
}
if (tt[ty][tx] == 0) {
uppersign = 1;
}
if (tt[ty][tx] != 0) {
uppersign = 0;
}
}
tx = x;
ty = y;
if (tt[ty + 1][tx + 1] != side) {
if (tt[ty + 1][tx + 1] == 0) {
downsign = 1;
}
if (tt[ty + 1][tx + 1] != 0) {
downsign = 0;
}
} else {
tx += 1;
ty += 1;
while (tt[ty][tx] == side) {
c_count += 1;
tx++;
ty++;
}
if (tt[ty][tx] == 0) {
downsign = 1;
}
if (tt[ty][tx] != 0) {
downsign = 0;
}
}
mark += pow(base, c_count);
if ((uppersign + downsign) > 0) {
// mark*=(uppersign+downsign);
if ((uppersign + downsign) == 2) {
mark *= (uppersign + downsign);
}
if ((uppersign + downsign) == 1) {
mark = mark / 2;
}
} else if (c_count == 5) {
mark *= 4;
} else {
mark = 0;
}
if (c_count == 5) {
mark += INVALID;
}
return mark;
}
private long analyseRdlu(int x, int y, int side) {
int tt[][] = new int[17][17];
int i, j;
int tx, ty;
long mark = 0;
int base = BASE;
int uppersign = 0;
int downsign = 0;
int c_count = 1;
for (i = 0; i < 17; i++) {
for (j = 0; j < 17; j++) {
tt[i][j] = chessBoard[i][j];
}
}
tt[y][x] = side;
/* 左下和右上 */
tx = x;
ty = y;
if (tt[ty - 1][tx + 1] != side) {
if (tt[ty - 1][tx + 1] == 0) {
uppersign = 1;
}
if (tt[ty - 1][tx + 1] != 0) {
uppersign = 0;
}
} else {
tx += 1;
ty -= 1;
while (tt[ty][tx] == side) {
c_count += 1;
tx++;
ty--;
}
if (tt[ty][tx] == 0) {
uppersign = 1;
}
if (tt[ty][tx] != 0) {
uppersign = 0;
}
}
tx = x;
ty = y;
if (tt[ty + 1][tx - 1] != side) {
if (tt[ty + 1][tx - 1] == 0) {
downsign = 1;
}
if (tt[ty + 1][tx - 1] != 0) {
downsign = 0;
}
} else {
tx -= 1;
ty += 1;
while (tt[ty][tx] == side) {
c_count += 1;
tx--;
ty++;
}
if (tt[ty][tx] == 0) {
downsign = 1;
}
if (tt[ty][tx] != 0) {
downsign = 0;
}
}
mark += pow(base, c_count);
if ((uppersign + downsign) > 0) {
if ((uppersign + downsign) == 2) {
mark *= (uppersign + downsign);
}
if ((uppersign + downsign) == 1) {
mark = mark / 2;
}
} else if (c_count == 5) {
mark *= 4;
} else {
mark = 0;
}
if (c_count == 5) {
mark += INVALID;
}
return mark;
}
private long analyse(int x, int y, int side) {
long mark = 0;
mark += analyseUd(x, y, side);
mark += analyseLr(x, y, side);
mark += analyseLdru(x, y, side);
mark += analyseRdlu(x, y, side);
return mark;
}
private Queue searchPoint(int chess[][], int deepth) {
// temp
int cx, cy;
// int newdeepth;
char s[] = new char[10];
// temp
Queue pq[] = null, pq_temp[] = null, pq_final;
int temp_chess[][] = new int[17][17];
long mark = 0;
int duce;
int i, j;
int m, n, p, q;
int media;
int MAX;
int k, b;
// mark
MAX = MAX1 <= (225 - STEPCOUNTER) ? MAX1 : (225 - STEPCOUNTER);
if (MAX == (225 - STEPCOUNTER)) {
MINDEEPTH = 1;
}
pq = new Queue[MAX + 1];
for (m = 0; m < MAX; m++) {
pq[m] = new Queue();
}
for (m = 0; m < MAX; m++) {
pq[m].mark = 0;
pq[m].position = 0;
}
for (i = 1; i <= 15; i++) {
// System.out.println();
for (j = 1; j <= 15; j++) {
if (chess[i][j] != 0) {
mark = 0;
} else {
mark = analyse(j, i, 1) / 2 + analyse(j, i, 2);
// System.out.print("\t" + mark);
}
// tempboard[i][j]=mark;
for (m = 0; m < MAX; m++) {
if (mark > pq[m].mark) {
for (n = MAX - 1; n > m; n--) {
pq[n].mark = pq[n - 1].mark;
pq[n].position = pq[n - 1].position;
}
pq[m].mark = mark;
pq[m].position = i * 100 + j;
break;
}
}
}
}
// newdeepth=maxdeepth;
if (pq[0].mark >= INVALID / 2) {
MINDEEPTH = deepth;
}
if (deepth < MINDEEPTH) {
for (m = 0; m < MAX; m++) {
for (p = 0; p <= 16; p++) {
for (q = 0; q <= 16; q++) {
temp_chess[p][q] = chess[p][q];
}
}
if (deepth % 2 == 1) {
media = 2;
} else {
media = 1;
}
temp_chess[pq[m].position / 100][pq[m].position % 100] = media;
pq[m] = searchPoint(temp_chess, deepth + 1);
}
}
pq_temp = new Queue[MAX + 1];
for (m = 0; m < MAX; m++) {
pq_temp[m] = new Queue();
}
for (p = 0; p < MAX; p++) {
pq_temp[p].mark = 0;
pq_temp[p].position = 0;
}
for (p = 0; p < MAX; p++) {
for (q = 0; q < MAX; q++) {
if (pq[p].mark > pq_temp[q].mark) {
for (i = MAX - 1; i > q; i--) {
pq_temp[i] = pq_temp[i - 1];
}
pq_temp[q] = pq[p];
break;
}
}
}
pq_final = pq_temp[0];
return pq_final;
}
public int computerDo() {
int position = 0;
int cx, cy;
position = (searchPoint(chessBoard, 3)).position;
cx = position % 100;
cy = position / 100;
// System.out.print("\n" + cy + "\t" + cx + "\n");
if (cx == 0 && cy == 0) {
return 1;
}
return position;
}
}
}
// 鼠标Adapter
class ChessWZQ_this_mouseAdapter extends java.awt.event.MouseAdapter {
BoardPanel adaptee;
ChessWZQ_this_mouseAdapter(BoardPanel adaptee) {
this.adaptee = adaptee;
}
public void mouseClicked(MouseEvent e) {
adaptee.this_mouseClicked(e);
}
}
class ChessWZQ_this_mouseMotionAdapter extends
java.awt.event.MouseMotionAdapter {
BoardPanel adaptee;
ChessWZQ_this_mouseMotionAdapter(BoardPanel adaptee) {
this.adaptee = adaptee;
}
public void mouseMoved(MouseEvent e) {
adaptee.this_mouseMoved(e);
}
}
package com.test.wzq;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
/**
* @author 原创 java课程设计网 http://www.javakcsj.com/
* @date2018-7-31
*/
public class ChessWZQ extends JFrame {
JPanel contentPane;
BorderLayout borderLayout1 = new BorderLayout();
protected Image white = null;
protected Image black = null;
protected static int pColor; // 人的颜色
protected static int cColor; // 电脑的颜色
static boolean ptocFlag = false;
boolean pFirst = false;
private int bestX = 0; // 电脑找到最好的棋子位置的 X坐标
private int bestY = 0; // 电脑找到最好的棋子位置的Y坐标
private int RectX1 = 0; // 根据坐标 (x,y)确定矩形范围
private int RectY1 = 0; // 长度为 9
private int RectX2 = 0; // 大小为 9*9
private int RectY2 = 0;
private int weightBoard[][];
static Socket socket;
private static int PORT;
static ObjectInputStream in;
static ObjectOutputStream out;
String name = null;
String serverAddress = null;
static char send[];
public static Message message = new Message();
public static boolean beginFlag = false;
BoardPanel bpanel = new BoardPanel();
JPanel jpanel3 = new JPanel();
JLabel label1 = new JLabel("Player1");
JLabel label2 = new JLabel(" VS ");
JLabel label3 = new JLabel("Player2");
JLabel label4 = new JLabel("Player List ");
JLabel label5 = new JLabel("Message list... ");
static JLabel label6 = new JLabel("welcome");
JLabel label7 = new JLabel("Host");
JLabel label8 = new JLabel("Player");
JRadioButton jrbBlack = new JRadioButton("Black");
JRadioButton jrbWhite = new JRadioButton("White");
DefaultListModel lItems = new DefaultListModel();
JList list = new JList(lItems);
JMenuBar mb = new JMenuBar();
JMenu create = new JMenu("Create");
JMenu setting = new JMenu("Setting");
JMenu quit = new JMenu("Quit");
JMenu about = new JMenu("About");
JMenuItem cPtoP = new JMenuItem("Play With people");
JMenuItem cPtoC = new JMenuItem("Play With Computer");
JMenuItem load = new JMenuItem("Load game...");
JMenuItem save = new JMenuItem("Save ...");
// JMenuItem sLimited = new JMenuItem("禁止禁手");
// JMenuItem sNoLimited = new JMenuItem("允许禁手");
public ChessWZQ() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
getContentPane().setLayout(null);
weightBoard = new int[15][15]; // 保存每个位置的重要性
PORT = Server.PORT;// 设置套接字端口
send = new char[60];
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
try {
getContentPane().setLayout(null);
jrbBlack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bpanel.setColor(1);
cColor = 2;
jrbBlack.setEnabled(false);
jrbWhite.setEnabled(false);
drawChess(1);
jrbWhite.setSelected(true);
if (ptocFlag == true) {
return;
}
Message ms = new Message();
ms.color = 1;
ms.type = 13;
try {
out.writeObject(ms);
} catch (IOException error) {
error.printStackTrace();
}
}
});
jrbWhite.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bpanel.setColor(2);
cColor = 1;
jrbWhite.setEnabled(false);
jrbBlack.setEnabled(false);
drawChess(2);
jrbBlack.setSelected(false);
if (ptocFlag == true) {
return;
}
Message ms = new Message();
ms.color = 2;
ms.type = 13;
try {
out.writeObject(ms);
} catch (IOException error) {
error.printStackTrace();
}
}
});
about.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JOptionPane
.showMessageDialog(
null,
"Author: Kahn \nCopyright (c) 2007-CUIT \nMail:zhao4824593@163.com",
"五子棋1.0(beta)",
JOptionPane.INFORMATION_MESSAGE);
}
});
quit.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int flag = JOptionPane.showConfirmDialog(null,
"Quit the Program ?", "Are you sure to quit ?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (flag == 0) { // 确定
// 断开和服务端的连接
sendDisconnect();
System.exit(0);
}
}
});
setting.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Object selection[] = { "Forbiden", "Allow any" };
Object set = JOptionPane.showInputDialog(null,
"Setting...", "would you allow any method?",
JOptionPane.QUESTION_MESSAGE, null, selection,
selection[0]);
if (ptocFlag == true) {
return;
}
Message ms = new Message();
if (set == null) {
return;
}
if (set.toString().equals(selection[0])) {
ms.setting = false;
} else {
ms.setting = true;
}
// System.out.println("setting begin..."+msg.setting);
ms.type = 12;
try {
out.writeObject(ms);
} catch (IOException error) {
error.printStackTrace();
}
}
});
cPtoP.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ptocFlag = false;
JOptionPane
.showMessageDialog(
null,
"You can choose a player from the listBox on the right",
"Welcome...",
JOptionPane.INFORMATION_MESSAGE);
}
});
cPtoC.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (ptocFlag == true) {
int flag = JOptionPane.showConfirmDialog(null,
"You give up... ?", "Message",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (flag == 0) {
newGame();
return;
}
}
label3.setText("Computer");
Object selection[] = { "Computer First", "You First" };
Object set = JOptionPane.showInputDialog(null,
"choose who first...", "setting...",
JOptionPane.QUESTION_MESSAGE, null, selection,
selection[0]);
ptocFlag = true;
if (set.toString().equals(selection[1])) {
pFirst = true;
} else {
pFirst = false;
}
pColor = bpanel.getColor();
if (pColor == 1) {
jrbBlack.setSelected(true);
jrbWhite.setSelected(false);
cColor = 2;
} else {
jrbWhite.setSelected(true);
jrbBlack.setSelected(false);
cColor = 1;
}
jrbBlack.setEnabled(false);
jrbWhite.setEnabled(false);
ptoComputer();
}
});
create.setBounds(5, 5, 40, 20);
setting.setBounds(45, 5, 40, 20);
quit.setBounds(85, 5, 40, 20);
about.setBounds(125, 5, 40, 20);
create.add(cPtoP);
create.add(cPtoC);
// create.add(load);
// create.add(save);
mb.add(create);
mb.add(setting);
mb.add(quit);
mb.add(about);
this.setJMenuBar(mb);
bpanel.setBounds(0, 0, 470, 460);
bpanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 1,
Color.ORANGE));
jpanel3.setLayout(null);
jpanel3.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1,
Color.DARK_GRAY));
jpanel3.setBounds(470, 0, 180, 460);
label7.setBounds(10, 10, 30, 20);
label7.setBackground(Color.blue);
label7.setForeground(Color.yellow);
label8.setBounds(90, 10, 40, 30);
label8.setBackground(Color.blue);
label8.setForeground(Color.yellow);
label1.setBounds(10, 40, 50, 20);
label2.setForeground(Color.RED);
label2.setBounds(60, 40, 50, 20);
label3.setBounds(90, 40, 70, 20);
label4.setForeground(Color.BLUE);
label4.setBounds(10, 78, 70, 20);
label5.setBackground(Color.magenta);
label5.setForeground(Color.RED);
label5.setBounds(15, 395, 160, 20);
label6.setBounds(15, 415, 180, 20);
// label6.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.yellow));
jrbBlack.setSelected(true);
jrbBlack.setBounds(10, 380, 80, 15);
jrbWhite.setBounds(90, 380, 80, 15);
list.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1,
Color.black));
list.setBounds(10, 100, 150, 265);
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// 双击选择玩家
if (e.getClickCount() == 2) {
String str = list.getSelectedValue().toString();
if (str.equals(name) == true) {
label6.setText("You can't choose yourself");
return;
}
label3.setText(str);
list.setEnabled(false);
Message ms = new Message();
ms.type = 3; // 请求和别人游戏
strToCharArray(str, ms.msg);
ms.color = bpanel.getColor();
// System.out.println("request for play with "+str);
try {
out.writeObject(ms);
} catch (IOException er) {
er.printStackTrace();
}
}
}
});
jpanel3.add(label1);
jpanel3.add(label2);
jpanel3.add(label3);
jpanel3.add(label4);
jpanel3.add(label5);
jpanel3.add(label6);
jpanel3.add(label7);
// jpanel3.add(label8);
jpanel3.add(jrbBlack);
jpanel3.add(jrbWhite);
jpanel3.add(list);
// getContentPane().add(jpanel1);
getContentPane().add(bpanel);
getContentPane().add(jpanel3);
// lItems.add(0,"Kahn1");
// lItems.add(0,"Kahn2");
} catch (Exception e) {
e.printStackTrace();
}
}
// 组件初始化
private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(borderLayout1);
this.setSize(new Dimension(660, 530));
this.setTitle("五子棋客户端(beta)");
}
/**
* 发送断开请求到服务端 type = 7
*/
public void sendDisconnect() {
Message ms = new Message();
ms.type = 7;
try {
out.writeObject(ms);
} catch (IOException e) {
e.printStackTrace();
}
}
public void drawChess(int col) {
Graphics g = jpanel3.getGraphics();
if (col == 1)
g.setColor(Color.black);
else
g.setColor(Color.white);
g.fillOval(50, 10, 20, 20);
}
/**
* 格式: java ChessWZQ < server address> args[0]=服务端地址
* args[1]=玩家名字
*/
public static void main(String[] args) {
System.out.println("**************运行客户端********************");
ChessWZQ wzq = new ChessWZQ();
wzq.setResizable(false);
wzq.setVisible(true);
wzq.drawChess(1); // 默认颜色为黑色
Message ms = new Message();
if (args[0] != null)
wzq.serverAddress = new String(args[0]);
else
wzq.serverAddress = new String("localhost");
if (args[1] != null)
wzq.name = new String(args[1]);
else
wzq.name = new String("Kahn");
wzq.strToCharArray(wzq.name, ms.msg);
try {
// 从命令行得到服务端名字
InetAddress addr = InetAddress.getByName(wzq.serverAddress);
// System.out.println("address "+ addr.toString()+" port: "+PORT);
socket = new Socket(addr, PORT);
// System.out.println("set socket successful...");
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
ms.type = 1;
try {
out.writeObject(ms);
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
ms = (Message) in.readObject();
// System.out.println("get message from server...type = "+ms.type);
wzq.doMessage(ms);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// System.out.println("ms.coordinateX + , + msg.coordinateY");
// System.out.println(ms.color);
// System.out.println("close ...");
// socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 处理从服务端发来的信息 msg
*/
protected int doMessage(Message msg) {
String str = arrayToString(msg.msg);
// System.out.println("msg name = "+str+" msg.type = "+msg.type);
switch (msg.type) {
case 2: {// 响应放棋子
putChessman(msg);
break;
}
case 3: {// 其他玩家的请求
requestAnother(msg);
break;
}
case 4: { // B拒绝和A游戏
getDeny(msg);
break;
}
case 5: { // B 接收A的请求
acceptToPlay(msg);
break;
}
case 6: {
getVictory(msg);
break;
}
case 7: {
getDisconnection(msg);
break;
}
case 9: {// 回复添加新玩家到所有的客户端
// /System.out.println("add new player to list type = 9 name = "+str+"msg[0]= "+msg.msg[0]);
lItems.add(0, str);
break;
}
case 10: { // 连接回复
// System.out.println("add him self type = 10 name = "+str+"msg[0]= "+msg.coordinateX+msg.msg[0]);
label1.setText(str);
label6.setText("welcome " + str);
lItems.add(0, str);
break;
}
case 14: { // B接收和A游戏,设置MSG及设置游戏选项
break;
}
case 15: {
lItems.clear();
break;
}
case 17: {
getFailed(msg);
break;
}
case 20: {
ptocWin(msg);
break;
}
}
return 0; // 结束
}
private void ptocWin(Message ms) {
String str = this.arrayToString(ms.msg);
JOptionPane.showMessageDialog(null, str + " win the game!",
"Win the game", JOptionPane.INFORMATION_MESSAGE);
newGame();
}
/**
* 游戏失败并开始新的游戏 type == 17 msg
*/
public void getFailed(Message msg) {
bpanel.drawChess(msg.coordinateX, msg.coordinateY);
JOptionPane.showMessageDialog(null, "Sorry,You've failed the game",
"Try Again", JOptionPane.INFORMATION_MESSAGE);
label3.setText("Player2");
// 继续新游戏
newGame();
}
/**
* 另一个玩家发送断开请求 type ==7 msg
*/
public void getDisconnection(Message msg) {
getVictory(msg);
}
/**
* 游戏胜利 type ==6 msg
*/
public void getVictory(Message msg) {
JOptionPane.showMessageDialog(null, "You Win The Game",
"Congratulations", JOptionPane.INFORMATION_MESSAGE);
// 继续新游戏
label3.setText("Player2");
newGame();
}
/**
* 当人获胜时 ,他能够开始新游戏 msg
*/
public void newGame() {
jrbBlack.setEnabled(true);
jrbWhite.setEnabled(true);
jrbBlack.setSelected(true);
jrbWhite.setSelected(false);
list.setEnabled(true);
setting.setEnabled(true);
bpanel.clearBoard();
drawChess(1);
pColor = 1;
cColor = 2;
if (ptocFlag == false) {
Message msg = new Message();
msg.type = 19;
strToCharArray(name, msg.msg);
try {
out.writeObject(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
ptocFlag = false;
beginFlag = false;
}
public void putChessman(Message msg) {
if (ptocFlag == false) {
bpanel.updateBoard(msg.coordinateX, msg.coordinateY);
bpanel.drawChess(msg.coordinateX, msg.coordinateY);
beginFlag = true;
return;
} else {
// 更新本地面板
// 搜索最优坐标并下棋
}
}
/**
* A从B收到确定消息并根据B来设置 type= 5 B 接受和A游戏 msg = B的名字
*/
public void acceptToPlay(Message msg) {
String str = arrayToString(msg.msg);
String ss = null;
if (msg.color == 1) {
ss = new String("white");
bpanel.setColor(2);
} else {
ss = new String("black");
bpanel.setColor(1);
}
JOptionPane.showMessageDialog(null, "OK. " + str
+ " have accepted your requestion\nYour color is" + ss,
"Game will to begin...", JOptionPane.ERROR_MESSAGE);
list.setEnabled(false);
jrbBlack.setEnabled(false);
jrbWhite.setEnabled(false);
setting.setEnabled(false);
beginFlag = true;
}
/**
* A收到B的拒绝信息 type ==4 拒绝游戏 msg
*/
public void getDeny(Message msg) {
String str = arrayToString(msg.msg);
JOptionPane.showMessageDialog(null, "I'm sorry\n" + str
+ " denied your requestion", "Sorry...",
JOptionPane.ERROR_MESSAGE);
list.setEnabled(true);
label3.setText("Player2");
}
/**
* A请求和B游戏,B的动作如下 msg = 请求者的名字
*/
public void requestAnother(Message msg) {
String str = arrayToString(msg.msg);
// System.out.print("client requestAnother begin ...");
int flag = JOptionPane.showConfirmDialog(null, "Player " + str
+ " want to play with you\nAre you OK?", "Play request...",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (flag == 0) {// 确定
msg.type = 5; // 同意请求
if (msg.color == 1) { // msg.color为B的颜色
drawChess(msg.color);
jrbBlack.setSelected(true);
jrbWhite.setSelected(false);
bpanel.setColor(1);
} else {
drawChess(msg.color);
jrbWhite.setSelected(true);
jrbBlack.setSelected(false);
bpanel.setColor(2);
}
// System.out.println("B's color is"+msg.color);
list.setEnabled(false);
label3.setText(str);
setting.setEnabled(false);
jrbBlack.setEnabled(false);
jrbWhite.setEnabled(false);
beginFlag = true;
}
if (flag == 1) {// 拒绝请求
msg.type = 4;
}
try {
out.writeObject(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
super.paint(g);
drawChess(bpanel.getColor());
}
/**
* 当WINDOWS关闭时能退出
*/
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.exit(0);
}
}
// 把字符串转换成数组并以'\0'结束
public void strToCharArray(String str, char[] arr) {
int i;
for (i = 0; i < str.length() && i < 49; i++) {
arr[i] = str.charAt(i);
}
arr[i] = '\0';
}
/**
* 在数组的末端过滤黑棋的位置 arr str
*/
public String arrayToString(char[] arr) {
int i = 0, length = 0;
while (arr[i] != '\0' && i < 50) {
i++;
}
length = i;
char[] ss = new char[length];
for (i = 0; i < length; i++) {
ss[i] = arr[i];
}
String str = new String(ss);
return str;
// System.out.println("arraytoString "+str+"length = "+length);
}
/**
* 人和电脑对战
*/
public void ptoComputer() {
int x = 0, y = 0;
int position;
if (pFirst == false) {
x = 7;
y = 7;
bpanel.updateBoard(x, y);
bpanel.drawChess(x, y);
beginFlag = true;
} else {
beginFlag = true;
}
}
/**
* 选择最优的位置下棋
*/
private void cPutChess(int x, int y) {
setRect(x, y);
setWeight(x, y, pColor);
getBetter(3);
}
/**
* 9*9矩形
*/
private void setRect(int x, int y) {
if (x - 4 > 0)
RectX1 = x - 4;
else
RectX1 = 0;
if (x + 4 > 14)
RectX2 = 14;
else
RectX2 = x + 4;
if (y - 4 > 0)
RectY1 = y - 4;
else
RectY1 = 0;
if (y + 4 > 14)
RectY2 = 14;
else
RectY2 = y + 4;
if (RectX1 > RectY1)
RectX1 = x - (y - RectY1);
else
RectY1 = y - (x - RectX1);
if (RectX2 > RectY2)
RectY2 = y + (RectX2 - x);
else
RectX2 = x + (RectY2 - y);
}
/**
* 在范围内设定黑棋重要性
*/
private void setWeight(int x, int y, int tcolor) {
int i = RectX1, j = RectY1, value = 0, k = 0, n = 0, flag = 0;
// '--' 方向
for (i = RectX1, j = y; i <= RectX2; i++) {
if (BoardPanel.board[i][j] != 0) {
continue;
}
value = 0;
flag = 0;
for (k = 1; i - k >= RectX1 && k < 5; k++) {
if (BoardPanel.board[i - k][j] == tcolor) {
value++;
continue;
}
if (BoardPanel.board[i - k][j] == 0) {// black space
flag++;
break;
}
}
for (k = 1; i + k < RectX2 && k < 5; k++) {
if (BoardPanel.board[i + k][j] == tcolor) {
value++;
}
if (BoardPanel.board[i + k][j] == 0) {
flag++;
break;
}
}
n = weight(value, flag);
if (weightBoard[i][j] < n) {
weightBoard[i][j] = n;
}
}
// '|' 方向
for (i = x, j = RectY1; j <= RectY2; j++) {
if (BoardPanel.board[i][j] != 0) {
continue;
}
value = 0;
flag = 0;
for (k = 1; j - k >= RectY1 && k < 5; k++) {
if (BoardPanel.board[i][j - k] == tcolor) {
value++;
continue;
}
if (BoardPanel.board[i][j - k] == 0) {
flag++;
break;
}
}
for (k = 1; j + k < RectY2 && k < 5; k++) {
if (BoardPanel.board[i][j + k] == tcolor) {
value++;
}
if (BoardPanel.board[i][j + k] == 0) {
flag++;
break;
}
}
n = weight(value, flag);
if (weightBoard[i][j] < n) {
weightBoard[i][j] = n;
}
}
// '\' 方向
for (i = RectX1, j = RectY1; i <= RectX2; i++, j++) {
if (BoardPanel.board[i][j] != 0) {
continue;
}
value = 0;
flag = 0;
for (k = 1; i - k >= RectX1 && k < 5; k++) {
if (BoardPanel.board[i - k][j - k] == tcolor) {
value++;
continue;
}
if (BoardPanel.board[i - k][j - k] == 0) {
flag++;
break;
}
}
for (k = 1; i + k < RectX2 && k < 5; k++) {
if (BoardPanel.board[i + k][j + k] == tcolor) {
value++;
}
if (BoardPanel.board[i + k][j + k] == 0) {
flag++;
break;
}
}
n = weight(value, flag);
if (weightBoard[i][j] < n) {
weightBoard[i][j] = n;
}
}
// '/' 方向
for (i = RectX2, j = RectY1; i >= RectX1; i--, j++) {
if (BoardPanel.board[i][j] != 0) {
continue;
}
value = 0;
flag = 0;
for (k = 1; i + k <= RectX2 && k < 5; k++) {
if (BoardPanel.board[i + k][j - k] == tcolor) {
value++;
continue;
}
if (BoardPanel.board[i + k][j - k] == 0) {
flag++;
break;
}
}
for (k = 1; i - k >= RectX1 && k < 5; k++) {
if (BoardPanel.board[i - k][j + k] == tcolor) {
value++;
}
if (BoardPanel.board[i - k][j + k] == 0) {
flag++;
break;
}
}
n = weight(value, flag);
if (weightBoard[i][j] < n) {
weightBoard[i][j] = n;
}
}
}
/**
* 返回重量值 count flag
*/
private int weight(int count, int flag) {
int weight = 0;
switch (count) {
case 0: {
if (flag > 0)
weight = 200;
else
weight = 0;
break;
}
case 1: {
if (flag > 0)
weight = 1000;
else
weight = 0;
break;
}
case 2: {
if (flag > 0)
weight = 5000;
else
weight = 0;
break;
}
case 3: {
if (flag > 0)
weight = 8000;
else
weight = 0;
break;
}
case 4: {
if (flag > 0)
weight = 10000;
else
weight = 0;
break;
}
}
return weight;
}
/**
* 搜索整个面板找到更好的计数位置,默认值为3
*/
private void getBetter(int count) {
int[][] better = new int[count][2];
int[][] tempArray = new int[15][15];
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
tempArray[i][j] = weightBoard[i][j];
}
}
for (int i = 0; i < count; i++) {
getBiggest(tempArray, better[i][0], better[i][1]);
}
bestX = better[0][0];
bestY = better[0][1];
}
/**
* arr x y
*/
private void getBiggest(int[][] arr, int x, int y) {
int[] temp = new int[2];
int swt = arr[0][0], tmp = 0;
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if (arr[i][j] > swt) {
temp[0] = i;
temp[1] = j;
swt = arr[i][j];
}
}
}
x = temp[0];
y = temp[1];
arr[x][y] = 0;
}
}
package com.test.wzq;
/**
* @author 原创 java课程设计网 http://www.javakcsj.com/
* @date2018-7-31
*/
public class Group {
String self = null;
ServeOneClient selfSocket = null;
String player = null;
ServeOneClient playerSocket = null;
int selfColor = 0;
int playerColor = 0;
boolean Setting = false;
int board[][];
public Group() {
board = new int[15][15];
}
}
package com.test.wzq;
import java.io.Serializable;
/**
* 消息列表
* type = 1 // 请求连接, msg = 连接者名字
* type = 2 // 放棋子
* type = 3 // 请求和其他人游戏
* type = 4 // 拒绝游戏请求
* type = 5 // 同意请求
* type = 6 // 发送胜利消息
* type = 7 // 断开连接请求
* type = 8 // 保存游戏,但是不放在磁盘上,在下一局开始时将会丢失
* type = 9 // 添加新的玩家到所有客户端的玩家列表
* type = 10// 响应信息 type ==1
* type = 11// 和玩家游戏,msg 保存玩家的名字 ,创建游戏的玩家设置游戏
* type = 12//信息设置
* type = 13// 设置玩家颜色
* type = 14// msg= 接受请求的一方设置
* type = 15// 服务端更新信息
* type = 16// 发送控制或错误信息
* type = 17// 游戏失败
* type = 18// 服务端套接字关闭
* type = 19// 玩家结束游戏及更新
* tyep = 20// 电脑获胜/ 玩家获胜
*/
/**
* @author 原创 java课程设计网 http://www.javakcsj.com/
* @date2018-7-31
*/
public class Message implements Serializable // 启用其序列化功能
{
byte type; // 消息类型 ,eg.1=请求连接
boolean setting; // 是否设置禁手
int color; // 棋子颜色 ,1 = black ,2 = white
boolean forYourTurn; // 判断是否轮到接收者下棋
int coordinateX; // 记录坐标(X,Y)
int coordinateY;
char[] msg; // 消息主体
public Message() {
setting = true;
msg = new char[50];
// StringBuffer ss = new StringBuffer(50);
}
}
package com.test.wzq;
import java.net.Socket;
/**
* @author 原创 java课程设计网 http://www.javakcsj.com/
* @date2018-7-31
*/
public class Player {
String self = null;
ServeOneClient selfSocket = null;
boolean setting = false;
int color = 1;
public Player() {
}
/*
* public Player(Player pp){ self = new String(pp.self); selfSocket =
* pp.selfSocket; player = new String(pp.player); playerSocket =
* pp.playerSocket; }
*/
}
package com.test.wzq;
import java.io.*;
import java.net.*;
/**
* @author 原创 java课程设计网 http://www.javakcsj.com/
* @date2018-7-31
*/
public class ServeOneClient extends Thread {
private Socket socket;
private String player = null;
protected ObjectInputStream in;
protected ObjectOutputStream out;
public ServeOneClient(Socket s) throws IOException {
socket = s;
// System.out.println("server socket begin ...");
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
// System.out.println("server socket in and out ...");
// 如果所有的请求都抛出异常,请求者负责关闭套接字,否则线程会将其关闭
start();
}
public void run() {
Message obj = new Message();
while (true) {
try {
obj = (Message) in.readObject();
doMessage(obj);
} catch (ClassNotFoundException er) {
} catch (IOException e) {
}
}
/*
* System.out.println("closing..."); try { socket.close(); }catch
* (IOException e) {}
*/
}
/**
* 处理消息 msg 1= 成功的请求 2=套接字关闭
*/
public int doMessage(Message msg) {
// System.out.println("doMessage begin...type="+msg.type);
switch (msg.type) {
case 1: {// 新的连接到服务端
sendNewPlayer(msg); // 客户端必须返回类型type==10
addPlayer(msg); // msg.msg == 新玩家的名字
break;
}
case 2: {// 下棋子
putChessman(msg);
break;
}
case 3: {// 请求其他人游戏
requestAnother(msg);
break;
}
case 4: {
denyRequest(msg);
break;
}
case 5: {
acceptRequest(msg);
break;
}
case 6: {// 胜利请求
checkVictory(msg);
break;
}
case 7: {// 断开请求
getdisconnect(msg);
break;
}
case 8: {// 保存游戏
break;
}
case 12: {// 信息设置
boolean flag = true;
setting(msg, flag);
break;
}
case 13: {
boolean flag = false;
setting(msg, flag);
break;
}
case 19: {
playerRefresh(msg);
break;
}
case 20: {
try {
this.out.writeObject(msg);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
default: {
}
}
return 0; // 完毕
}
/**
* 判断游戏,更新所有的客户端面板 type = 7 发起者将要关闭游戏
*/
public void getdisconnect(Message msg) {
Group gg = null;
Player pp = null;
String str = null;
// 如果发起连接的人在一个组
for (int i = 0; i < Server.groupList.size(); i++) {
gg = (Group) Server.groupList.get(i);
if (this.equals(gg.selfSocket) == true) {
msg.type = 6; // gg.player win
try {
gg.playerSocket.out.writeObject(msg);
} catch (IOException e) {
e.printStackTrace();
}
sendLeftMsg(gg.self);
// 更新列表
Server.groupList.remove(gg);
return;
}
if (this.equals(gg.playerSocket) == true) {
msg.type = 6;
try {
gg.selfSocket.out.writeObject(msg);
} catch (IOException e) {
e.printStackTrace();
}
sendLeftMsg(gg.player);
Server.groupList.remove(gg);
return;
}
}
// 发起断开连接请求的玩家是否在列表里
for (int i = 0; i < Server.playerList.size(); i++) {
pp = (Player) Server.playerList.get(i);
if (this.equals(pp.selfSocket) == true) {
break;
}
}
sendLeftMsg(pp.self);
Server.playerList.remove(pp); // 移去断开者
updateClient();
}
private void sendLeftMsg(String str) {
char cc;
for (int i = 0; i < 50; i++) {
cc = str.charAt(i);
if (cc != '\0')
System.out.print(cc);
else
break;
}
System.out.print(" has left server ...\n");
}
/**
* 拒绝玩家请求 type ==4 msg == 拒绝者的名字
*/
public void denyRequest(Message msg) {
String denyName = null;
Player pp = null;
for (int i = 0; i < Server.playerList.size(); i++) {
pp = (Player) Server.playerList.get(i);
if (this.equals(pp.selfSocket) == true) {
denyName = new String(pp.self);
break;
}
}
for (int i = 0; i < Server.playerList.size(); i++) {
pp = (Player) Server.playerList.get(i);
if (arrayMatchString(msg.msg, pp.self) == true) {
Message ms = new Message();
ms.type = 4;
strToCharArray(denyName, ms.msg);
try {// requestor 's socket send msg to it's client
pp.selfSocket.out.writeObject(ms);
} catch (IOException er) {
er.printStackTrace();
}
break;
}
}
}
/**
* B接受请求,A 服务端 更新列表 type ==5 msg == A的名字
*/
public void acceptRequest(Message msg) {
Player pps = null, ppd = null;// ppd = B pps = A
String acceptName = null;
for (int i = 0; i < Server.playerList.size(); i++) {
ppd = (Player) Server.playerList.get(i);
if (this.equals(ppd.selfSocket) == true) {
break;
}
}
for (int i = 0; i < Server.playerList.size(); i++) {
pps = (Player) Server.playerList.get(i);
if (arrayMatchString(msg.msg, pps.self) == true) {
break;
}
}
Message ss = new Message();
ss.type = 14; // B玩家设置颜色
ss.color = msg.color;
try {
ppd.selfSocket.out.writeObject(ss);
} catch (IOException e) {
e.printStackTrace();
}
ss.type = 5; // B接受A的请求
strToCharArray(ppd.self, ss.msg);
try {
pps.selfSocket.out.writeObject(ss);
} catch (IOException e) {
e.printStackTrace();
}
// 上传列表并显示,服务端显示数组列表
Group p1 = new Group();
p1.self = new String(pps.self);
p1.selfSocket = pps.selfSocket;
p1.selfColor = pps.color;
p1.player = new String(ppd.self);
p1.playerSocket = ppd.selfSocket;
if (p1.selfColor == 1) {
p1.playerColor = 2;
} else {
p1.playerColor = 1;
}
p1.Setting = pps.setting;
Server.groupList.add(p1);
// /System.out.println(p1.self+p1.selfColor+" player "+p1.player+p1.playerColor);
if (Server.playerList.size() == 2) {
msg.type = 15;
try {
pps.selfSocket.out.writeObject(msg);
ppd.selfSocket.out.writeObject(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
Server.playerList.remove(pps);
Server.playerList.remove(ppd);
// System.out.println(" after create a group,playerlist size = "+Server.playerList.size());
updateClient();
}
/**
* 当新组创建或玩家离开时更新CLIENT端列表
*/
public void updateClient() {
Message msg = new Message();
Player pp = null, ppm = null;
for (int i = 0; i < Server.playerList.size(); i++) {
pp = (Player) Server.playerList.get(i);
msg.type = 15; // 更新客户端玩家列表
try { // 清空列表
// System.out.println("clear "+pp.self+"'s list box");
pp.selfSocket.out.writeObject(msg);
} catch (IOException e) {
e.printStackTrace();
}
for (int j = 0; j < Server.playerList.size(); j++) {
ppm = (Player) Server.playerList.get(j);
strToCharArray(ppm.self, msg.msg);
msg.type = 9;
try {
// System.out.println("updating ..."+pp.self+" list box about"+ppm.self);
pp.selfSocket.out.writeObject(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 稍后,同一组玩家的列表将会更新
}
/**
* 判断arr[] 是否等于 str
*/
private boolean arrayMatchString(char[] arr, String str) {
for (int i = 0; i < 50 && str.charAt(i) != '\0'; i++) {
if (arr[i] != str.charAt(i))
return false;
}
return true;
}
/**
* type ==3
*/
public void requestAnother(Message msg) {
Player pp = null; // 接收者
Player spp = null; // 发送者
String senderName = null;
// 获得发起者的名字
for (int i = 0; i < Server.playerList.size(); i++) {
spp = (Player) Server.playerList.get(i);
if (this.equals(spp.selfSocket) == true) {
senderName = new String(spp.self);
// System.out.println("requestor 's name = "+senderName);
break;
}
}
for (int i = 0; i < Server.playerList.size(); i++) {
pp = (Player) Server.playerList.get(i);
if (arrayMatchString(msg.msg, pp.self) == true) {
Message ms = new Message();
strToCharArray(senderName, ms.msg);
ms.type = 3;
if (spp.color == 1) {
ms.color = 2; // set another's color
} else {
ms.color = 1;
}
ms.setting = spp.setting;
try {// 玩家B的套接字发送 msg 到B的客户端
pp.selfSocket.out.writeObject(ms);
// System.out.println("type= "+ms.type+" "+pp.self+
// " send msg to name = "+ms.msg[0]+"with B's color"+ms.color);
} catch (IOException er) {
er.printStackTrace();
}
break;
}
}
}
// 以'\0'结束,把字符串转换成数组
public void strToCharArray(String str, char[] arr) {
int i = 0;
for (i = 0; i < str.length() && i < 49; i++) {
arr[i] = str.charAt(i);
}
arr[i] = '\0';
}
/**
* 设置信息标志 msg
*/
public void setting(Message msg, boolean flag) {
int i = 0;
Player pp = null;
for (i = 0; i < Server.playerList.size(); i++) {
pp = (Player) Server.playerList.get(i);
if (this.equals(pp.selfSocket) == true) {
if (flag == true)
pp.setting = msg.setting;
else
pp.color = msg.color;
// System.out.println("setting "+pp.setting+"color = "+pp.color);
}
}
}
/**
* 在数组的结束端过滤黑棋所占的空间
*/
public String arrayToString(char[] arr) {
int i = 0, length = 0;
while (arr[i] != '\0' && i < 50) {
i++;
}
length = i;
char[] ss = new char[length];
for (i = 0; i < length; i++) {
ss[i] = arr[i];
}
String str = new String(ss);
return str;
// System.out.println("arraytoString "+str+"length = "+length);
}
/**
* 添加新玩家到所有的CLIENT端玩家列表 读取服务端玩家列表并发送到每个CLIENT上
*/
public void sendNewPlayer(Message player) {
Player pp = null;
player.type = 9;
// System.out.println("send new Player ...");
for (int i = 0; i < Server.playerList.size(); i++) {
pp = (Player) Server.playerList.get(i);
try {
if (pp.self != null) {// 发送信息到其他人,除了自己
// System.out.println(pp.self+" add list "+player.msg[0]+"i = "+i);
pp.selfSocket.out.writeObject(player);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 玩家结束游戏并等待
*/
public void playerRefresh(Message player) {
Player ppo = new Player();
Player pp = null;
ppo.color = player.color;
ppo.self = new String(player.msg);
ppo.selfSocket = this;
Server.playerList.add(ppo);
for (int i = 0; i < Server.playerList.size(); i++) {
pp = (Player) Server.playerList.get(i);
if (this.equals(pp.selfSocket) == false) {
Message msg = new Message();
strToCharArray(pp.self, msg.msg);
msg.type = 9;
msg.color = pp.color;
// System.out.println("refresh " + pp.self + "serverlist size "
// +
// Server.playerList.size());
try {
this.out.writeObject(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Message ms = new Message();
strToCharArray(ppo.self, ms.msg);
ms.type = 10;
try {
this.out.writeObject(ms);
} catch (IOException e) {
e.printStackTrace();
}
// Message ms = new Message();
player.type = 10;
for (int i = 0; i < Server.playerList.size(); i++) {
pp = (Player) Server.playerList.get(i);
if (this.equals(pp.selfSocket) != true) {
try {
pp.selfSocket.out.writeObject(player);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 添加新玩家到服务端玩家列表
*/
public void addPlayer(Message player) {
int i = 0;
Player pp = null, tp = null;
for (i = 0; i < Server.playerList.size(); i++) {
pp = (Player) Server.playerList.get(i);
if (this.equals(pp.selfSocket) == true) {
// System.out.println("match socket ok and send to itself...");
pp.self = new String(player.msg);
try {
for (int j = 0; j < Server.playerList.size(); j++) {
Message temp = new Message();
tp = (Player) Server.playerList.get(j);
if (tp.self != null) {
strToCharArray(tp.self, temp.msg);
// temp.coordinateX=(byte)j;
temp.type = 10; // reply for type==1
// System.out.println("host "+pp.self+" add list to client name = "+temp.coordinateX+temp.msg[0]);
pp.selfSocket.out.writeObject(temp);
}
}
// out.writeObject(player);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}/*
* System.out.print("welcome "); int k=0; while(true){
* if(player.msg[k]!='\0') System.out.print(player.msg[k++]); else
* break; } System.out.println();
*/
// System.out.println(" at "+pp.selfSocket.socket.toString());
}
public Socket getSocket() {
return socket;
}
/**
* 检查MSG发送者是否获胜 type=6 msg = 获胜者的名字
*/
public void checkVictory(Message msg) {
}
/**
* type = 2 ,(msg.coordinateX,msg.coordinateY).msg.color
*/
public void putChessman(Message msg) {
Group gg = new Group();
ServeOneClient soc = null;
String tName = null;
int color = 0;
// 修改服务段面板
for (int i = 0; i < Server.groupList.size(); i++) {
gg = (Group) Server.groupList.get(i);
if (this.equals(gg.selfSocket) == true) {
soc = gg.playerSocket;
tName = new String(gg.player);
color = gg.selfColor;
break;
}
if (this.equals(gg.playerSocket) == true) {
soc = gg.selfSocket;
tName = new String(gg.self);
color = gg.playerColor;
break;
}
}
gg.board[msg.coordinateX][msg.coordinateY] = color;
// 判断是否有人获胜
if (judge(gg, msg.coordinateX, msg.coordinateY) == true) {// 一方获胜
// 告诉双方并从列表中移开
try {
msg.type = 6; // 胜利
this.out.writeObject(msg);
msg.type = 17; // 失败
soc.out.writeObject(msg);
// System.out.println("send failed to "+tName);
} catch (IOException e) {
e.printStackTrace();
}
Server.groupList.remove(gg); // 从列表中移开
return;
}
// 发送msg到其他玩家
try {
// System.out.println("server put chess man "+msg.coordinateX+","+msg.coordinateY);
soc.out.writeObject(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 判断是否有人获胜
*/
private boolean judge(Group gg, int x, int y) {
int i = 0, j = 0, count = 0;
int color = gg.board[x][y];
// x 方向
for (i = 0, count = 0; x - i >= 0 && i < 5; i++) {
if (color == gg.board[x - i][y]) {
count++;
} else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
for (i = 1; x + i < 15 && i < 5; i++) {
if (color == gg.board[x + i][y]) {
count++;
} else {
break;
}
if (count == 5)
return true;
}
// y 方向
for (i = 0, count = 0; y - i >= 0 && i < 5; i++) {
if (color == gg.board[x][y - i]) {
count++;
} else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
for (i = 1; y + i < 15 && i < 5; i++) {
if (color == gg.board[x][y + i]) {
count++;
} else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
// '\' 方向
for (i = 0, count = 0; x - i >= 0 && y - i >= 0 && i < 5; i++) {
if (color == gg.board[x - i][y - i]) {
count++;
} else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
for (i = 1; x + i < 15 && y + i < 15 && i < 5; i++) {
if (color == gg.board[x + i][y + i]) {
count++;
} else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5) {
return true;
}
}
// '/' 方向
for (i = 0, count = 0; x + i < 15 && y - i >= 0 && i < 5; i++) {
if (color == gg.board[x + i][y - i]) {
count++;
} else {
count = 0;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
for (i = 1; x - i >= 0 && y + i < 15 && i < 5; i++) {
if (color == gg.board[x - i][y + i]) {
count++;
} else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5) {
return true;
}
}
return false;
}
}
package com.test.wzq;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
/**
* @author 原创 java课程设计网 http://www.javakcsj.com/
* @date2018-7-31
*/
public class Server {
public static final int PORT = 8180;
public static ArrayList playerList = new ArrayList();
public static ArrayList groupList = new ArrayList();
public static void main(String[] args) throws IOException {
System.out.println("***********运行了服务端****************");
ServerSocket s = new ServerSocket(PORT);
System.out
.println("Welcome using ChessWZQ1.0 server (test)...\nAuthor:java课程设计网 http://www.javakcsj.com/\n \n");
System.out.println("Server Started at port " + PORT + "...");
try {
while (true) {
// 开始连接时阻塞终止:
Socket socket = s.accept();
try {
ServeOneClient server = new ServeOneClient(socket);
Player client = new Player();
client.selfSocket = server;
playerList.add(client);
// System.out.println("create a socket frome server");
} catch (IOException e) {
// 如果失败关闭端口,
// 否则线程会关闭它
socket.close();
}
}
} finally {
s.close();
}
}
}
共七个类,其中server是服务端,需要先启动,然后执行 chessWZQ,源码下载中,已经做好了server.bat,client.bat,直接执行就可以看效果了,客户端需要传入参数的,你参考client.bat即可。还有不懂的可以留言。
大家都在看
java批量压缩文件

利用zip工具,批量将文件夹或者文件压缩,提供java源代码下载(java课程设计网原创)...查看更多
java图片切割

java课程设计之java图片切割,提供java源代码下载(java课程设计网原创)...查看更多
企业任务流程管理系统

java课程设计之企业任务流程管理系统,采用springMVC全注解开发,带流程功能。开发工具:myeclipse10,数据库:mysql,数据库导入工具:navicat,增删改查,分页,图片上传,附件上传,流程审批,权限控制,三个角色员工,领导,超级管理员。提供java源代码下载(java课程设计网原创)...查看更多
java对mp3的播放功能

java课程设计之java对mp3的播放功能,提供java源代码下载(java课程设计网原创)...查看更多
发送邮件客户端,带发送附件

java课程设计之发送邮件客户端,带发送附件,提供java源代码下载(java课程设计网原创)...查看更多
java经纬度算两点之间的距离

java课程设计之java经纬度算两点之间的距离,提供java源代码下载(java课程设计网原创)...查看更多
word文档转换成html

word文档转换成html,附带源码以及依赖的jia包下载,直接使用...查看更多
批量给自己项目下的java文件添加注释

批量给自己项目下的java文件添加注释...查看更多
(0) 回复