用爪子对PLTW机器人自然语言进行编程


if(SensorValue (bumpswitch)==1)
{
startMotor(WheelMotor2,-20);
}
if(SensorValue (bumpswitch2)==1)
{
startMotor(WheelMotor2,20);
}
if(SensorValue(bumpswitch3)==1)
{
startMotor(LiftMotor,30);
}
if(SensorValue(bumpswitch3)==0)
{
stopMotor(LiftMotor);
}
if (SensorValue(bumpswitch4)==1)
{
startMotor(TopMotor,120);
}

} 我们如何让所有这些电机用一个凸块开关移动?有没有更好的方法来编码?

您似乎缺少else关键字。

为了解释一下,这里有一些类似于你的代码:

if (condition1) {action1;}
if (condition2) {action2;}

如果两者都为真,则两者都被执行。这意味着如果bumpswitchbumpswitch2都有值1,那么代码将首先在20处旋转电机,然后立即将其更改为-20

if (condition1) {action1;}
else if (condition2) {action2;}

这相当于:

if (condition1) {
action1;
} else {
if (condition2) {
action2;
}
}

如果condition1满意,那么它将运行第一部分(action1)。如果不满意,condition2满意,那么它将运行第二部分。所以:

if (传感器值(凹凸开关) == 1) { 启动电机(轮电机2, -20); } else if (SensorValue(bumpswitch2) == 1) { 启动电机(轮电机2, 20); }

将解决第一个问题。

现在,至于更好的编码方法,并没有太多需要改进的地方。如果你想要更多关于使代码更好的技巧,你可能想查看 CodeReview.SE。

最终代码应如下所示:

if (SensorValue(bumpswitch) == 1) {
startMotor(WheelMotor2, -20);
} else if (SensorValue(bumpswitch2) == 1) {
startMotor(WheelMotor2, 20);
}
if (SensorValue(bumpswitch3) == 1) {
startMotor(LiftMotor, 30);
} else if (SensorValue(bumpswitch3) == 0) {
stopMotor(LiftMotor);
}
if (SensorValue(bumpswitch4) == 1) {
startMotor(TopMotor, 120);
}

请注意,它们并不都是else if块,否则只能执行一个操作。

或者,如果问题是电机一个接一个地启动,那么这应该可以工作:

if (SensorValue(bumpswitch) == 1) {
new Thread() {
public void run() {
startMotor(WheelMotor2, -20);
}
}).start();
} else if (SensorValue(bumpswitch2) == 1) {
new Thread() {
public void run() {
startMotor(WheelMotor2, 20);
}
}).start();
}
if (SensorValue(bumpswitch3) == 1) {
new Thread() {
public void run() {
startMotor(liftMotor, 30);
}
}).start();
} else if (SensorValue(bumpswitch3) == 0) {
new Thread() {
public void run() {
stopMotor(liftMotor);
}
}).start();
}
if (SensorValue(bumpswitch4) == 1) {
new Thread() {
public void run() {
startMotor(TopMotor, 120);
}
}).start();
}

这将为每个操作启动一个新线程,以便它们并行运行。

如果传感器值必须为 1 或 0,则可以将else if (SensorValue(bumpswitch3) == 0)替换为else,因为如果c1if (c1) {a1;} else {a2;}将运行a1,否则,仅以其他方式运行,a2

最新更新