0

I am trying to write a simple program that will allow me to control the location of the number 5 in an array. However, when I run the code the controls don't really work. Also, I'm trying to clear the terminal so that it only shows the current position, not the past ones, but even that doesn't work. Please help.

import numpy as np
import keyboard
from os import system




a = int(input())
c = int(input())
z = 0


isKEYPRESSED = 0



while (True):
    b = np.zeros((a,c))
    for i in range(a):
        for j in range(c):
            b[i][j]=0

    b[z][0] = 5
    print(b)
    
    if keyboard.read_key() =="right" and isKEYPRESSED == 0:
        b[z][0] = 0
        z = z + 1
        isKEYPRESSED = 1
        if keyboard.read_key() =="right" and isKEYPRESSED == 1:
            isKEYPRESSED = 0
    if keyboard.read_key() =="left" and isKEYPRESSED == 0:
        b[z][0] = 0
        z = z - 1
        isKEYPRESSED = 1
        if keyboard.read_key() =="left" and isKEYPRESSED == 1:
            isKEYPRESSED = 0
    
    system('clear')
martineau
  • 119,623
  • 25
  • 170
  • 301
J R
  • 1

1 Answers1

0

You can try this, which uses more reliable callbacks that only fire on "key down". However, be aware that this is installing GLOBAL hooks, which will grab keys no matter which app has the focus. The keyboard module is not a good choice for this kind of application.

import numpy as np
import keyboard
from os import system
import sys


a = int(input())
c = int(input())
z = 0

b = np.zeros((a,c))


def onkey(evt):
    global z
    print(evt.name)
    if evt.name =="right":
        if keyboard.is_pressed('right'):
            b[z][0] = 0
            z = z + 1
    elif evt.name =="left":
        if keyboard.is_pressed('left'):
            b[z][0] = 0
            z = z - 1
    b[z][0] = 5
    print(b)
    

b[z][0] = 5
print(b)
keyboard.on_press(onkey)
keyboard.wait()
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Thank you for your help. I am still confused though, how is the program able to run continuously without a while loop? – J R Jun 04 '21 at 23:42
  • `keyboard.wait()` does that. It basically loops forever, doing callbacks when a key is pressed. – Tim Roberts Jun 05 '21 at 00:50