HarmonyOS小游戏:吃豆豆---基于分布式数据库与分布式任务调度

开发 分布式 分布式 OpenHarmony
本次学习笔记记录了吃豆豆的游戏实现,最近学习到的UI设置,页面跳转,分布式数据库,分布式任务调度等内容。作为我的第一个实践的项目,项目或多或少会有小问题和一些还没有解决的问题。

[[417423]]

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

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

https://harmonyos.51cto.com

前言

我是深圳大学的一名本科生在读生,虽然在学校的课程中已经学习到了最常用的几种编程语言,但是纸上得来终觉浅,觉知此事要躬行。若只是为了学习语言而学习,而缺乏动手实践显然是不行的。恰逢鸿蒙出世,借着这个契机我决定尝试把我课堂上所学习到的东西在鸿蒙上做一些实践。为此加入了深圳大学木棉花鸿蒙小组,与伙伴们一起学习。暑假这段时间以来我在木棉花小组内学习到了一些鸿蒙分布式数据库,分布式任务调度等方面的内容,因此写下这篇文章来记录我这些天学习到的东西。

概述

这个吃豆豆小游戏项目分为单机游戏版和双人游戏版,在单机游戏版中将有两个怪物追赶玩家,玩家在不被追赶上的情况下吃完盘面的豆豆则获胜。双人游戏版则是利用分布式数据库和分布式调度的功能,实现两人联机进行吃豆豆。

游戏封面如下:

小游戏:吃豆豆--基于分布式数据库与分布式任务调度(学习笔记)-鸿蒙HarmonyOS技术社区

选择游戏模式:

小游戏:吃豆豆--基于分布式数据库与分布式任务调度(学习笔记)-鸿蒙HarmonyOS技术社区

双人模式下设备选择界面:

小游戏:吃豆豆--基于分布式数据库与分布式任务调度(学习笔记)-鸿蒙HarmonyOS技术社区

游戏界面截图如下:

单人模式

小游戏:吃豆豆--基于分布式数据库与分布式任务调度(学习笔记)-鸿蒙HarmonyOS技术社区

双人模式

小游戏:吃豆豆--基于分布式数据库与分布式任务调度(学习笔记)-鸿蒙HarmonyOS技术社区

正文

单机游戏

绘制游戏

