Guest User

Untitled

a guest
Feb 19th, 2018
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. #include <iostream> // mainを使わないとき不要
  2. #include <vector>
  3. #include <cmath> // sqrt, powに必要
  4. using namespace std;
  5.  
  6. // 戦略を分析した後に最適なものを返すクラス
  7. class Teacher
  8. {
  9. private:
  10. vector< double > log; // 各bhvのゴールとボールの距離の合計
  11. int bhvnum; // bhvの数
  12. int curbhv; // 行うべきbhv
  13. int precycle; // 学習サイクル
  14.  
  15. // 現在の状況を保持する変数
  16. double goalx;
  17. double goaly;
  18. double ballx;
  19. double bally;
  20. int cycle;
  21.  
  22. double distance(double, double, double, double);
  23.  
  24. public:
  25. Teacher(int, int);
  26. void set_goalpos(double, double);
  27. void set_ballpos(double, double);
  28. void set_cycle(int);
  29.  
  30. void update(void);
  31. int bhv(void);
  32.  
  33. };
  34.  
  35. // num = behaviorの数
  36. // cyc = 学習するサイクル
  37. Teacher::Teacher(int num, int cyc){
  38. curbhv = 0;
  39. bhvnum = num;
  40. precycle = cyc;
  41.  
  42. log.resize(bhvnum);
  43.  
  44. return;
  45. }
  46.  
  47. // ゴールの座標設定
  48. void Teacher::set_goalpos(double x, double y){
  49. goalx = x;
  50. goaly = y;
  51. return;
  52. }
  53.  
  54. // ボールの座標設定
  55. void Teacher::set_ballpos(double x, double y){
  56. ballx = x;
  57. bally = y;
  58. return;
  59. }
  60.  
  61. // サイクル設定
  62. void Teacher::set_cycle(int c){
  63. cycle = c;
  64. return;
  65. }
  66.  
  67. // 学習データを更新
  68. void Teacher::update(void){
  69. if (cycle < precycle ){
  70. log[curbhv] += distance(goalx, goaly, ballx, bally);
  71. curbhv = (int)( cycle / (precycle / bhvnum) );
  72. }else{
  73. int smaller = 0;
  74. for( int i=0; i<bhvnum; i++){
  75. if( log[smaller] > log[i] ) smaller = i;
  76. }
  77. curbhv = smaller;
  78. }
  79. return;
  80. }
  81.  
  82. // エージェントが行うべきbehaviorを返す
  83. int Teacher::bhv(void){
  84. return curbhv;
  85. }
  86.  
  87. // 2点間の距離を計算する
  88. double Teacher::distance(double ax, double ay, double bx, double by){
  89. double diffx = ax - bx;
  90. double diffy = ay - by;
  91. return pow( sqrt(diffx) + sqrt(diffy) , 2.0);
  92. }
  93.  
  94.  
  95. // 利用例
  96. // behaviorが2つで50サイクル学習、
  97. // ボールが徐々にゴールから離れる入力、
  98. // 前半のほうがゴールに近いので、0が返れば正しい
  99. int main(void){
  100. Teacher tcr(2, 50);
  101. tcr.set_goalpos(52.5, 0.0 );
  102. for(int i=0;i<80;i++){
  103. tcr.set_ballpos(50 - i , 0.0);
  104. tcr.set_cycle(i);
  105. tcr.update();
  106. cout << "now: "<< i << "bhv: "<< tcr.bhv() << endl;
  107. }
  108. return 0;
  109. }
Add Comment
Please, Sign In to add comment