J2SE版五子棋(Demo学习总结)(一)

2014-11-24 10:09:32 · 作者: · 浏览: 0

(完全手绘版五子棋)


在制作五子棋时的一般流程:


首先:设置好显示窗口的大小、布局、外观,绘制好棋子所下的网格线和一些信息描述等等。


其次:定义一个二维数组用于保存所有棋子的坐标,


例如:


// 保存之前下过的所有全部棋子的坐标


// 其中数据内容 0:表示这个点并没有棋子, 1:表示有这个点


int[][] allChess = new int[19][19];


当在网格线中放置棋子时,将相应的网格点存入到该数组中。如下所示:


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;


} else {


allChess[x][y] = 2;


isBlack = true;


}


//在每次点击的时候进行重绘(这样不知妥不妥)


//并且在每走一格的时候都进行判断输赢O(∩_∩)O~


下面是详细的判断方法:


@Override


public void mousePressed(MouseEvent e) {


// TODO 鼠标点击操作


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) {


allChess[x][y] = 1; // 向棋子数组中添加数据


} else {


allChess[x][y] = 2;


}


isBlack = !isBlack; // 目的是让黑白棋子轮流下


winFlag = checkWin();//每走一格都要进行判断


if (winFlag) {


JOptionPane.showMessageDialog(this, "游戏结束,"


+ (allChess[x][y] == 1 "黑方" : "白方") + "获胜!");


}


}


}


this.repaint();


}



private boolean checkWin() {


boolean flag = false;


int color = allChess[x][y]; // 判断是黑色还是白色(表示刚下的那一格的棋子)


// 保存共有多少相同颜色的棋子相连


int count = 1;


int i = 1;


while (color == allChess[x + i][y]) {


count++;


i++;


}


i = 1;


while (color == allChess[x - i][y]) {


count++;


i++;


} // 纵向的判断


int i2 = 1;


int count2 = 1;



while (color == allChess[x][y - i2]) {


count2++;


i2++;


}



i2 = 1;


while (color == allChess[x][y + i2]) {


count2++;


i2++;


} // 斜方向的判断(右上 + 左下)


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++;


} // 斜方向的判断(右下 + 左上)


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 (count >= 5)


flag = true;



if (count2 >= 5)


flag = true;



if (count3 >= 5)


flag = true;



if (count4 >= 5)


flag = true;



return flag;


}


根据棋盘上的左右方向,上下方向,左上右下方向,右下左上方向,判断当前网格线上的棋子个数,然后判断输赢。



下面是优化后的判断输赢的方法


private boolean checkWin() {


boolean flag = false;


// 保存共有多少相同颜色的棋子相连


int count = 1;



// 判断横向是否有五个棋子相连,特点 纵坐标 是相同,即allChess[x][y]中y值相同


int color = allChess[x][y]; // 判断是黑色还是白色


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.checkCoun