基于java开发的蜘蛛纸牌程序设计(含源文件) 联系客服

发布时间 : 星期二 文章基于java开发的蜘蛛纸牌程序设计(含源文件)更新完毕开始阅读4a43e7d5710abb68a98271fe910ef12d2af9a93a

4.3.3纸牌的初始化以及发牌操作

代码实现如下:

public void initCards(){

//如果纸牌已被赋值,即将其从框架的面板中移去 if (cards[0] != null){

for (int i = 0; i < 104; i++){ pane.remove(cards[i]); } }

int n = 0;

//通过难度等级,为n赋值

if (this.grade == Spider.EASY){ n = 1; }

else if (this.grade == Spider.NATURAL){ n = 2; }

else{

n = 4; }

//为card赋值

for (int i = 1; i <= 8; i++){

for (int j = 1; j <= 13; j++){

cards[(i - 1) * 13 + j - 1] = new PKCard((i % n + 1) + \

this);假设n=1,此时i%n的值为0,则1%n+1的值为1,所以创建的图片应该是1-1到1-13全是黑桃,为同一花色,n等于其它值时类似。

} } 如图所示:

简单,单一花色:

中级,双

17

高级,四花色:

//随机纸牌初始化

this.randomCards();\\\\将纸牌的顺序打乱 }

/**

**纸牌随机分配 */

public void randomCards(){ PKCard temp = null; //随机生成牌号

for (int i = 0; i < 52; i++){

int a = (int) (Math.random() * 104); int b = (int) (Math.random() * 104); temp = cards[a]; cards[a] = cards[b]; cards[b] = temp; } }

设置纸牌的位置

public void setCardsLocation(){ 坐标位于界面的右下角区域 //初始化待展开的纸牌

将card转向背面 cards[n].turnRear();

将card放在固定的位置上

cards[n].moveto(new Point(x, y));

table = new Hashtable(); c = 0;

finish = 0; n = 0; a = 0;

int x = 883;

int y = 580;\\\\ for (int i = 0; i < 6; i++){

for (int j = 0; j < 10; j++){ int n = i * 10 + j; pane.add(cards[n]); // //

18

//将card的位置及相关信息存入

table.put(new Point(x, y), cards[n]); }

x += 10;\\\\x的值循环一次增10,表示下一叠纸牌的位置 }

x = 20;

y=4:\\\\坐标位于上方的玩牌区域最左边一个背景框的位置。 初始化表面显示的纸牌

for (int i = 10; i > 5; i--){

for (int j = 0; j < 10; j++){

int n = i * 10 + j;\\\\生成索引值

if (n >= 104) continue;\\\\值超过104则退出本次循环 pane.add(cards[n]);\\\\将索引值所指的纸牌添加到面板容器 cards[n].turnRear();\\\\将纸牌转到背面去

cards[n].moveto(new Point(x, y));\\\\将纸牌移动的固定的位置上去

table.put(new Point(x, y), cards[n]);\\\\将纸牌及其对应的位置存入到哈希表中

x += 101;背景框间隔的X值为101 }

x = 20;X坐标回到原先的位置处

y -= 5;Y坐标会向下移动5个单位,表示第二行纸牌的初始化开始

}

}

19

方法:游戏运行

public void deal() {

this.setNA();

//判断10列中是否空列

for (int i = 0; i < 10; i++){

if (this.getLastCardLocation(i) == null){

JOptionPane.showMessageDialog(this, \有空位不能发牌!\提示\

JOptionPane.WARNING_MESSAGE); return; } }

int x = 20;

for (int i = 0; i < 10; i++){

Point lastPoint = this.getLastCardLocation(i); //这张牌应“背面向上” if (c == 0){

lastPoint.y += 5;\\\\当还没有发过牌时,每列的纸牌中y坐标相差5个单位。

}

//这张牌应“正面向上” else{

lastPoint.y += 20;否则是两张正面显示纸牌差值 }

table.remove(cards[c + i].getLocation()); cards[c + i].moveto(lastPoint);

table.put(new Point(lastPoint), cards[c + i]); cards[c + i].turnFront();

cards[c + i].setCanMove(true);

//将组件card移动到容器中指定的顺序索引。

20