Student claims the motorcyle moves diagnolly when he presses either button after reset


#1

//buggy code
// Set the speed of the motorcycle
var speed = 10;
var switchWatch = 0
onBoardEvent(toggleSwitch,“open”,function(event) {
if (toggleSwitch.isOpen === true) {
led.on();
// Move the motorcycle up when the left button is clicked
onBoardEvent( buttonL, “press”, function(event) {
var y = getProperty(“motorcycle”, “y”);
setProperty(“motorcycle”, “y”, y - speed);
});
// Move the motorcycle down when right button is clicked
onBoardEvent( buttonR, “press”, function(event) {
var y = getProperty(“motorcycle”, “y”);
setProperty(“motorcycle”, “y”, y + speed);
});
}
});
onBoardEvent(toggleSwitch,“close”,function(event) {
if (toggleSwitch.isOpen === false) {
led.off();
onBoardEvent( buttonL, “press”, function(event) {
var x = getProperty(“motorcycle”, “x”);
setProperty(“motorcycle”, “x”, x - speed);
});

// Move the motorcycle down when right button is clicked
onBoardEvent( buttonR, “press”, function(event) {
var x = getProperty(“motorcycle”, “x”);
setProperty(“motorcycle”, “x”, x + speed);
});
}
});


#2

@efarrow

Hi Eugenie,

This code should make the motorcycle move diagonally after the toggle switch has been closed and opened because the student is creating the button press events inside the toggle open and lose events.

When the user opens the toggle switch, two new events are created. These events move the motor cycle up and down with the buttons. The student should note that these events continue to exist even after the toggle switch is closed, so for the rest of the run of this program, the buttons will move the motorcycle up and down, no matter the state of the toggle switch.

If the user closes the toggle switch, two new events are created. These events moce the motorcycle left and right with the buttons. These events continue to exist even after the toggle switch is open, so for the rest of the run of this program, the buttons will move the motorcycle let and right, no matter the state of the toggle switch.

At this point, the left button will move the motorcycle both to the left and up (so diagonally) and the right button will move the motorcycle for to the right and down (diagonally).

I think what the student actually wants to do is create an event that checks for a left button press, then uses a conditional to determine the state of the toggle switch and makes the motorcycle move either left or up depending on whether the toggle is open or closed, then create a similar event for the right button. This program does not actually need an event for changing the toggle switch, just checking its state.

Elizabeth


#3

Thank you. I see the issue and have discussed with student.