我正在尝试在 Python 中创建 ASCII 级别编辑器,但遇到了问题。在我的渲染器函数中,有一个 for 循环,在打印关卡行后,应该打印换行符。但是,这似乎不起作用。与 newLine
函数有关吗?
import os
class LevelEditor:
def __init__(self, level = [], currentLine = 0, line = ""):
self.level = level
self.currentLine = currentLine
self.line = line
def renderer(self):
for i in range(len(self.level)):
for j in range(len(self.level[i])):
print(self.level[i][j], end="")
print()
def clearScreen(self):
if os.name == "posix":
os.system("clear")
elif os.name == "nt":
os.system("cls")
else:
print("OS not recognized")
print()
def newLine(self):
self.line = input("\n")
self.level += [[]]
# add line to level
for i in range(len(self.line)):
self.level[self.currentLine] += self.line[i]
def loop(self):
while(True):
self.clearScreen()
self.renderer()
self.newLine()
Editor = LevelEditor()
Editor.loop()
最佳答案
尝试打印 self.level
中的内容。如果您输入了 123
、456
、789
行,您想要的大概是这样的:
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
...但是你拥有的是这样的:
[['1', '2', '3', '4', '5', '6', '7', '8', '9'], [], []]
为什么?因为你用这个添加它们:
self.level[self.currentLine] += self.line[i]
...并且您永远不会在任何地方增加 self.currentLine
。您可能想将此行添加到 newLine
的末尾:
self.currentLine += 1
<小时/>
但是,构建新行并添加它可能会更简单,甚至不需要使用 currentLine
变量。而且,就此而言,您不需要 line
属性;这只是一个局部变量。另外,您不需要循环将字符串一一转换为字符列表。因此,您可以将整个内容替换为:
line = input('\n')
self.level += list(line)
<小时/>
顺便说一句,您可能不想使用 []
作为 self.level
的默认值。如果您这样做,并使用默认参数创建两个单独的 LevelEditor 实例,它们最终将共享相同的列表。要解决此问题,请执行以下操作:
def __init__(self, level=[]):
self.level = list(level)
...或者,如果您想明确允许共享列表,但并非意外:
def __init__(self, level=None):
self.level = [] if level is None else level
…或者,真的有任何理由允许传入一个值吗?如果没有:
def __init__(self):
self.level = []
关于python - 为什么不打印这个换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49991192/