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