Welcome to the CSC Q&A.
Get help and give help!
Write great code!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+6 votes

Maybe sometimes the keystrokes don't work, or you can't get it to work at all...

asked ago in CSC201 Spring 2021 by (13k points)

1 Answer

+1 vote

There could be a number of reasons, but one of the common ones is that people aren't properly understanding how checkKey works.

You should probably only call checkKey() ONCE each time through your main game loop, and save the returned value to a variable, so that you can keep checking that variable.

The problem is, if you call checkKey() multiple times in a row, then you will only get the key the user pressed returned by checkKey() the FIRST time it is called. After that, you'll just get the empty string "" back until the user presses another key.(edited)

Remember that checkKey() returns the name of any key that the user pressed SINCE the last time you called checkKey(), or the empty string "" if no key was pressed in that time.

For example, I am seeing students writing code like:

if window.checkKey() == 'Left':
   ...
elif window.checkKey() == 'Right':
   ...

But if the user pressed the 'Right' arrow key, then the first checkKey() will return 'Right', but the second checkKey() will return "", because the 'Right' keystroke has already been processed, and the user didn't have time to press any other keys before checkKey() got called again.

Instead, you should do something like:

key = window.checkKey()
if key == 'Left':
   ...

This way, you won't MISS any user keystrokes. Every keystroke gets to the key variable, and then you can take the appropriate action, depending on what the key variable is ('Left', 'Right', etc., or the empty string "" because they didn't hit a key since the last checkKey).

answered ago by (13k points)
...