把地图以二维数组的形式存储,其中1是墙,2是玩家,3是怪物,0是豆豆,如下:

  1. public  int[][] grids={ 
  2.            {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, 
  3.            {1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1}, 
  4.            {1, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1}, 
  5.            {1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1}, 
  6.            {1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 
  7.            {1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 
  8.            {1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 
  9.            {1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1}, 
  10.            {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1}, 
  11.            {1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1}, 
  12.            {1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 
  13.            {1, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 
  14.            {1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1}, 
  15.            {1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 
  16.            {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}};; 

绘制游戏面板

  1. public void drawtable(int grids[][]){ 
  2.        layout.setLayoutConfig((new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT,ComponentContainer.LayoutConfig.MATCH_PARENT))); 
  3.  
  4.        Component.DrawTask task = new Component.DrawTask() { 
  5.            @Override 
  6.            public void onDraw(Component component, Canvas canvas) { 
  7.                Paint paint=new Paint(); 
  8.                paint.setColor(Color.BLACK); 
  9.  
  10.                RectFloat rect=new RectFloat(30-20,250-20,length*15+interval*14+30+20,length*15+interval*14+250+20); 
  11.                canvas.drawRect(rect,paint); 
  12.  
  13.                for(int row = 0; row < height; row++) 
  14.                { 
  15.                    for(int column = 0; column < width; column++){ 
  16.                        if 
  17.                        (grids[row][column]==food || grids[row][column]==empty){ 
  18.                            paint.setColor(Color.BLACK); 
  19.                        } 
  20.                        else if(grids[row][column]==wall) 
  21.                            paint.setColor(Color.BLUE); 
  22.                        else if(grids[row][column]==player1) 
  23.                            paint.setColor(Color.RED); 
  24.                        else if(grids[row][column]==monster) 
  25.                            paint.setColor(Color.MAGENTA); 
  26.                        RectFloat rectFloat=new RectFloat(30+column*(length+interval),250+row*(length+interval),30+length+column*(length+interval),250+length+row*(length+interval)); 
  27.                        canvas.drawRect(rectFloat,paint); 
  28.                        if(grids[row][column]==food){ 
  29.                            paint.setColor(Color.YELLOW); 
  30.                            Circle circle=new Circle(30+column*(length+interval)+length/2,250+row*(length+interval)+length/2,length/5); 
  31.                            canvas.drawCircle(circle,paint); 
  32.                        } 
  33.                    } 
  34.                } 
  35.  
  36.  
  37.            } 
  38.        }; 
  39.        layout.addDrawTask(task); 
  40.        setUIContent(layout); 
  41.    } 

绘制按钮

以下代码分别绘制了四个方向的按钮,并在按钮按下时设置了回调方法,入按下向做的按钮,则把玩家的方向设置成向左,以此类推

  1. public void drawButton() { 
  2.             ShapeElement background = new ShapeElement(); 
  3.             background.setRgbColor(new RgbColor(174, 158, 143)); 
  4.             background.setCornerRadius(100); 
  5.  
  6.             Button button1 = new Button(this); 
  7.             button1.setText("←"); 
  8.             button1.setTextAlignment(TextAlignment.CENTER); 
  9.             button1.setTextColor(Color.WHITE); 
  10.             button1.setTextSize(100); 
  11.             button1.setMarginTop(1500); 
  12.             button1.setMarginLeft(180); 
  13.             button1.setPadding(10,0,10,0); 
  14.             button1.setBackground(background); 
  15.             button1.setClickedListener(new Component.ClickedListener() { 
  16.                 @Override 
  17.                 public void onClick(Component component) { 
  18.                     player.left();//把玩家的方向设置成向左 
  19.                 } 
  20.             }); 
  21.             layout.addComponent(button1); 
  22.  
  23.             Button button2 = new Button(this); 
  24.             button2.setText("↑"); 
  25.             button2.setTextAlignment(TextAlignment.CENTER); 
  26.             button2.setTextColor(Color.WHITE); 
  27.             button2.setTextSize(100); 
  28.             button2.setMarginLeft(470); 
  29.             button2.setMarginTop(-330); 
  30.             button2.setPadding(10,0,10,0); 
  31.             button2.setBackground(background); 
  32.             button2.setClickedListener(new Component.ClickedListener() { 
  33.                 @Override 
  34.                 public void onClick(Component component) { 
  35.                     player.up();//把玩家的方向设置成向上 
  36.                 } 
  37.             }); 
  38.             layout.addComponent(button2); 
  39.  
  40.             Button button3 = new Button(this); 
  41.             button3.setText("→"); 
  42.             button3.setTextAlignment(TextAlignment.CENTER); 
  43.             button3.setTextColor(Color.WHITE); 
  44.             button3.setTextSize(100); 
  45.             button3.setMarginLeft(760); 
  46.             button3.setMarginTop(55); 
  47.             button3.setPadding(10,0,10,0); 
  48.             button3.setBackground(background); 
  49.             button3.setClickedListener(new Component.ClickedListener() { 
  50.                 @Override 
  51.                 public void onClick(Component component) { 
  52.                     player.right();把玩家的方向设置成向右 
  53.                 } 
  54.             }); 
  55.             layout.addComponent(button3); 
  56.  
  57.             Button button = new Button(this); 
  58.             button.setText("↓"); 
  59.             button.setTextSize(100); 
  60.             button.setTextAlignment(TextAlignment.CENTER); 
  61.             button.setTextColor(Color.WHITE); 
  62.             button.setMarginTop(100); 
  63.             button.setMarginLeft(470); 
  64.             button.setPadding(10,10,10,10); 
  65.             button.setBackground(background); 
  66.             button.setClickedListener(new Component.ClickedListener() { 
  67.                 @Override 
  68.                 public void onClick(Component component) { 
  69.                     player.down();把玩家的方向设置成向下 
  70.                 } 
  71.             }); 
  72.             layout.addComponent(button); 
  73.         } 

玩家类

玩家类的属性有方向,玩家的x,y坐标,玩家得分。玩家类的方法有:player_run(),left(),right(),up(),down()等。player_run()将根据玩家实例的方向,在判断玩家实例下一步是否是wall,若不是wall,则行进下一步。而left()等方法则是用于在按下方向键时改变方向时使用。

下面仅贴出部分关键代码:

  1. public class Player 
  2.     private int direction; 
  3.     public int player_x; 
  4.     public int player_y; 
  5.     private static final int food=0; 
  6.     private static final int wall=1; 
  7.     private static final int player=2; 
  8.     private static final int monster=3; 
  9.     private static final int empty=4; 
  10.     private static final int left=1; 
  11.     private static final int up=2; 
  12.     private static final int right=3; 
  13.     private static final int down=4; 
  14.  
  15.     public Player(int direction,int player_x,int player_y) 
  16.     { 
  17.         this.direction=direction; 
  18.         this.player_x=player_x; 
  19.         this.player_y=player_y; 
  20.     } 
  21.  
  22.     public int[][] player_run(int [][] grids) { 
  23.     int [][]grid=grids; 
  24.         if (direction == left) { 
  25.             if (grid[player_y][player_x - 1] != wall) 
  26.             { 
  27.                 grid[player_y][player_x - 1] = player; 
  28.                 grid[player_y][player_x] = empty; 
  29.                 player_x--; 
  30.             } 
  31.         } else if (direction == up) 
  32.         { 
  33.             if (grid[player_y - 1][player_x] != wall) 
  34.             { 
  35.                 grid[player_y - 1][player_x] = food; 
  36.                 grid[player_y][player_x] = empty; 
  37.                 player_y--; 
  38.             } 
  39.         } 
  40.         else if (direction == right
  41.         { 
  42.             if (grid[player_y][player_x + 1] != wall) 
  43.             { 
  44.                 grid[player_y][player_x + 1] = player; 
  45.                 grid[player_y][player_x] = empty; 
  46.                 player_x++; 
  47.             } 
  48.         } else if (direction == down) { 
  49.  
  50.             if (grid[player_y + 1][player_x] != wall) 
  51.             { 
  52.                 grid[player_y + 1][player_x] = player; 
  53.                 grid[player_y][player_x] = empty; 
  54.                 player_y++; 
  55.             } 
  56.         } 
  57.         return grid; 
  58.     } 
  59.  
  60.  public void left() 
  61.     { 
  62.         this.direction=left
  63.     } 
  64.     public void up() 
  65.     { 
  66.         this.direction=up; 
  67.     } 
  68.     public void right() 
  69.     { 
  70.         this.direction=right
  71.     } 
  72.  
  73.     public void down() 
  74.     { 
  75.         this.direction=down; 
  76.     } 

怪物类

怪物类主要实现的是追赶玩家,这里采用的方法是:计算怪物当前坐标与玩家当前坐标的差,以此来做出追赶。追赶是这个游戏里最复杂的地方,需要注意的地方有:

1.需要防止两个怪物重叠在一起

2.怪物经过有食物的格子时不能够把食物吃掉,因此要判断当前格子是否说食物格。为此设置了布尔类型的标志isfood;

Monster类的属性和构造方法如下:

  1. public class Monster { 
  2.     private int monster_x; 
  3.     private int monster_y; 
  4.     private int x_difference;//列差 
  5.     private int y_difference;//行差 
  6.     private int x_distance;//行距离 
  7.     private int y_distance;//列距离 
  8.     private final int wall = 1; 
  9.     private final int player = 2; 
  10.     private final int monster = 3; 
  11.     private final int food=0; 
  12.     private final int empty=4; 
  13.     private boolean isfood=true
  14.  
  15.  
  16.     public Monster(int monster_x, int monster_y) { 
  17.         this.monster_x = monster_x; 
  18.         this.monster_y = monster_y; 
  19.     } 

追赶方法:计算当前怪物与玩家的x,y方向上的距离,选择其中距离更大的一个方向优先追赶,如若在这个方向上怪物无法行进(两边都是wall),那么则转成朝另一个方向进行追赶。

  1. public int[][] chase1(int[][] grids, Player player) { 
  2.         int[][] grid = grids; 
  3.         this.x_difference = monster_x - player.getPlayer_x(); 
  4.         this.y_difference = monster_y - player.getPlayer_y(); 
  5.         this.x_distance = Math.abs(x_difference); 
  6.         this.y_distance = Math.abs(y_difference); 
  7. //判断当前位置是否是食物,若是食物,则先将当前位置置成是食物,再走下一步 
  8. //若不是食物,则把当前位置置空,然后走下一步 
  9.         if(isfood==true
  10.             grid[monster_y][monster_x]=food; 
  11.         else if(isfood==false
  12.             grid[monster_y][monster_x]=empty; 
  13.         if (y_distance < x_distance)//如果y方向上的距离更小,则先从x方向上靠近它 
  14.         { 
  15.             if (x_difference > 0 && grid[monster_y][monster_x - 1] != wall && grid[monster_y][monster_x - 1] != monster) 
  16.             { 
  17.                 monster_x--; 
  18.                 if(grid[monster_y][monster_x]==food)//如果下一步是食物,设置标志 
  19.                 { 
  20.                     isfood=true
  21.                     grid[monster_y][monster_x] = monster; 
  22.  
  23.                 } 
  24.                 else if(grids[monster_y][monster_x]==4) 
  25.                 { 
  26.                     isfood=false
  27.                     grid[monster_y][monster_x] = monster; 
  28.                 } 
  29.             } 
  30.             else if (x_difference < 0 && grid[monster_y][monster_x +1] != wall && grid[monster_y][monster_x - 1] != monster) { 
  31.                 monster_x++; 
  32.                 if(grid[monster_y][monster_x]==0)//判断下一步要走的格子有没有食物,若有则把标志位置true;反之,置false 
  33.                 { 
  34.                     isfood=true
  35.                     grid[monster_y][monster_x] = monster; 
  36.                 } 
  37.                 else if(grids[monster_y][monster_x]==4) 
  38.                 { 
  39.                     isfood=false
  40.                     grid[monster_y][monster_x] = monster; 
  41.                 } 
  42.             } 
  43.             else //如果x的方向走不通,则转而向y方向进行追赶 
  44.                 { 
  45.                 if (y_difference > 0 && grid[monster_y - 1][monster_x] != wall && grid[monster_y - 1][monster_x] != monster) { 
  46.                     monster_y--; 
  47.                     if(grid[monster_y][monster_x]==0) 
  48.                     { 
  49.                         isfood=true
  50.                         grid[monster_y][monster_x] = monster; 
  51.                     } 
  52.                     else if(grids[monster_y][monster_x]==4) 
  53.                     { 
  54.                         isfood=false
  55.                         grid[monster_y][monster_x] = monster; 
  56.                     } 
  57.                 } 
  58.                 else if (y_difference < 0 && grid[monster_y + 1][monster_x] != wall && grid[monster_y + 1][monster_x] != monster) 
  59.                 { 
  60.                     monster_y++; 
  61.                     if(grid[monster_y][monster_x]==0) 
  62.                     { 
  63.                         isfood=true
  64.                         grid[monster_y][monster_x] = monster; 
  65.                     } 
  66.                     else if(grids[monster_y][monster_x]==4) 
  67.                     { 
  68.                         isfood=false
  69.                         grid[monster_y][monster_x] = monster; 
  70.                     } 
  71.                 } 
  72.             } 
  73.         } 
  74.         else//x方向上的距离更小或二者相等,则先在y方向上进行追赶 
  75.         { 
  76.             if (y_difference > 0 && grid[monster_y - 1][monster_x] != wall && grid[monster_y - 1][monster_x] != monster) { 
  77.                 monster_y--; 
  78.                 if(grid[monster_y][monster_x]==0) 
  79.                 { 
  80.                     isfood=true
  81.                     grid[monster_y][monster_x] = monster; 
  82.                 } 
  83.                 else if(grids[monster_y][monster_x]==4) 
  84.                 { 
  85.                     isfood=false
  86.                     grid[monster_y][monster_x] = monster; 
  87.                 } 
  88.             } 
  89.             else if (y_difference < 0 && grid[monster_y + 1][monster_x] != wall && grid[monster_y + 1][monster_x] != monster) { 
  90.                 monster_y++; 
  91.                 if(grid[monster_y][monster_x]==0) 
  92.                 { 
  93.                     isfood=true
  94.                     grid[monster_y][monster_x] = monster; 
  95.                 } 
  96.                 else if(grids[monster_y][monster_x]==4) 
  97.                 { 
  98.                     isfood=false
  99.                     grid[monster_y][monster_x] = monster; 
  100.                 } 
  101.             } 
  102.  
  103.             else 
  104.                 { 
  105.                 if (x_difference > 0 && grid[monster_y][x_distance - 1] != wall && grid[monster_y ][monster_x-1] != monster) { 
  106.                     monster_x--; 
  107.                     if(grid[monster_y][monster_x]==0) 
  108.                     { 
  109.                         isfood=true
  110.                         grid[monster_y][monster_x] = monster; 
  111.                     } 
  112.                     else if(grids[monster_y][monster_x]==4) 
  113.                     { 
  114.                         isfood=false
  115.                         grid[monster_y][monster_x] = monster; 
  116.                     } 
  117.                 } 
  118.                 else if (x_difference < 0 && grid[monster_y][monster_x + 1] != wall && grid[monster_y ][monster_x+1] != monster) 
  119.                 { 
  120.                     monster_x++; 
  121.                     if(grid[monster_y][monster_x]==0) 
  122.                     { 
  123.                         isfood=true
  124.                         grid[monster_y][monster_x] = monster; 
  125.                     } 
  126.                     else if(grids[monster_y][monster_x]==4) 
  127.                     { 
  128.                         isfood=false
  129.                         grid[monster_y][monster_x] = monster; 
  130.                     } 
  131.                 } 
  132.             } 
  133.         } 
  134.             return grid; 
  135.         } 

绘制游戏结束或游戏成功

首先需要判断游戏结束或成功,我们定义被怪物追上为游戏结束,即玩家的x,y坐标同时与其中一个怪物相同的情况。定义当盘面所有豆豆都被吃完的情况为游戏成功。判断游戏结束和游戏成功的代码如下:

  1. private boolean gamesucess() 
  2.       { 
  3.           for(int row = 0; row < height; row++) 
  4.           { 
  5.               for (int column = 0; column < width; column++) 
  6.               { 
  7.                   if (grids[row][column] == 0) 
  8.                       return false
  9.               } 
  10.           } 
  11.       return true
  12.       } 
  13.  
  14.       private boolean game_over(Player player,Monster monster1,Monster monster2) 
  15.       { 
  16.           if((player.getPlayer_x()==monster1.getMonster_x() && player.getPlayer_y()==monster1.getMonster_y()) || (player.getPlayer_x()==monster2.getMonster_x() && player.getPlayer_y()==monster2.getMonster_y())) 
  17.               return true
  18.           else 
  19.               return false
  20.       } 

绘制游戏结果的代码如下:

  1. private void drawGame_over() 
  2.    { 
  3.        timer.cancel(); 
  4.        Text text=new Text(this); 
  5.        text.setText("游戏结束"); 
  6.        text.setTextSize(100); 
  7.        text.setTextColor(Color.BLUE); 
  8.        text.setTextAlignment(TextAlignment.CENTER); 
  9.        text.setMarginsTopAndBottom(-1800,0); 
  10.        text.setMarginsLeftAndRight(350,0); 
  11.        layout.addComponent(text); 
  12.        setUIContent(layout); 
  13.    } 
  14.  
  15. private void drawGamesuccess() 
  16.    { 
  17.        timer.cancel(); 
  18.        Text text=new Text(this); 
  19.        text.setText("游戏成功"); 
  20.        text.setTextSize(100); 
  21.        text.setTextColor(Color.BLUE); 
  22.        text.setTextAlignment(TextAlignment.CENTER); 
  23.        text.setMarginsTopAndBottom(-1800,0); 
  24.        text.setMarginsLeftAndRight(350,0); 
  25.        layout.addComponent(text); 
  26.        setUIContent(layout); 
  27.    } 

双人游戏

分布式任务调度与页面跳转

双人游戏模式下,我设置了一个设备选择的页面。选择设备A的一方将操纵player1,而同时另一方将自动地设置为B方,操纵player2。更重要的是,我希望在两台设备的其中之一做出选择之后,两台设备将自动地同时跳转到游戏页面。于是我采用了带有参数的分布式任务调度来操纵另一台机器的任务拉起,采用带有参数的同Page页面跳转(也就是present语句)来实现本机的跳转。具体代码如下:

首先需要在config.json文件中声明所需要的权限,在"module"代码块中添加:

小游戏:吃豆豆--基于分布式数据库与分布式任务调度(学习笔记)-鸿蒙HarmonyOS技术社区

然后我们在MainAbility类中对敏感权限进行显式声明:

  1. public class MainAbility extends Ability  
  2.     @Override 
  3.     public void onStart(Intent intent) { 
  4.         super.onStart(intent); 
  5.         String[] permissions = { 
  6.                 "ohos.permission.READ_USER_STORAGE",//读取数据库权限 
  7.                 "ohos.permission.WRITE_USER_STORAGE",//写入数据库权限 
  8.                 "ohos.permission.DISTRIBUTED_DATASYNC"//分布式数据同步权限 
  9.         }; 
  10.         requestPermissionsFromUser(permissions, 0); 
  11.         super.setMainRoute(MainAbilitySlice.class.getName()); 
  12.     } 

下面使用分布式调度的方法完成对另一个设备的拉起,利用页面跳转来完成本地设备的跳转,这两个跳转都为带参数的跳转,目的是方便后面对设备操作对象的绑定。

分布式调度有两个地方需要注意:

1.BUNDLE_NAME和ABILITY_NAME的设置

可以在config文件的app代码块中找到BUNDLE_NAME

小游戏:吃豆豆--基于分布式数据库与分布式任务调度(学习笔记)-鸿蒙HarmonyOS技术社区

可以在module代码块的abilities部分找到ABILITY_NAME

小游戏:吃豆豆--基于分布式数据库与分布式任务调度(学习笔记)-鸿蒙HarmonyOS技术社区

2.分布式调度只能够调度Ability类而不能够调度AbilitySlice类,若想要调度AbilitySlice类,可先调度Ability类再由里面的super.setMainRoute()方法跳转到AbilitySlice类。笔者在一开始时就反了这个错误,导致调度失败。

分布式调度与页面调度的代码如下:

  1. public class ChooseAB_Ability extends AbilitySlice { 
  2.  
  3.     private static final String BUNDLE_NAME = "com.example.test"
  4.     private static final String ABILITY_NAME = "com.example.test.Test"
  5.  
  6.  
  7.     public void onStart(Intent intent) { 
  8.         super.onStart(intent); 
  9.         super.setUIContent(ResourceTable.Layout_ability_third); 
  10.  
  11. //获取联网设备 
  12.         List<DeviceInfo> deviceInfoList = DeviceManager.getDeviceList(DeviceInfo.FLAG_GET_ONLINE_DEVICE); 
  13.        if(deviceInfoList.size()==0) 
  14.            return ; 
  15.        String deviceID=deviceInfoList.get(0).getDeviceId(); 
  16.  
  17.         Button buttonA = (Button) findComponentById(ResourceTable.Id_A_btn); 
  18.         buttonA.setClickedListener(component -> { 
  19.  
  20.                 // 远程启动FA 
  21.                 Intent remoteIntent = new Intent(); 
  22.                 Operation operation = new Intent.OperationBuilder().withDeviceId(deviceID) 
  23.                         .withBundleName(BUNDLE_NAME) 
  24.                         .withAbilityName(ABILITY_NAME) 
  25.                         .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE) 
  26.                         .build(); 
  27.  
  28.                 remoteIntent.setOperation(operation); 
  29.                 remoteIntent.setParam("device","B");//设值跳转参数,"device"是键,"B"是值 
  30.             try { 
  31.                 // 目标设备是否包含指定FA 
  32.                 List<AbilityInfo> abilityInfoList = getBundleManager().queryAbilityByIntent(remoteIntent, 0, 0); 
  33.                 if (abilityInfoList != null && !abilityInfoList.isEmpty()) { 
  34.                     startAbility(remoteIntent);//调度另一台设备 
  35.                 } 
  36.             } catch (RemoteException e) { 
  37.                 //处理错误 
  38.             } 
  39.  
  40.            //带参数的页面跳转 
  41.  
  42.                 Intent intent1=new Intent(); 
  43.                 intent1.setParam("device","A");//设置参数 
  44.                 present(new MultiGameAbility_3(),intent1);页面跳转 
  45.  
  46.         }); 
  47.  
  48. //另一个按键的代码与上面基本相同,只是传递的参数不同 
  49.         Button buttonB = (Button) findComponentById(ResourceTable.Id_B_btn); 
  50.         buttonB.setClickedListener(new Component.ClickedListener() { 
  51.             @Override 
  52.             public void onClick(Component component) { 
  53.                  Intent remoteIntent = new Intent(); 
  54.  
  55.                 Operation operation = new Intent.OperationBuilder().withDeviceId(deviceID) 
  56.                         .withBundleName(BUNDLE_NAME) 
  57.                        .withAbilityName(ABILITY_NAME) 
  58.                      .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE) 
  59.                         .build(); 
  60.  
  61.                 remoteIntent.setOperation(operation); 
  62.                 remoteIntent.setParam("device","A"); 
  63.                 try { 
  64.                     // 目标设备是否包含指定FA 
  65.                     List<AbilityInfo> abilityInfoList = getBundleManager().queryAbilityByIntent(remoteIntent, 0, 0); 
  66.                     if (abilityInfoList != null && !abilityInfoList.isEmpty()) { 
  67.                         startAbility(remoteIntent); 
  68.                     } 
  69.                 } catch (RemoteException e) { 
  70.                     //处理错误 
  71.                 } 
  72.  
  73.                Intent intent1=new Intent(); 
  74.                intent1.setParam("device","B"); 
  75.                present(new MultiGameAbility_3(),intent1); 
  76.                 } 
  77.  
  78.         }); 
  79.  
  80.     } 

分布式数据库的建立

定义全局变量如下:

  1. private static final String STORE_ID = "distributed_db"
  2. private SingleKvStore singleKvStore; 
  3. private KvManager kvManager; 

 建立数据库的过程如下:

  1. private void initDbManager() 
  2.     { 
  3.         kvManager=createManager(); 
  4.         singleKvStore=createDb(kvManager); 
  5.         subscribeDb(singleKvStore); 
  6.     } 
  7.  
  8.     private KvManager createManager() 
  9.     { 
  10.         KvManagerConfig config = new KvManagerConfig(this); 
  11.         KvManager manager = KvManagerFactory.getInstance().createKvManager(config); 
  12.         return manager; 
  13.     } 
  14.  
  15.  
  16. //利用KvManager创建数据库 
  17.     private SingleKvStore createDb(KvManager kvManager) 
  18.     { 
  19.         SingleKvStore kvStore=null
  20.         try{ 
  21.             Options options=new Options(); 
  22.             options.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION); 
  23.             kvStore=kvManager.getKvStore(options,STORE_ID); 
  24.         } 
  25.         catch (KvStoreException exception) 
  26.         { 
  27.             //错误处理 
  28.         } 
  29.         return kvStore; 
  30.  
  31.     } 
  32.  
  33. //订阅数据库的变化 
  34.     private void subscribeDb(SingleKvStore singleKvStore) 
  35.     { 
  36.         class KvStoreObserverClient implements KvStoreObserver 
  37.         { 
  38.             public void onChange(ChangeNotification notification) 
  39.             { 
  40.                 if(queryContact_Int("player1_d")!=error) 
  41.                     direction1=queryContact_Int("player1_d"); 
  42.                 if(queryContact_Int("player2_d")!=error) 
  43.                     direction2=queryContact_Int("player2_d"); 
  44.                 if(queryContact_String("array")!=null
  45.                     array=queryContact_String("array"); 
  46.                 if(queryContact_Int("A_Score")!=error) 
  47.                     A_Score=queryContact_Int("A_Score"); 
  48.                 if(queryContact_Int("A_Score")!=error) 
  49.                     B_Score=queryContact_Int("A_Score"); 
  50.  
  51.             } 
  52.         } 
  53.         KvStoreObserver kvStoreObserverClient=new KvStoreObserverClient(); 
  54.         singleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL,kvStoreObserverClient); 
  55.     } 

数据库的增、删、改、查

阅读文档我们会发现,分布式数据库的插入和修改操作是同一个语句,若关键字未存在于数据库中,则作插入操作;若数据库存在于数据库中,则作更新操作。这样在一定程度上会显得更智能和便利,但是我更倾向于把这两个功能分开,这样会更加清晰。在学习的过程中,我们曾犯过的错是:先入为主,默认查询是成功的,导致程序的闪退;事实上,它是一个Throws类,其中会抛出的一个错误就是关键字不存在的错误,所以对于所有的Throws类都严格地采用try+catch形式是很重要的。

字符串的增、改、查如下:

  1. //字符串的插入 
  2.  private void inputData_String(String key,String value) 
  3.     { 
  4.  
  5.         if(key==null||key.isEmpty()||value==null||value.isEmpty()) 
  6.             ;//如果是关键字是空的话,则不做操作 
  7.         else 
  8.         {//当关键字不是空,且这个关键字没有值的时候,才进行putString操作 
  9.             if (queryContact_String(key) == null
  10.             { 
  11.                 singleKvStore.putString(key, value); 
  12.             } 
  13.         } 
  14.  
  15.     } 
  16. //字符串的修改 
  17.     private void update_String(String key,String value) 
  18.     { 
  19.         if(key==null||key.isEmpty()||value==null||value.isEmpty()||queryContact_String(key)==null
  20.             ;//如果关键字是空的,不做操作 
  21.         else 
  22.             singleKvStore.putString(key,value); 
  23.     } 
  24. //字符串的查询 
  25.     private String queryContact_String(String key
  26.     { 
  27.         try { 
  28.             return singleKvStore.getString(key); 
  29.         } 
  30.         catch (KvStoreException exception) 
  31.         { 
  32.             return null;//如果出问题了,返回一个null,以便后续的操作 
  33.         } 
  34.     } 

整型的增、改、查

  1. private int queryContact_Int(String key
  2.     { 
  3.         try { 
  4.             return singleKvStore.getInt(key); 
  5.         } 
  6.         catch (KvStoreException exception) 
  7.         { 
  8.             return error;//此处error我定义为程序中不会出现的负整数(-1) 
  9.         } 
  10.     } 
  11.  
  12.     private void update_Int(String key,int value) 
  13.     { 
  14.  
  15.         if (key == null || key.isEmpty()||queryContact_Int(key)==error) 
  16.             ; 
  17.         else 
  18.             singleKvStore.putInt(key, value); 
  19.     } 
  20.  
  21.     private void inputData_Int(String key,int value) 
  22.     { 
  23.  
  24.         if(queryContact_Int(key)==error) 
  25.         { 
  26.             singleKvStore.putInt(key,value); 
  27.         } 
  28.         else 
  29.             ; 
  30.  
  31.     } 

联网设备ID绑定

对ID进行绑定,我们的方法是借助数据库来进行绑定,往数据库中传入设备ID与对应的值。

(”A“或”B“)。因为这两个设备运行的是同一个程序,可以说是镜像的,如果仅仅在本地进行操作则或产生”覆盖“的情况,所以需要一个第三地方的公共的区域来进行绑定操作,因此我们选择数据库。

首先需要获取本地设备ID以及联网的另一设备的ID。

  1. private String self;//全部变量 
  2. private String other;//全局变量 
  3. public void getId() 
  4.    { 
  5.        self = KvManagerFactory.getInstance().createKvManager(new KvManagerConfig(this)).getLocalDeviceInfo().getId();//获取自己的id 
  6.        List<DeviceInfo> onlineDevices = DeviceManager.getDeviceList(DeviceInfo.FLAG_GET_ONLINE_DEVICE); 
  7.        if (onlineDevices.size() == 0) 
  8.            return
  9.        other = onlineDevices.get(0).getDeviceId();//获取联网中另一设备的id 
  10.    } 

利用上面分布式调度和页面跳转中intent类所带有的参数,并配合分布式数据库进行设备的绑定,代码如下:

  1. if(intent!=null) { 
  2.                //绑定设备 
  3.                if (intent.getStringParam("device").equals("A")) { 
  4.                    inputData_String(self, "A"); 
  5.                    inputData_String(other, "B"); 
  6.                } else if (intent.getStringParam("device").equals("B")) { 
  7.                    inputData_String(self, "B"); 
  8.                    inputData_String(other, "A"); 
  9.                } 
  10.            } 

至此,我们就完成了ID的同步了。

操作界面

相较于单机模式,双人模式按钮与操作对象绑定,按钮的回调方法改变如下(以其中一个按钮为例):

  1. button_left.setClickedListener(new Component.ClickedListener() { 
  2.                 @Override 
  3.                 public void onClick(Component component) { 
  4.                     if(queryContact_String(self).equals("A")) { 
  5.                         player1.left(); 
  6.                         update_Int("player1_d",player1.getDirection()); 
  7.                     } 
  8.                     else if(queryContact_String(self).equals("B")) 
  9.                     { 
  10.                         player2.left(); 
  11.                         update_Int("player2_d",player2.getDirection()); 
  12.                     } 
  13.                 } 
  14.             }); 

同步游戏的方法

同步游戏的方法有多种,说白了就是往数据库传什么类型的值,一下是我们想到的三种方法。

1.最直接的想法是传byte类型的数组,由于只能够传一维数组,可以把二维数组的行下标作为关键字,再把列作用一维数组传入。但是经过我的尝试,传数组容易造成程序闪退的问题。我们猜测由于数据的读取与写入是需要时间的,设备难以在小游戏高刷新速度的情况下完成数组的传递。

2.把二维数组先转化成字符串,再把字符串传到分布式数据库。在本地完成数组和字符串之间的转换,速度应该是很快的,这样只需要向数据库读写一次,设备能够完成。

3.传递玩家的坐标和方向,这种方法不需要进行字符串和数组之间的转换,且对数据库的读取量也较少,设备能够完成。

那么下面仅放出第二种实现代码,第三种的实现代码将在后续的完整代码中放出。

以下为数组和字符串之间转换的方法

  1. private String Array_to_String(int grids[][]) 
  2.    { 
  3.        StringBuilder builder=new StringBuilder(); 
  4.        for(int i=0;i<15;i++) 
  5.        { 
  6.            for(int j=0;j<15;j++) 
  7.            { 
  8.                builder.append(grids[i][j]); 
  9.            } 
  10.        } 
  11.        return builder.toString(); 
  12.    } 
  13.  
  14.    private int[][] String_to_Array(String value) 
  15.    { 
  16.        int [][] grid=grids; 
  17.        for(int i=0;i<15;i++) 
  18.        { 
  19.            for(int j=0;j<15;j++) 
  20.            { 
  21.             grid[i][j]= Integer.parseInt(value.substring(i*15+j,i*15+j+1)); 
  22.            } 
  23.        } 
  24.        return grid; 
  25.    } 

程序初始化:在启动时向数据库写入一些初始值

  1. public void initialize(){ 
  2.            layout = new DirectionalLayout(this); 
  3.            inputData_Int("player1_d",direction1);//分别把两个玩家的初始方向上传数据库 
  4.            inputData_Int("player2_d",direction2); 
  5.  
  6.            inputData_Int("A_score",0); 
  7.            inputData_Int("B_Score",0); 
  8.  
  9.            array=Array_to_String(grids);//把数组转化成字符串 
  10.            inputData_String("array",array);//把字符串写入数据库*/ 
  11.  
  12.            drawButton(); 
  13.            drawtable(); 
  14.        } 

视觉上的同步

想要把分布式数据库上的数据同步体现在视觉上,就需要创建一个以较高速度回调的时间对象,不断地调用画图方法以达到视觉上的同步。同时,在单机版的时候我们本来也有一个时间对象来回调player_run()。

  1.  public void run() 
  2.         { 
  3.             timer1=new Timer(); 
  4.  
  5.             timer1.schedule(new TimerTask() { 
  6.                 @Override 
  7.                 public void run() { 
  8.                     getUITaskDispatcher().asyncDispatch(()-> 
  9.                     { 
  10.                       if(!(game_over(player1,monster1,monster2)||game_over(player2,monster1,monster2)||gamesucess())) 
  11.                         { 
  12.                            if(queryContact_String("array")!=null
  13.                            { 
  14. player1.setDirection(queryContact_Int("player1_d"));                          player2.setDirection(queryContact_Int("player2_d")); 
  15.                                 array = queryContact_String("array"); 
  16.                                 grids = String_to_Array(array); 
  17.                                 player1.setScore(queryContact_Int("A_Score")); 
  18.                                 player2.setScore(queryContact_Int("B_Score")); 
  19.  
  20.  
  21.                             } 
  22.                            drawtable_test(); 
  23.                         } 
  24.                         else 
  25.                            ; 
  26.                     }); 
  27.                 } 
  28.             },0,70); 
  29.  
  30.             timer2=new Timer(); 
  31.             timer2.schedule(new TimerTask() { 
  32.                 @Override 
  33.                 public void run() 
  34.                 { 
  35.                     getUITaskDispatcher().asyncDispatch(()->{ 
  36.                         { 
  37.                             if(game_over(player1,monster1,monster2)||game_over(player2,monster1,monster2)) 
  38.                             { 
  39.                                 drawGame_over(); 
  40.                             } 
  41.                             else if(gamesucess()) 
  42.                             { 
  43.                                 drawGamesuccess(); 
  44.                             } 
  45.                             else 
  46.                             { 
  47.                                 player1.setDirection(queryContact_Int("player1_d")); 
  48.                                 player2.setDirection(queryContact_Int("player2_d")); 
  49.                                 if(queryContact_String("array")!=null
  50.                                 { 
  51.                                     array = queryContact_String("array"); 
  52.                                     grids = String_to_Array(array); 
  53.                                 } 
  54.                                 grids= player1.player_run_test(grids); 
  55.                                 grids=player2.player_run_test(grids); 
  56.                                 array=Array_to_String(grids); 
  57.                                 update_String("array",array); 
  58.                             } 
  59.                         } 
  60.                     }); 
  61.                 } 
  62.             },0,2000); 
  63.         } 

小结

本次学习笔记记录了吃豆豆的游戏实现,最近学习到的UI设置,页面跳转,分布式数据库,分布式任务调度等内容。作为我的第一个实践的项目,项目或多或少会有小问题和一些还没有解决的问题。例如在双人模式下取消了怪物的设定就是因为在怪物存在的情况下,常常会出现”怪物分身的问题“,我尝试过去解决但是都没有很好的效果,猜测是与数据库的读写有关。完整代码会在稍后作一些修改后放出,希望届时大家多加指证其中的错误。我当然也会继续去尝试解决本项目中未解决的问题。

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

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

https://harmonyos.51cto.com

 

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

2020-09-29 19:20:05

鸿蒙

2020-11-06 12:12:35

HarmonyOS

2021-12-20 15:44:28

ShardingSph分布式数据库开源

2023-12-05 07:30:40

KlustronBa数据库

2023-07-31 08:27:55

分布式数据库架构

2022-03-10 06:36:59

分布式数据库排序

2023-03-07 09:49:04

分布式数据库

2023-07-28 07:56:45

分布式数据库SQL

2020-06-23 09:35:13

分布式数据库网络

2022-08-01 18:33:45

关系型数据库大数据

2015-10-16 18:03:25

Docker分布式CoreOS

2023-06-26 00:14:28

Openjob分布式任务

2020-04-14 11:14:02

PostgreSQL分布式数据库

2022-12-08 08:13:11

分布式数据库CAP

2012-09-29 13:18:23

分布式数据库Google Span

2018-05-25 13:12:10

UCloud数据库UDDB

2022-06-09 10:19:10

分布式数据库

2021-12-14 10:16:00

鸿蒙HarmonyOS应用

2023-04-26 06:56:31

分布式数据库伪需求

2024-03-15 07:33:02

分布式数据库索引数据结构
点赞
收藏

51CTO技术栈公众号