HarmonyOS 学习

文章23 |   阅读 14781 |   点赞0

来源:https://blog.csdn.net/weixin_47094733/category_11119618.html

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

x33g5p2x  于2022-03-07 转载在 其他  
字(12.0k)|赞(0)|评价(0)|浏览(675)

前两天看到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. public Position() {
  10. }
  11. public Position(int sizeX, int sizeY) {
  12. this.sizeX = sizeX;
  13. this.sizeY = sizeY;
  14. }
  15. public Position(int sizeX, int sizeY, int x, int y) {
  16. this.sizeX = sizeX;
  17. this.sizeY = sizeY;
  18. this.x = x;
  19. this.y = y;
  20. }
  21. public Position(Position orig) {
  22. this(orig.sizeX, orig.sizeY, orig.x, orig.y);
  23. }
  24. /**
  25. * 移动到下一个位置
  26. */
  27. public boolean moveToNextPosition() {
  28. if (x < sizeX - 1) {
  29. x++;
  30. } else if (y < sizeY - 1) {
  31. x = 0;
  32. y++;
  33. } else {
  34. return false;
  35. }
  36. return true;
  37. }
  38. @Override
  39. public String toString() {
  40. return "Position{" +
  41. "x=" + x +
  42. ", y=" + y +
  43. '}';
  44. }
  45. }

CubeView.java

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

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. private Position mPosition;
  3. private int mNumber;
  4. public CubeView(Context context) {
  5. super(context);
  6. init();
  7. }
  8. public CubeView(Context context, AttrSet attrSet) {
  9. super(context, attrSet);
  10. init();
  11. }
  12. private void init(){
  13. }
  14. public void setNumber(int n) {
  15. mNumber = n;
  16. setText(String.valueOf(n));
  17. }
  18. public int getNumber() {
  19. return mNumber;
  20. }
  21. public Position getPosition() {
  22. return mPosition;
  23. }
  24. public void setPosition(Position position) {
  25. this.mPosition = position;
  26. }
  27. @Override
  28. public String toString() {
  29. return "CubeView{" +
  30. "mPosition=" + mPosition +
  31. ", mNumber=" + mNumber +
  32. '}';
  33. }
  34. }

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

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

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

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

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

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

第二个坑


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PvmUPB0c-1634810943992)(C:\Users\HHCH\AppData\Roaming\Typora\typora-user-images\image-20211021175237912.png)]

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

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

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

总结

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

我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3w24mefasg8wc

相关文章