好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

跳一跳自动跳跃C#代码实现

      最近这款[跳一跳]很火,在段子里面看到有人才放了张画着坐标的纸在手机上,说根据距离确定摁的[嘟]的次数,还有通过程序来实现自动计算的。看得心血来潮忍不住来试一试?话不多说,先上图。

       因为比较急着做出成品,所以细节上没多细抠。感觉设置的跳跃速度稍快了一点,有兴趣的同学可以实测一下。也有一个因素是测试时后台程序比较多,影响了结果。
       原理其实也是跟大家想的一样很简单,无非就是三个要素:距离、速度、时间。就是通过当前小蓝人脚底所在的像素坐标和目标平台中心像素的坐标计算距离,除以事先通过测试得出的速度,得出触摸屏幕时间,由程序发出[触摸]指令,实现定点跳跃。不过在做自动计算跳跃所需触摸时间之前还是要做一些准备功夫的。下面直接说一下详细的过程吧。

准备工作:

1、通过ps等工具获取①小蓝人最底下一行(作为当前位置y坐标)和最左边一列(作为当前位置x坐标)的像素rgb,实测在本机基本都是一样的x(54,63, 102),y(43, 43, 73)。图片左上角、右下角坐标分别为[0,0][xmax,ymax]。②获取小蓝人的头的宽度(所占像素点)。③获取左上角分数最底下一行的像素y坐标。

2、通过指令

?

adb shell input touchscreen swipe x y x y 延时(ms)

(x、y为触摸屏幕的坐标),结合photoshop测试出[跳一跳]每一条的速度。本例中测得结果约为17 / 24(pixel/ms),实际游戏中的速度略小于这个速度。大家用代码可以精确测一下,我已经没耐心了0.0。

