0

So I got bored and decided to write a short script that prints out a sizeable grid for the player to draw and stuff but had trouble getting the user's key inputs. I decided to use a while loop because I wasn't sure how to go about it any other way but with this method, it has a pretty high CPU usage and it made me wonder why such a simple task was so resource demanding.

Anyway, here is the entire script because this is actually my first ever class written in python and am not sure if I'm doing anything proper or efficient.

from keyboard import is_pressed
from subprocess import Popen


def clear():
    """Clear the terminal."""
    Popen("cls", shell=True).wait()


class Board():
    """
    Initialize sizeable grid as the play area for a player to freely move around in.
    """
    def __init__(self, rows, columns):

        self.area = [[" " for _ in range(rows)] for _ in range(columns)]

        self.xMax = columns
        self.yMax = rows
        
        self.x = int(columns / 2)
        self.y = int(rows / 2)

        self.area[self.y][self.x] = " "


    #  Replace current location with empty
    def place(self):
        self.area[self.y][self.x] = "O"
    
    #  Replace current location with player
    def change(self):
        self.area[self.y][self.x] = "_"


    #  Translate a single unit rightwards
    def right(self):
        new = self.x + 1

        if ((new > -1) and (new < self.xMax)):
            self.place()
            self.x = new
            self.change()

    #  Translate a single unit leftwards
    def left(self):
        new = self.x - 1

        if ((new > -1) and (new < self.xMax)):
            self.place()
            self.x = new
            self.change()

    #  Translate a single unit upwards
    def up(self):
        new = self.y - 1

        if ((new > -1) and (new < self.yMax)):
            self.place()
            self.y = new
            self.change()

    #  Translate a single unit downwards
    def down(self):
        new = self.y + 1

        if ((new > -1) and (new < self.yMax)):
            self.place()
            self.y = new
            self.change()


    def toString(self):
        for r in self.area:
            for i, c in enumerate(r):
                if i == len(r) - 1:
                    print(c)
                    continue

                print(c, end=" ")


#  Clear terminal beforehand
clear()

#  Custom playable grid size  |  Having different values doesn't work for some reason
obj = Board(25, 25)

#  Print default location
obj.toString()


#  Begin key detection loop  |  This honestly uses a lot of my cpu  |  The `while` loops within each for statement are to prevent the player from continuous translation but there is some wierd pause after releasing the held key
while True:

    if is_pressed("d"):
        clear()
        obj.right()
        obj.toString()

#       while is_pressed("d"):
#           continue

    elif is_pressed("a"):
        clear()
        obj.left()
        obj.toString()

#       while is_pressed("a"):
#           continue

    elif is_pressed("w"):
        clear()
        obj.up()
        obj.toString()

#       while is_pressed("w"):
#           continue

    elif is_pressed("s"):
        clear()
        obj.down()
        obj.toString()

#       while is_pressed("s"):
#           continue

    elif is_pressed("esc"):
        break
  • I don't have experience with taking input this way, but I assume that adding a `time.sleep(.1)` to the bottom of your loop will improve things. I expect that you're checking for input way more often than you need to, and that's what is killing your CPU. You'll want to play with the exact sleep time. You likely want to make the number as large as you can without it affecting the responsiveness of your program. – CryptoFool Feb 13 '21 at 03:38
  • The duplicate is a bit heavy reading, but worth it if you can slog through it. See if there is a way to attach a listener in `keyboard`. You want to respond to actual keypresses more than poll constantly as much as possible. Happy coding! Your project looks fun and you can learn a lot from it. – Mad Physicist Feb 13 '21 at 04:32

0 Answers0