鸿蒙小游戏-数字华容道自定义组件的踩坑记录

开发
前两天看到HarmonyOS开发者官网上发布的一个挑战HarmonyOS分布式趣味应用的帖子,然后有个想法想搞一个小游戏出来,结果三天的时间都卡在了自定义组件上。

[[430553]]

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

前两天看到HarmonyOS开发者官网上发布的一个挑战HarmonyOS分布式趣味应用的帖子,然后有个想法想搞一个小游戏出来,结果三天的时间都卡在了自定义组件上,使用了各种方式方法去实现功能,但是还是没有达到预期的效果,暂时先做个小总结,其实坑有的时候真的很深…

一、效果演示

小应用其实也挺简单,以前也见到过,叫做数字华容道,当你把所在的数字以顺序放置完成后游戏结束。

其实属于益智类的小游戏了;

最终实现效果:

鸿蒙小游戏-数字华容道  自定义组件的踩坑记录-鸿蒙HarmonyOS技术社区

当前实现效果:

鸿蒙小游戏-数字华容道  自定义组件的踩坑记录-鸿蒙HarmonyOS技术社区

二、实现过程

暂时说一下现在的进度,每一个方块可以表示一个棋子,棋子的名称也就是3*3的九宫格,1-9的数字,只是最后一个数字单独设置为空白。点击空白周围的棋子可以与这个空白棋子做一次位置调换,直到将所有棋子顺序排列完成为止。

这里先说一个这个棋子,棋子有两个东西需要被记住,一个是棋子的坐标就是在九宫格里面的位置,另一个就是棋子的名称;所以选择使用自定义组件的方式将坐标和名称进行一个绑定。

Position.java

  1. /** 
  2.  * 定义棋子的位置 
  3.  */ 
  4. public class Position { 
  5.     public int sizeX; // 总列数 
  6.     public int sizeY; // 总行数 
  7.     public int x; // 横坐标 
  8.     public int y; // 纵坐标 
  9.  
  10.     public Position() { 
  11.     } 
  12.  
  13.     public Position(int sizeX, int sizeY) { 
  14.         this.sizeX = sizeX; 
  15.         this.sizeY = sizeY; 
  16.     } 
  17.  
  18.     public Position(int sizeX, int sizeY, int x, int y) { 
  19.         this.sizeX = sizeX; 
  20.         this.sizeY = sizeY; 
  21.         this.x = x; 
  22.         this.y = y; 
  23.     } 
  24.  
  25.     public Position(Position orig) { 
  26.         this(orig.sizeX, orig.sizeY, orig.x, orig.y); 
  27.     } 
  28.  
  29.     /** 
  30.      * 移动到下一个位置 
  31.      */ 
  32.     public boolean moveToNextPosition() { 
  33.         if (x < sizeX - 1) { 
  34.             x++; 
  35.         } else if (y < sizeY - 1) { 
  36.             x = 0; 
  37.             y++; 
  38.         } else { 
  39.             return false
  40.         } 
  41.         return true
  42.     } 
  43.  
  44.     @Override 
  45.     public String toString() { 
  46.         return "Position{" + 
  47.                 "x=" + x + 
  48.                 ", y=" + y + 
  49.                 '}'
  50.     } 

CubeView.java

  1. public class CubeView extends ComponentContainer { 
  2.  
  3.     private Position mPosition; 
  4.     private int mNumber; 
  5.  
  6.     private Text mTextCub; 
  7.     private int mTextSize = 20; 
  8.  
  9.     public CubeView(Context context) { 
  10.         super(context); 
  11.         init(); 
  12.     } 
  13.  
  14.     public CubeView(Context context, AttrSet attrSet) { 
  15.         super(context, attrSet); 
  16.         init(); 
  17.     } 
  18.  
  19.     private void init(){ 
  20.         Component component = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_cube_view_item, this, false); 
  21.         mTextCub = (Text) component.findComponentById(ResourceTable.Id_tv_item); 
  22.         mTextCub.setTextSize(mTextSize, Text.TextSizeType.VP); 
  23.     } 
  24.  
  25.     public void setNumber(int n) { 
  26.         mNumber = n; 
  27.         mTextCub.setText(String.valueOf(n)); 
  28.     } 
  29.  
  30.  
  31.     public int getNumber() { 
  32.         return mNumber; 
  33.     } 
  34.  
  35.     public Position getPosition() { 
  36.         return mPosition; 
  37.     } 
  38.  
  39.     public void setPosition(Position position) { 
  40.         this.mPosition = position; 
  41.     } 
  42.  
  43.     @Override 
  44.     public String toString() { 
  45.         return "CubeView{" + 
  46.                 "mPosition=" + mPosition + 
  47.                 ", mNumber=" + mNumber + 
  48.                 '}'
  49.     } 

 cube_view_item.xml

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <DirectionalLayout 
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos" 
  4.     ohos:height="match_content" 
  5.     ohos:width="match_content"
  6.     <Text 
  7.         ohos:id="$+id:tv_item" 
  8.         ohos:height="100vp" 
  9.         ohos:width="100vp" 
  10.         ohos:background_element="$graphic:cube_view_bg" 
  11.         ohos:text="1" 
  12.         ohos:text_alignment="center" 
  13.         ohos:text_color="$color:cubeViewStroke" 
  14.         ohos:text_size="20vp"
  15.         ></Text> 
  16. </DirectionalLayout> 

到这问题就来了,因为在代码中只是使用到了setText()方法,那么有人会问我为什么不直接继承Text组件,多写一个布局有点麻烦了不是?

第一个坑

这里就是第一个坑了,因为在以前写Android自定义控件的时候,对于简单的组件来说直接继承它的组件名称就可以了,不用去继承公共类然后再去使用布局去定位到里面的组件。原本我也是这么写的,CubeView直接继承Text没有毛病可以使用,可以看到两者间并无差别。

  1. public class CubeView extends Text { 
  2.  
  3.     private Position mPosition; 
  4.     private int mNumber; 
  5.  
  6.  
  7.     public CubeView(Context context) { 
  8.         super(context); 
  9.         init(); 
  10.     } 
  11.  
  12.     public CubeView(Context context, AttrSet attrSet) { 
  13.         super(context, attrSet); 
  14.         init(); 
  15.     } 
  16.  
  17.     private void init(){ 
  18.          
  19.     } 
  20.  
  21.     public void setNumber(int n) { 
  22.         mNumber = n; 
  23.         setText(String.valueOf(n)); 
  24.     } 
  25.  
  26.  
  27.     public int getNumber() { 
  28.         return mNumber; 
  29.     } 
  30.  
  31.     public Position getPosition() { 
  32.         return mPosition; 
  33.     } 
  34.  
  35.     public void setPosition(Position position) { 
  36.         this.mPosition = position; 
  37.     } 
  38.  
  39.     @Override 
  40.     public String toString() { 
  41.         return "CubeView{" + 
  42.                 "mPosition=" + mPosition + 
  43.                 ", mNumber=" + mNumber + 
  44.                 '}'
  45.     } 

但是在调用组件的时候出现了问题,因为我需要把这个棋子的组件添加到我的棋盘布局中,那么就需要先引入这个组件。引入组件后出问题了,布局报错(在原来Android引入自定义组件的时候,单个组件也是可以直接引入的);报错原因是,我最外层没有放置布局导致不能直接识别单个组件,但是如果我加上一个布局的话,文件不会报错,但是在我的棋盘上不能拿到这个棋子的组件;

鸿蒙小游戏-数字华容道  自定义组件的踩坑记录-鸿蒙HarmonyOS技术社区

为此我只能将棋子的自定义组件写成了布局引入方式。

到这里,棋子的开发工作也就基本做完了,下面要对棋盘进行布局。还是选择自定义组件的方式;

cube_view.xml

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <com.example.codelabs_games_hrd.CubeView 
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos" 
  4.     ohos:background_element="$graphic:cube_view_bg" 
  5.     ohos:height="100vp" 
  6.     ohos:width="100vp" 
  7.     ohos:id="$+id:title_bar_left" 
  8.     ohos:text="1" 
  9.     ohos:text_alignment="center" 
  10.     ohos:text_color="$color:cubeViewStroke" 
  11.     ohos:text_size="20vp" 
  12.  
  13.     > 
  14. </com.example.codelabs_games_hrd.CubeView> 

 ability_game.xml

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <StackLayout 
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos" 
  4.     ohos:height="match_parent" 
  5.     ohos:width="match_parent" 
  6.     ohos:background_element="$color:cubeViewBg"
  7.  
  8.     <com.example.codelabs_games_hrd.BoardView 
  9.         ohos:id="$+id:board" 
  10.         ohos:height="300vp" 
  11.         ohos:width="300vp" 
  12.         ohos:layout_alignment="center" 
  13.         ohos:background_element="$color:boardViewBg"
  14.     </com.example.codelabs_games_hrd.BoardView> 
  15.  
  16.     <Text 
  17.         ohos:id="$+id:tvCheat" 
  18.         ohos:height="10vp" 
  19.         ohos:width="10vp"></Text> 
  20.  
  21.     <Text 
  22.         ohos:id="$+id:mask" 
  23.         ohos:height="match_parent" 
  24.         ohos:width="match_parent" 
  25.         ohos:background_element="$color:cubeViewBg" 
  26.         ohos:text="123456789" 
  27.         ohos:text_size="48vp"></Text> 
  28.  
  29. </StackLayout> 

BoardView.java

  1. public class BoardView extends ComponentContainer implements ComponentContainer.EstimateSizeListener, ComponentContainer.ArrangeListener { 
  2.     private static final String TAG = "BoardView"
  3.     /** 
  4.      * 每一行有多少个棋子 
  5.      */ 
  6.     private int mSizeX = 3; 
  7.     /** 
  8.      * 有多少行棋子 
  9.      */ 
  10.     private int mSizeY = 3; 
  11.  
  12.  
  13.     private int maxWidth = 0; 
  14.  
  15.     private int maxHeight = 0; 
  16.  
  17.     private int mChildSize; 
  18.  
  19.     private Position mBlankPos; 
  20.     private CubeView[] mChildren; 
  21.  
  22.     private OnFinishListener mFinishListener; 
  23.  
  24.     private int xx = 0; 
  25.  
  26.     private int yy = 0; 
  27.  
  28.     private int lastHeight = 0; 
  29.  
  30.     // 子组件索引与其布局数据的集合 
  31.     private final Map<Integer, Layout> axis = new HashMap<>(); 
  32.  
  33.     //位置及大小 
  34.     private static class Layout { 
  35.         int positionX = 0; 
  36.         int positionY = 0; 
  37.         int width = 0; 
  38.         int height = 0; 
  39.     } 
  40.  
  41.  
  42.     private void invalidateValues() { 
  43.         xx = 0; 
  44.         yy = 0; 
  45.         maxWidth = 0; 
  46.         maxHeight = 0; 
  47.         axis.clear(); 
  48.     } 
  49.  
  50.     public BoardView(Context context) { 
  51.         super(context); 
  52.     } 
  53.  
  54.     public BoardView(Context context, AttrSet attrs) { 
  55.         super(context, attrs); 
  56.         setEstimateSizeListener(this); 
  57.         setArrangeListener(this); 
  58.         init(); 
  59.     } 
  60.  
  61.     private void init() { 
  62.         mChildSize = mSizeX * mSizeY - 1; 
  63.         mChildren = new CubeView[mChildSize]; 
  64.         Position p = new Position(mSizeX, mSizeY); 
  65.         for (int i = 0; i < mChildSize; i++) { 
  66.         //添加棋子 
  67.             CubeView view = (CubeView) LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_cube_view, this, false); 
  68.             view.setPosition(new Position(p)); 
  69.             view.setClickedListener(component -> moveChildToBlank(view)); 
  70.             addComponent(view); 
  71.             p.moveToNextPosition(); 
  72.             mChildren[i] = view
  73.         } 
  74.         //最后一个空白棋子 
  75.         mBlankPos = new Position(mSizeX, mSizeY, mSizeX - 1, mSizeY - 1); 
  76.     } 
  77.  
  78.  
  79.  
  80.     public void setData(List<Integer> data) { 
  81.         for (int i = 0; i < mChildSize; i++) { 
  82.             CubeView view = (CubeView) getComponentAt(i); 
  83.             view.setNumber(data.get(i)); 
  84.         } 
  85.     } 
  86.  
  87.     //测量监听方法 
  88.     @Override 
  89.     public boolean onEstimateSize(int widthEstimatedConfig, int heightEstimatedConfig) { 
  90.         invalidateValues(); 
  91.         //测量子组件的大小 
  92.         measureChildren( widthEstimatedConfig,  heightEstimatedConfig); 
  93.        //关联子组件的索引与其布局数据 
  94.         for (int idx = 0; idx < getChildCount(); idx++) { 
  95.             CubeView childView = (CubeView) getComponentAt(idx); 
  96.             addChild(childView, idx, EstimateSpec.getSize(widthEstimatedConfig)); 
  97.         } 
  98.         //测量本身大小 
  99.         setEstimatedSize( widthEstimatedConfig,  heightEstimatedConfig); 
  100.  
  101.  
  102.         return true
  103.     } 
  104.  
  105.     private void measureChildren(int widthEstimatedConfig, int heightEstimatedConfig) { 
  106.         for (int idx = 0; idx < getChildCount(); idx++) { 
  107.             CubeView childView = (CubeView) getComponentAt(idx); 
  108.             if (childView != null) { 
  109.                 LayoutConfig lc = childView.getLayoutConfig(); 
  110.                 int childWidthMeasureSpec; 
  111.                 int childHeightMeasureSpec; 
  112.                 if (lc.width == LayoutConfig.MATCH_CONTENT) { 
  113.                     childWidthMeasureSpec = EstimateSpec.getSizeWithMode(lc.width, EstimateSpec.NOT_EXCEED); 
  114.                 } else if (lc.width == LayoutConfig.MATCH_PARENT) { 
  115.                     int parentWidth = EstimateSpec.getSize(widthEstimatedConfig); 
  116.                     int childWidth = parentWidth - childView.getMarginLeft() - childView.getMarginRight(); 
  117.                     childWidthMeasureSpec = EstimateSpec.getSizeWithMode(childWidth, EstimateSpec.PRECISE); 
  118.                 } else { 
  119.                     childWidthMeasureSpec = EstimateSpec.getSizeWithMode(lc.width, EstimateSpec.PRECISE); 
  120.                 } 
  121.  
  122.                 if (lc.height == LayoutConfig.MATCH_CONTENT) { 
  123.                     childHeightMeasureSpec = EstimateSpec.getSizeWithMode(lc.height, EstimateSpec.NOT_EXCEED); 
  124.                 } else if (lc.height == LayoutConfig.MATCH_PARENT) { 
  125.                     int parentHeight = EstimateSpec.getSize(heightEstimatedConfig); 
  126.                     int childHeight = parentHeight - childView.getMarginTop() - childView.getMarginBottom(); 
  127.                     childHeightMeasureSpec = EstimateSpec.getSizeWithMode(childHeight, EstimateSpec.PRECISE); 
  128.                 } else { 
  129.                     childHeightMeasureSpec = EstimateSpec.getSizeWithMode(lc.height, EstimateSpec.PRECISE); 
  130.                 } 
  131.                 childView.estimateSize(childWidthMeasureSpec, childHeightMeasureSpec); 
  132.             } 
  133.         } 
  134.     } 
  135.  
  136.  
  137.     private void measureSelf(int widthEstimatedConfig, int heightEstimatedConfig) { 
  138.         int widthSpce = EstimateSpec.getMode(widthEstimatedConfig); 
  139.         int heightSpce = EstimateSpec.getMode(heightEstimatedConfig); 
  140.         int widthConfig = 0; 
  141.         switch (widthSpce) { 
  142.             case EstimateSpec.UNCONSTRAINT: 
  143.             case EstimateSpec.PRECISE: 
  144.                 int width = EstimateSpec.getSize(widthEstimatedConfig); 
  145.                 widthConfig = EstimateSpec.getSizeWithMode(width, EstimateSpec.PRECISE); 
  146.                 break; 
  147.             case EstimateSpec.NOT_EXCEED: 
  148.                 widthConfig = EstimateSpec.getSizeWithMode(maxWidth, EstimateSpec.PRECISE); 
  149.                 break; 
  150.             default
  151.                 break; 
  152.         } 
  153.  
  154.         int heightConfig = 0; 
  155.         switch (heightSpce) { 
  156.             case EstimateSpec.UNCONSTRAINT: 
  157.             case EstimateSpec.PRECISE: 
  158.                 int height = EstimateSpec.getSize(heightEstimatedConfig); 
  159.                 heightConfig = EstimateSpec.getSizeWithMode(height, EstimateSpec.PRECISE); 
  160.                 break; 
  161.             case EstimateSpec.NOT_EXCEED: 
  162.                 heightConfig = EstimateSpec.getSizeWithMode(maxHeight, EstimateSpec.PRECISE); 
  163.                 break; 
  164.             default
  165.                 break; 
  166.         } 
  167.         setEstimatedSize(widthConfig, heightConfig); 
  168.     } 
  169.  
  170.  
  171.  
  172.     //每个棋子组件的位置及大小 
  173.     @Override 
  174.     public boolean onArrange(int l, int t, int r, int b) { 
  175.  
  176.         for (int idx = 0; idx < getChildCount(); idx++) { 
  177.             Component childView = getComponentAt(idx); 
  178.             Layout layout = axis.get(idx); 
  179.             if (layout != null) { 
  180.                 childView.arrange(layout.positionX, layout.positionY, layout.width, layout.height); 
  181.             } 
  182.         } 
  183.         return true
  184.     } 
  185.  
  186.  
  187.     private void addChild(CubeView component, int id, int layoutWidth) { 
  188.         Layout layout = new Layout(); 
  189.         layout.positionX = xx + component.getMarginLeft(); 
  190.         layout.positionY = yy + component.getMarginTop(); 
  191.         layout.width = component.getEstimatedWidth(); 
  192.         layout.height = component.getEstimatedHeight(); 
  193.         if ((xx + layout.width) > layoutWidth) { 
  194.             xx = 0; 
  195.             yy += lastHeight; 
  196.             lastHeight = 0; 
  197.             layout.positionX = xx + component.getMarginLeft(); 
  198.             layout.positionY = yy + component.getMarginTop(); 
  199.         } 
  200.         axis.put(id, layout); 
  201.         lastHeight = Math.max(lastHeight, layout.height + component.getMarginBottom()); 
  202.         xx += layout.width + component.getMarginRight(); 
  203.         maxWidth = Math.max(maxWidth, layout.positionX + layout.width + component.getMarginRight()); 
  204.         maxHeight = Math.max(maxHeight, layout.positionY + layout.height + component.getMarginBottom()); 
  205.     } 
  206.      
  207.     //点击棋子后进行位置切换 
  208.     public void moveChildToBlank(@org.jetbrains.annotations.NotNull CubeView child) { 
  209.         Position childPos = child.getPosition(); 
  210.         Position dstPos = mBlankPos; 
  211.         if (childPos.x == dstPos.x && Math.abs(childPos.y - dstPos.y) == 1 || 
  212.                 childPos.y == dstPos.y && Math.abs(childPos.x - dstPos.x) == 1) { 
  213.             child.setPosition(dstPos); 
  214.             //component中没有对组件进行物理平移的方法 
  215.             //setTranslationX(),setTranslationY()两个方法没有 
  216.             child.setTranslationX(dstPos.x * xx); 
  217.             child.setTranslationY(dstPos.y * yy); 
  218.  
  219.             mBlankPos = childPos; 
  220.             mStepCounter.add(); 
  221.         } 
  222.         checkPosition(); 
  223.     } 
  224.  
  225.     /** 
  226.      * 检查所有格子位置是否正确 
  227.      */ 
  228.     private void checkPosition() { 
  229.         if (mBlankPos.x != mSizeX - 1 || mBlankPos.y != mSizeY - 1) { 
  230.             return
  231.         } 
  232.  
  233.         for (CubeView child : mChildren) { 
  234.             int num = child.getNumber(); 
  235.             int x = child.getPosition().x; 
  236.             int y = child.getPosition().y; 
  237.             if (y * mSizeX + x + 1 != num) { 
  238.                 return
  239.             } 
  240.         } 
  241.  
  242.         if (mFinishListener != null) { 
  243.             mFinishListener.onFinished(mStepCounter.step); 
  244.         } 
  245.         for (CubeView child : mChildren) { 
  246.             child.setClickable(false); 
  247.         } 
  248.     } 
  249.  
  250.     public void setOnFinishedListener(OnFinishListener l) { 
  251.         mFinishListener = l; 
  252.     } 
  253.  
  254.     public interface OnFinishListener { 
  255.         void onFinished(int step); 
  256.     } 
  257.  
  258.     public int getSizeX() { 
  259.         return mSizeX; 
  260.     } 
  261.  
  262.     public int getSizeY() { 
  263.         return mSizeY; 
  264.     } 
  265.  
  266.     /** 
  267.      * 步数统计 
  268.      */ 
  269.     class StepCounter { 
  270.         private int step = 0; 
  271.  
  272.         void add() { 
  273.             step++; 
  274.         } 
  275.  
  276.         void clear() { 
  277.             step = 0; 
  278.         } 
  279.     } 
  280.  
  281.     private StepCounter mStepCounter = new StepCounter(); 
  282.  

棋盘的自定义布局也完成了。棋盘的布局稍微复杂一点,因为需要根据棋盘的大小计算每一个棋子的大小,还需要对棋子进行绑定,尤其是需要对最后一个棋子做空白处理。

然后点击棋子进行棋子的平移,平移后与其位置进行互换。

第二个坑

鸿蒙小游戏-数字华容道  自定义组件的踩坑记录-鸿蒙HarmonyOS技术社区

点击棋子进行位置平移,因为在API里面没有找到component公共组件下的平移方法,setTranslationX()/setTranslationY()方法,没有办法做到组件的物理位置平移,导致大家看到开头演示的效果,点击后与空白位置坐了切换但是重新对其进行物理位置赋值的时候没有办法去赋值,这个问题困扰了我两天。

现在还是没有解决掉,试着想想是不是可以使用TouchEvent事件一个滑动处理,不做点击事件做滑动事件。

最终现在项目的结构如下:

总结

后面还会继续去完善,以至于到整个功能可以正常去使用,踩坑还是要踩的,总会有收获的时候…

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

 

责任编辑:jianghua 来源: 鸿蒙社区
相关推荐

2021-08-25 09:54:51

鸿蒙HarmonyOS应用

2021-11-02 14:55:42

鸿蒙HarmonyOS应用

2020-12-22 11:20:36

鸿蒙HarmonyOS游戏

2020-12-11 12:27:35

鸿蒙HarmonyOS

2021-10-09 14:49:50

鸿蒙HarmonyOS应用

2022-10-17 14:39:12

自定义弹窗组件鸿蒙

2022-10-25 15:12:24

自定义组件鸿蒙

2022-10-26 15:54:46

canvas组件鸿蒙

2012-11-04 14:54:24

2021-02-20 12:34:53

鸿蒙HarmonyOS应用开发

2022-04-24 15:17:56

鸿蒙操作系统

2021-03-09 15:23:45

鸿蒙HarmonyOS应用开发

2021-01-11 11:36:23

鸿蒙HarmonyOSApp开发

2021-11-01 10:21:36

鸿蒙HarmonyOS应用

2023-02-20 15:20:43

启动页组件鸿蒙

2009-06-24 15:13:36

自定义JSF组件

2013-10-15 09:48:03

C++Lambda函数式编程

2021-12-24 15:46:23

鸿蒙HarmonyOS应用

2022-02-16 15:25:31

JS代码Canvas鸿蒙

2022-07-06 20:24:08

ArkUI计时组件
点赞
收藏

51CTO技术栈公众号