3、电脑准备好调试环境(因为穷所以测试用的是自己的android机,所以要准备好adk(platform-tools/adb.exe);另外本次测试语言是c#)

4、手机开启调试模式,连接电脑,打开[跳一跳] 

过程:

一、获取设备号(获取序列号,或者直接查看手机信息),指令:

?

adb devices

二、截取手机当前画面到sd卡(本机存储格式为png,实测手机按键截屏为jpg(失真)),指令:

?

adb -s 设备号 shell screencap -p /sdcard/temp.png

三、复制文件到电脑,指令:

?

adb -s 设备号 pull /sdcard/temp.png 保存路径

四、删除文件,指令:

?

adb -s 设备号 shell rm /sdcard/temp.png

五、获取小蓝人脚底像素坐标和目标平台中心像素坐标,下面详细说说里面的步骤

1、通过bitmap类读取图片,再用unsafe代码利用指针把rgb数据直接从内存拷出来存放到byte数组中(这步其实不用也可以但不知道直接通过bitmap获取像素效率会不会很低,大家可以测了分享一下结果)
2、用两层循环y从max->0,遍历x轴像素,通过对比找出小蓝人位置,本例通过两个rgb像素的标准差不超过3作为置信偏差判断两个像素是否为同一元素。再稍微处理一下就可得出当前坐标。
3、利用上面得到的坐标p以及一开始准备工作中提到的分数底行y坐标(取大于该y作为starty即可)再进行对目标坐标的搜索:用两层循环y从starty->py,遍历x轴像素(利用p的x坐标缩小搜索的x坐标范围:若x位于左半屏则搜索px+40->xmax,反之搜索0->px-40,注:不缩小范围会出错,原因大家想想)。(这个40可取大于小蓝人头宽度一半的值即可)
4、那就用我们的勾三股四弦五定理再开根求出距离。距离除以速度得出时间。

六、发送触摸指令实现定时跳跃,指令:

?

adb shell input touchscreen swipe x y x y延时(ms)

       这里不得不说一下,当时找半天找不到定时触摸的指令,网上有个用6个指令组合实现定时触摸屏幕的方法,但实测无效,而且也怕指令这么多,延时还是分开控制,肯定会对跳跃结果有很大影响。后面看到一条利用swipe指令实现的评论,真是醒目。swipe虽然是滑动指令,但如果设置起止坐标都是同一个坐标不就相当于实现了定点定时触摸了吗。

七、七就是一直重复二~六的步骤就是了。

       本次测试很东西都是急着做,没仔细研究,例如获取跳跃速度这个就是傻瓜式的通过手动发送跳跃指令、截图用ps手动计算出来的。大家可以用代码实现一下。希望大家指正可以改进的地方。

c#源码如下

cmd类,实现cmd执行命令

?

class cmd

{

  private system.diagnostics.process process;

  private bool isexecuted; // 是否执行过命令

  private string command; // 上次执行命令

  private int result;  // 上次执行命令结果

  private string resultcontent; // 上次执行命令返回结果

  public cmd()

  {

  process = new system.diagnostics.process();

  process.startinfo.filename = "cmd.exe" ;

  process.startinfo.useshellexecute = false ; //是否使用操作系统shell启动

  process.startinfo.redirectstandardinput = true ; //接受来自调用程序的输入信息

  process.startinfo.redirectstandardoutput = true ; //由调用程序获取输出信息

  process.startinfo.redirectstandarderror = true ; //重定向标准错误输出

  process.startinfo.createnowindow = true ; //不显示程序窗口

 

  isexecuted = false ;

  }

  public int executecmd( string cmd)

  {

  command = cmd;

  try

  {

   process.start();

   process.standardinput.writeline(cmd + "&exit" );

   process.standardinput.autoflush = true ;

   string content = process.standardoutput.readtoend();

   process.waitforexit(); //等待程序执行完退出进程

   process.close();

 

   result = 0;

   resultcontent = content.split( new string [] { "&exit" }, stringsplitoptions.none)[1].replace( "\n" , "" );

  }

  catch (exception ex)

  {

   result = -1;

   resultcontent = ex.message;

  }

 

  if (!isexecuted) isexecuted = true ;

 

  return result;

  }

  private int executecmd( string adbpath, string cmd)

  {

  command = $ "\"{adbpath}\" {cmd}" ;

  try

  {

   process.start();

   process.standardinput.writeline(command + "&exit" );

   process.standardinput.autoflush = true ;

   string content = process.standardoutput.readtoend();

   process.waitforexit(); //等待程序执行完退出进程

   process.close();

 

   result = 0;

   resultcontent = content.split( new string [] { "&exit" }, stringsplitoptions.none)[1].replace( "\n" , "" );

  }

  catch (exception ex)

  {

   result = -1;

   resultcontent = ex.message;

  }

 

  if (!isexecuted) isexecuted = true ;

 

  return result;

  }

  public string getexcresult()

  {

  if (isexecuted)

  {

   if (result == 0)

   {

   return resultcontent;

   }

   else

   {

   return $ "execute failed! command:{command}\n{resultcontent}" ;

   }

  }

  else

  {

   return "从未执行过命令" ;

  }

  }

  public void disposeprocess()

  {

  process.dispose();

  }

}

 

class pixel

{

  public byte [] pixel = new byte [3];

  public pixel()

  {

 

  }

}

pixel类,存放rgb字节

?

class pixel

  {

  public byte [] pixel = new byte [3];

  public pixel()

  {

 

  }

  }

playjumpjump类,实现主要分析计算和跳跃操作

?

class playjumpjump

  {

  private static readonly int confidenceitv = 3; // 两个rgb标准差小于等于3认为是同一元素

  private static readonly pixel manxrgb = new pixel { pixel = new byte [] { 54, 63, 102 } }; // 小人x坐标rgb

  private static readonly pixel manyrgb = new pixel { pixel = new byte [] { 43, 43, 73 } }; // 小人y坐标rgb

  private static readonly double startyper = 0.15625; // 分数下一行y为第289,取 300 / 1920 = 0.15625, 从下一行开始搜索目标

  private static readonly double speed = 17.0 / 24; // 速度,最重要的因素,这也是约摸算出来的

  private static readonly string [] touchcoor = new string [] { "800" , "1700" }; // 触屏位置

  private static readonly string format = "png" ; // 本人用机子截取为png,也可不设格式(实测bitmap与ps cc打开同一jpg,同一像素点rgb值不一致,怀疑是bitmap打开jpg会有失真)

  private static readonly string tempdir = "/sdcard/" ;

  private static readonly string savedir = "temp/" ;

  private static readonly string capturescreen_command = $ "-s {{0}} shell screencap -p {tempdir}{{1}}" ;

  private static readonly string copyfile_command = $ "-s {{0}} pull {tempdir}{{1}} \"{savedir}{{1}}\"" ;

  private static readonly string removefile_command = $ "-s {{0}} shell rm {tempdir}{{1}}" ;

  private static readonly string longpress_command = "shell input touchscreen swipe {0} {1} {0} {1} {2}" ;

  private cmd mycmd;

  private string adbcmdprefix;

  private string result;

  public list< string > devices;

 

  public playjumpjump( string adbpath)

  {

   mycmd = new cmd();

   adbcmdprefix = $ "\"{adbpath}\" " ;

   if (!directory.exists(savedir))

   {

   directory.createdirectory(savedir);

   }

  }

  public void init()

  {

   mycmd = new cmd();

  }

  public bool getdevices()

  {

   devices = new list< string >();

   mycmd.executecmd(returncommand( "devices" ));

   result = mycmd.getexcresult();

   foreach ( string line in result.split( new char [] { '\n' }))

   {

   if (line.contains( "device" ))

   {

    list< string > items = line.split( new char [] { '\t' , '\r' }, stringsplitoptions.none).tolist();

    if (items.count > 1)

    {

    devices.add(items[items.indexof( "device" ) - 1]);

    }

   }

   }

   return devices.count > 0 ? true : false ;

  }

  public string capturescreen()

  {

   string filename = $ "temp{datetime.now.tostring(" hhmmssfff ")}.{format}" ;

   mycmd.executecmd(returncommand(capturescreen_command, new string [] { devices[0], filename }));

   mycmd.executecmd(returncommand(copyfile_command, new string [] { devices[0], filename }));

   mycmd.executecmd(returncommand(removefile_command, new string [] { devices[0], filename }));

   return appdomain.currentdomain.basedirectory + savedir + filename;

  }

  public static unsafe pixel[][] getpixelarray( string path)

  {

   bitmap bitmap = new bitmap(path);

   int depth = image.getpixelformatsize(bitmap.pixelformat);

   if (depth == 24)

   {

   int width = bitmap.width;

   int height = bitmap.height;

   pixel[][] pixelarray = new pixel[height][];

   for ( int i = 0; i < pixelarray.length; i++) pixelarray[i] = new pixel[width];

 

   rectangle rect = new rectangle(0, 0, bitmap.width, bitmap.height);

   bitmapdata bmpdata = bitmap.lockbits(rect, imagelockmode. readonly , pixelformat.format24bpprgb);

 

   byte * ptr = ( byte *)bmpdata.scan0;

   for ( int i = 0; i < pixelarray.length; i++)

   {

    for ( int j = 0; j < pixelarray[i].length; j++)

    {

    pixelarray[i][j] = new pixel { pixel = new byte [] { *(ptr + 2), *(ptr + 1), *ptr } };

    ptr += 3;

    }

    ptr += bmpdata.stride - 3 * bmpdata.width; // 减去占位字节(可能出于性能或兼容性考虑,stride为4的倍数)

   }

 

   bitmap.unlockbits(bmpdata);

   return pixelarray;

   }

   else if (depth == 32)

   {

   int width = bitmap.width;

   int height = bitmap.height;

   pixel[][] pixelarray = new pixel[height][];

   for ( int i = 0; i < pixelarray.length; i++) pixelarray[i] = new pixel[width];

 

   rectangle rect = new rectangle(0, 0, bitmap.width, bitmap.height);

   bitmapdata bmpdata = bitmap.lockbits(rect, imagelockmode. readonly , pixelformat.format32bpprgb);

 

   byte * ptr = ( byte *)bmpdata.scan0;

   for ( int i = 0; i < pixelarray.length; i++)

   {

    for ( int j = 0; j < pixelarray[i].length; j++)

    {

    pixelarray[i][j] = new pixel { pixel = new byte [] { *(ptr + 2), *(ptr + 1), *ptr } };

    ptr += 4; // 每3个字节忽略1个透明度字节

    }

   }

 

   bitmap.unlockbits(bmpdata);

   return pixelarray;

   }

   else

   {

   return null ;

   }

  }

  public void jump2happy()

  {

   string picture = capturescreen();

   pixel[][] pixelarray = getpixelarray(picture);

   int [] curcoor = getcurcoordinates(pixelarray);

   int [] destcoor = getdestcoordinates(pixelarray, curcoor);

   double distance = math.round(math.sqrt(math.pow(math.abs(destcoor[0] - curcoor[0]), 2) + math.pow(math.abs(destcoor[1] - curcoor[1]), 2)), 3);

   int time = ( int )(distance / speed);

   console.writeline($ "from [{curcoor[0]},{curcoor[1]}]\tto [{destcoor[0]},{destcoor[1]}] distance≈{distance} take≈{time}ms ==>> jump " );

   mycmd.executecmd(returncommand(longpress_command, new string [] { touchcoor[0], touchcoor[1], time.tostring() }));

  }

  public static int [] getcurcoordinates(pixel[][] pixelarray)

  {

   int [] coordinates = new int [2];

   list< int []> xlist = new list< int []>();

   list< int []> ylist = new list< int []>();

   // y从max -> 0,遍历x轴像素

   for ( int i = pixelarray.length - 1; i >= 0; i--)

   {

   for ( int j = 0; j < pixelarray[i].length; j++)

   {

    if (issameelement(pixelarray[i][j], manxrgb, confidenceitv))

    {

    xlist.add( new int [] { j, i });

    }

   }

   if (xlist.count > 0) break ;

   }

   coordinates[0] = xlist.count > 0 ? (xlist[0][0] + xlist[xlist.count - 1][0]) / 2 : 0;

 

   // x从0 -> max,遍历y轴像素

   for ( int i = 0; i < pixelarray[0].length; i++)

   {

   for ( int j = pixelarray.length - 1; j >= 0; j--)

   {

    if (issameelement(pixelarray[j][i], manyrgb, confidenceitv))

    {

    ylist.add( new int [] { i, j });

    }

   }

   if (ylist.count > 0) break ;

   }

   coordinates[1] = ylist.count > 0 ? (ylist[0][1] + ylist[ylist.count - 1][1]) / 2 : 0;

 

   return coordinates;

  }

  public static int [] getdestcoordinates(pixel[][] pixelarray, int [] curcoor)

  {

   pixel envirgb; // 排除rgb采样

   pixel destrgb = null ; // 采样

   int [] coordinates = new int [2];

   list< int []> xlist = new list< int []>();

   list< int []> ylist = new list< int []>();

   int starty = ( int )(pixelarray.length * startyper);

   int start, end, inc;

   if (curcoor[0] < (pixelarray[0].length / 2))

   {

   start = curcoor[0] + 40;

   end = pixelarray[0].length;

   }

   else

   {

   start = 0;

   end = curcoor[0] - 40;

   }

   // y从0 -> max,遍历x轴像素

   for ( int i = starty; i < pixelarray.length; i++)

   {

   envirgb = pixelarray[i][0];

   for ( int j = start; j < end; j++)

   {

    if (!issameelement(pixelarray[i][j], envirgb, confidenceitv))

    {

    xlist.add( new int [] { j, i });

    if (destrgb == null ) destrgb = pixelarray[i][j];

    }

   }

   if (xlist.count > 0) break ;

   }

   coordinates[0] = xlist.count > 0 ? (xlist[0][0] + xlist[xlist.count - 1][0]) / 2 : 0;

 

   // x从0 -> max,遍历y轴像素

   if (coordinates[0] < (pixelarray[0].length / 2))

   {

   start = 0;

   end = pixelarray[0].length - 1;

   inc = 1;

   }

   else

   {

   start = pixelarray[0].length - 1;

   end = 0;

   inc = -1;

   }

   bool isfond = false ;

   for ( int i = start; i != end; i+=inc)

   {

   for ( int j = starty; j < curcoor[1]; j++)

   {

    if (issameelement(pixelarray[j][i], destrgb, confidenceitv))

    {

    coordinates[1] = j;

    isfond = true ;

    break ;

    }

   }

   if (isfond) break ;

   }

 

   return coordinates;

  }

  public static bool issameelement(pixel pixel1, pixel pixel2, int confidence)

  {

   return math.pow(pixel1.pixel[0] - pixel2.pixel[0], 2) + math.pow(pixel1.pixel[1] - pixel2.pixel[1], 2) + math.pow(pixel1.pixel[2] - pixel2.pixel[2], 2) <= 3 * math.pow(confidence, 2);

  }

  public string returncommand( string command, string [] parameter)

  {

   return adbcmdprefix + string .format(command, parameter);

  }

  public string returncommand( string command, string parameter)

  {

   return adbcmdprefix + string .format(command, parameter);

  }

  public string returncommand( string command)

  {

   return adbcmdprefix + command;

  }

  public void disposeprocess()

  {

   mycmd.disposeprocess();

   mycmd = null ;

  }

测试:

?

static void main( string [] args)

  {

   string adbpath = "" ; // adb.exe路径

  

   playjumpjump testplay = new playjumpjump(adbpath);

   if (testplay.getdevices())

   {

   while ( true )

   {

    testplay.jump2happy();

    thread.sleep(1200);

   }

   }

 

   testplay.disposeprocess();

 

   console.readkey();

  }

  }

更多内容大家可以参考专题《微信跳一跳》进行学习。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/iaplayer/article/details/79008711

dy("nrwz");

查看更多关于跳一跳自动跳跃C#代码实现的详细内容...

  阅读:43次