PDA

View Full Version : While Loop and Keypress Listener


wbarnum
08-21-2015, 12:33 PM
I've written a program that is supposed to move a character forward as long as the "up" arrow is pressed.

I'm using a while loop with the condition "event isKey UP is true".

The character starts moving forward when I press the "up" arrow, but when I release it, the character continues moving forward indefinitely.

I don't know if this is a bug or a case of user error.

MrMoke
08-21-2015, 01:54 PM
User Error.
You don't need the while statement, just an if.
Examine the "add details" options in the header of the key press event, and experiment with those to see what happens.

http://www.alice.org/3.1/materials_videos.php

wbarnum
08-21-2015, 02:41 PM
User Error.
You don't need the while statement, just an if.
Examine the "add details" options in the header of the key press event, and experiment with those to see what happens.

http://www.alice.org/3.1/materials_videos.php

Using an if has other undesirable consequences.

Is there any reason from a computer science perspective that a while loop shouldn't work here?

MrMoke
08-21-2015, 06:31 PM
From a Computer Science Perspective, Yes Absolutely!
Your while loop is doing exactly what it is supposed to do. (ie: Execute repeatedly as long as the test is true)

Don't forget to review the link I added to my last post, and checkout the How-to guide

wbarnum
08-24-2015, 01:15 PM
Your while loop is doing exactly what it is supposed to do. (ie: Execute repeatedly as long as the test is true)

When I let up on the key, wouldn't that make the condition false and it would stop executing the inner loop and therefore stop moving the character forward?

MrMoke
08-24-2015, 05:54 PM
Nope-
A key press triggers a call to the event, and the key value is passed in. If it is the key that you are looking for, the "while" will never stop because you are already in the event. Instead, focus on the "add detail" options in the "arrowKeyPressed" header.

Time to start Experimenting ;)

When I let up on the key, wouldn't that make the condition false and it would stop executing the inner loop and therefore stop moving the character forward?