关于2048小游戏中随机生成2与4个数的问题--已解决

public class InitNumer {
    Random random = new Random();

    public InitNumer() {
        super();
    }

    /**
     *  随机生成一个二维数组,并指定生成的2与4的个数
     * @param rowAndCol 二维数组的宽与高
     * @param numberOf2 数字2的个数
     * @param numberOf4 数字4的个数
     */
    public int[][] randomGetNumber(int rowAndCol, int numberOf2, int numberOf4) {
        int[][] numArray = new int[rowAndCol][rowAndCol];
        for(int i=0;i<numberOf2;i++){
            int xi = random.nextInt(rowAndCol);
            int yi = random.nextInt(rowAndCol);
            if(numArray[xi][yi]==0){
                numArray[xi][yi]=2;
            }
        }
        for(int j=0;j<numberOf4;j++){
            int xj = random.nextInt(rowAndCol);
            int yj = random.nextInt(rowAndCol);
            if(numArray[xj][yj]==0){
                numArray[xj][yj]=4;
            }
        }
        return  numArray;
    }
}

随机生成的二维数组会出现一个问题,就是当(xi,yi)与(xj,yj)坐标相同的时候就会少生成一个4。就是说随机生成的2的个数可以确定,但是4的个数不能确定。例如:

待解决。

解决办法:封装一个类point,包含属性x,y。

public class Point {
    private int x;
    private int y;

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public Point(int y, int x) {
        this.y = y;
        this.x = x;
    }

    public Point() {
    }
}

将数组中为0的坐标放到一个集合中。 

for(int i =0;i<rowAndCol;i++){
            for(int j=0;j<rowAndCol;j++)
                if (numArray[i][j] == 0) {
                    Point p = new Point();
                    p.setX(i);
                    p.setY(j);
                    list.add(p);
                }
        }

然后加入4的时候,根据集合长度随机生成一个数,取集合中下标为该随机数的元素。

将该元素取出来之后,从集合中remove。

for(int j=0;j<numberOf4;j++){
            int x,y;
            int pointOf4=random.nextInt(list.size() - 1);
            x=list.get(pointOf4).getX();
            y=list.get(pointOf4).getY();
                numArray[x][y]=4;
            list.remove(pointOf4);
        }

问题已解决。

转载于:https://www.cnblogs.com/zhoubohao/p/6116299.html

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值