Create a gist now

Instantly share code, notes, and snippets.

EV3 Lego Cannon, see {edit this part} for building instructions
import lejos.hardware.Button;
import lejos.hardware.lcd.LCD;
import lejos.hardware.motor.EV3LargeRegulatedMotor;
import lejos.hardware.motor.EV3MediumRegulatedMotor;
import lejos.hardware.port.MotorPort;
public class CanonGame {
public static void main(String[] args) {
Cannon cannon = new Cannon();
cannon.play();
}
}
class Cannon {
private EV3MediumRegulatedMotor gunMotor;
private EV3LargeRegulatedMotor verticalMotor;
private EV3LargeRegulatedMotor horizontalMotor;
public Cannon() {
gunMotor = new EV3MediumRegulatedMotor(MotorPort.A);
verticalMotor = new EV3LargeRegulatedMotor(MotorPort.B);
horizontalMotor = new EV3LargeRegulatedMotor(MotorPort.D);
displayStandardScreen();
}
/**
* Bring the play menu, rotate the gun when the user presses the
* buttons on the brick. Shoot when ENTER is pressed and quit
* when ESCAPE is pressed.
*/
public void play()
{
while (true)
{
int command = Button.getButtons();
if (command == 0) //No buttons pressed
continue;
if (command == Button.ID_UP)
horizontalMotor.rotate(-1);
else if (command == Button.ID_DOWN)
horizontalMotor.rotate(1);
else if (command == Button.ID_LEFT)
verticalMotor.rotate(-1);
else if (command == Button.ID_RIGHT)
verticalMotor.rotate(1);
else if (command == Button.ID_ENTER)
shoot();
else if (command == Button.ID_ESCAPE)
break;
displayStandardScreen();
}
}
public void shoot()
{
LCD.clear(0);
LCD.drawString("Shooting", 0, 0, true);
LCD.refresh();
gunMotor.rotate(360);
gunMotor.rotate(-360);
}
/**
* Show standard information screen with vertical and
* horizontal angles.
*/
private void displayStandardScreen()
{
LCD.clear();
LCD.drawString("Cannons loaded", 0, 0, true);
LCD.drawString("Vertical: " + verticalMotor.getTachoCount(), 0, 1);
LCD.drawString("Horizontal: " + horizontalMotor.getTachoCount() , 0, 2);
LCD.refresh();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment