python - 获取关键输入的最佳方法是什么?
问题描述
所以我觉得无聊,决定编写一个简短的脚本,打印出一个相当大的网格供玩家绘制和填充,但在获取用户的关键输入时遇到了麻烦。我决定使用while
循环,因为我不确定如何以其他方式进行,但是使用这种方法,它的 CPU 使用率非常高,这让我想知道为什么这么简单的任务需要如此多的资源。
无论如何,这是整个脚本,因为这实际上是我第一次用 python 编写的课程,我不确定我是否在做任何正确或有效的事情。
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
解决方案
推荐阅读
- javascript - 在 JavaScript 中简化对象的最佳方法是什么(最好使用 Jquery)
- powershell - 清除 SPO 用户配置文件的自动化方式
- firebase - Firestore 集合的时间戳
- discord - 如何添加对特定用户的反应?
- ios - 在 Swift 中创建 PDF,使用 UIViewRepresentable 来查看 UIView
- flutter - 如何在 Flutter 行中溢出文本小部件列表
- python - PyTorch张量的零对角线?
- javascript - 使用计划字符串开始索引和结束索引查找 html 字符串索引
- scrapy - 在脚本中使用 scrapy 并传递参数
- javascript - 如何让函数在返回之前完成一个 for 循环