📄 wraprandom.cpp
字号:
#include <airobot/cpp/SimpleRobot.hpp>
/**
* 围绕对手作来回的移动,并在此基础上添加了与对手保持一定距离,不撞墙的功能,
* 并且运动带有随机性。
* @author xiemin
*/
class WrapRandom : public SimpleRobot
{
private:
//理想距离
static const double PREFER_DISTANCE;
//计算目标点时采用的搜索半径
static const double SEARCH_DIS;
//每次迭代的递增量
static const double GAP;
//离墙的距离
static const double AWAY_FROM_WALL;
//移动的方向,这个变量的值只能取1和-1,1表示前进,-1表示后退
int direction;
//在一个方向上最大的移动时间
long maxTime;
//当前在一个方向上的移动时间
long time;
public:
WrapRandom(void)
{
direction = 1;
time = 0;
maxTime = 30;
}
void onTick(TickAction* action)
{
setDirection();
doMove();
doTurn();
}
private:
/**
* 设置移动的方向
*/
void setDirection(void)
{
time++;
if(time>=maxTime)
{
time=0;
//随机生成在这个方向上移动的时间
maxTime = rand()%60;
//改变运动方向
direction *= -1;
}
}
/**
* 执行移动
*/
void doMove(void)
{
move(10*direction);
}
/**
* 执行转动
*/
void doTurn(void)
{
Point2D center = getCenter();
double lineHeading = Math::heading(getLocation(), center);
double headingTo = lineHeading + Math::PI/2;
//为了保持距离用deltaAngle对headingTo进行修正
double deltaAngle = getDeltaAngle(center);
headingTo -= deltaAngle;
//为了不撞墙用needTurn对headingTo进行修正
double needTurn = getNeedTurn(headingTo);
headingTo -= needTurn;
//执行转动
double bearing = Math::bearing(headingTo, getHeading());
turn(bearing);
}
/**
* 得到用于保持理想距离的修正角deltaAngle
* @param center
* @return
*/
double getDeltaAngle(Point2D& center)
{
double distance = Math::distance(center, getLocation());
double deltaDistance = distance-PREFER_DISTANCE;
deltaDistance = deltaDistance/Math::max(distance, PREFER_DISTANCE);
return direction*Math::PI/3*deltaDistance;
}
/**
* 得到用来修正移动方向避免机器人撞墙的夹角needTurn
* @param headingTo
* @return
*/
double getNeedTurn(double headingTo)
{
double needTurn = 0;
//进入迭代
while(true)
{
Point2D nextPos = Math::nextPoint(
getLocation(), headingTo-needTurn, direction*SEARCH_DIS);
if(isValid(nextPos)) break;
needTurn += direction*GAP;
}
return needTurn;
}
/*
* 判断给定的点是否是一个有效的目标点
*/
bool isValid(const Point2D& point)
{
return inCourt(point, AWAY_FROM_WALL);
}
/**
* 得到圆心位置
*/
Point2D getCenter(void)
{
Bot* bot = getFirstOpponent();
if(bot!=NULL) return bot->getLocation();
else return Point2D(getCourtWidth()/2, getCourtHeight()/2);
}
};
const double WrapRandom::PREFER_DISTANCE = 300;
const double WrapRandom::SEARCH_DIS = 100;
const double WrapRandom::GAP = Math::toRadians(2);
const double WrapRandom::AWAY_FROM_WALL = 50;
//启动机器人程序
int main(int argC, char* argV[])
{
Robot* robot = new WrapRandom();
return startup(argC, argV, robot);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -