判断是否压牌
蓝框为b方格的宽度和高度的2倍,
判断t方格是否压住b方格,就要保证t方格的左上的黑点始终在蓝框内
即t的 x坐标(x1,x2)之间,y(y1,y2)之间
t方格的黑点设置为(x,y)
x1的x即为b的左上点x-其宽度
x2的x即为b左上点x+其宽度
y1的y即为b的左上点y-其高度
y2的y即为b的左上点y+其高度
public static boolean isCovered(JButton top,JButton bottom){
int x1 = bottom.getX()-59;
int x2 = bottom.getX()+59;
int y1 = bottom.getY()-63;
int y2 = bottom.getY()+63;
int x = top.getX();//x:top的x坐标
int y = top.getY();//y:top的y坐标
return x>x1 && x<x2 && y>y1 && y<y2;
}
先检测2张牌是否压住
//判断索引50是否压住索引为2的值
JButton bottom = cards.get(2);
JButton top = cards.get(50);
boolean isCover = isCovered(top,bottom);
if(isCover){
bottom.setEnabled(false);}
else{
bottom.setEnabled(true);
}
运行结果
遍历所有手牌
public static void allCover(LinkedList<JButton> cards){
for(int index=0;index<cards.size();index++){ //遍历所有卡牌
JButton bottom = cards.get(index); //获取下标为index的卡牌
for(int i=index+1;i<cards.size();i++){ //遍历当前卡牌后面的所有卡牌
JButton top = cards.get(i); //获取后面的卡牌
boolean cov = isCovered(top,bottom); //判断是否压住
if(cov){ //若压住了
bottom.setEnabled(false); //设置按钮不可用
break; //结束循环,若不结束则后面的卡牌没压住走else又点亮了
}else{ //没压住
bottom.setEnabled(true); //设置按钮可用
}
}
}
}
错误图
public static boolean isCovered(JButton top,JButton bottom){
int x1 = bottom.getX()-59;
int x2 = bottom.getX()+59;
int y1 = bottom.getY()-63;
int y2 = bottom.getY()+63;
int x = top.getX();//x:top的x坐标
int y = top.getY();//y:top的y坐标
return x>=x1 && x<=x2 && y>=y1 && y<=y2; //这边不能写=,不能接触边框
}
添加一个新的集合,用于存储下方的图片
LinkedList<JButton> belowCards = new LinkedList<>();
将下方图片添加到一个盒子中(简单的添加)
public static void addClickAction(LinkedList<JButton> cards,LinkedList<JButton>belowCards ,JPanel panel){
//在准备一个集合,存取下面卡槽的卡牌
for (int i = 0; i < cards.size(); i++) {
JButton card = cards.get(i);
card.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//添加监听事件
JButton current = (JButton)e.getSource();//获取被点击的source
cards.remove(current);//移除被点击的source
belowCards.add(current);//添加被移除的source
for (int i1 = 0; i1 < belowCards.size(); i1++) {
belowCards.get(i1).setLocation(20+(i1*63),640);//
}
}
});
}
}