【CS61B】Project 0 游戏2048


proj0是让我们写一个2048的游戏,大家应该都玩过,就不详细介绍了。
主要是完成这个游戏中的四个函数的实现,游戏的整体框架已经有了。

一、public static boolean emptySpaceExists(Board b)

这个函数,是用来判断游戏面板上是不是还有空格子。

这个很简单。但注意实现的时候格子在Bord类中是private类型的,无法直接调用,需要通过b.tile(i,j)函数来读取格子。

   public static boolean emptySpaceExists(Board b) {
    
    
        // TODO: Fill in this function.
        int size=b.size();
        for(int i=0;i<size;i++){
    
    
            for(int j=0;j<size;j++){
    
    
                if(b.tile(i,j)==null){
    
    
                    return true;
                }
            }
        }
        return false;
    }

二、public static boolean maxTileExists(Board b)

这个函数主要意思是让我们判断格子中是不是已经有2048这个数字了,有的话,游戏就结束。
这个在判断的时候,当时出现了一点小问题,就是我们应该判断格子的数值是否等于2048,而不是判断格子。
还有一点注意的是,不是直接判断2048,判断的是MAX_PIECE。

    public static boolean maxTileExists(Board b) {
    
    
        // TODO: Fill in this function.
        int size=b.size();
        for(int i=0;i<size;i++){
    
    
            for(int j=0;j<size;j++){
    
    
                Tile t = b.tile(i,j);
                if(t!=null && t.value()==MAX_PIECE){
    
    
                    return true;
                }
            }
        }
        return false;
    }

三、public static boolean atLeastOneMoveExists(Board b)

这个函数主要是让我们来判断这个游戏是否还可以继续:有两点

  1. 游戏面板还有空间,也就是有空格子,游戏还可以i继续。
  2. 相邻的格子有一样的,就是当前格子的上下左右有一样的就可以消除。(我在这一步犯得一个错误是,我算成四个角的格子了)
public static boolean atLeastOneMoveExists(Board b) {
    
    
        // TODO: Fill in this function.
        if (emptySpaceExists(b)) return true;
        int size=b.size();
        int dx[]={
    
    0,1,0,-1};
        int dy[]={
    
    1,0,-1,0};
        for(int col=0;col<size;col++){
    
    
            for(int row=0;row<size;row++){
    
    
                for(int move=0;move<4;move++){
    
    
                    int curvalue=b.tile(col,row).value();
                    int newcol=col+dx[move];
                    int newrow=row+dy[move];
                    if(newcol<size && newrow<size && newcol>=0 && newrow>=0){
    
    
                        Tile t=b.tile(newcol,newrow);
                        if(curvalue==t.value()){
    
    
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

四、public boolean tilt(Side side)

最具有挑战的一个方法。

猜你喜欢

转载自blog.csdn.net/weixin_43821215/article/details/131995891