Jordan Baron
Jordan Baron

Reputation: 4180

Why isn't this line break printing?

I am attempting to create an ASCII level editor in Python, but I've ran into an issue. In my renderer function there is a for loop that, after printing on line of the level, is supposed to print a line break. But, it doesn't seem to work. Is it something with the newLine function?

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()

Upvotes: 1

Views: 85

Answers (1)

abarnert
abarnert

Reputation: 365787

Try printing out what's in self.level. If you've entered lines 123, 456, 789, what you want is presumably this:

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

… but what you have is this:

[['1', '2', '3', '4', '5', '6', '7', '8', '9'], [], []]

Why? Because you add them with this:

self.level[self.currentLine] += self.line[i]

… and you never increment self.currentLine anywhere. You probably want to add this line to the end of newLine:

self.currentLine += 1

However, it might be simpler to just build the new line and add it, and not even bother with that currentLine variable. And, for that matter, you don't need a line attribute; that's just a local variable. Plus, you don't need a loop to convert a string into a list of characters one by one. So, you can replace the whole thing with:

line = input('\n')
self.level += list(line)

As a side note, you probably don't want to use [] as a default value for self.level. If you do that, and create two separate LevelEditor instances with default arguments, they're going to end up sharing the same list. To fix that, either do this:

def __init__(self, level=[]):
    self.level = list(level)

… or, if you want to allow explicitly sharing lists, but not accidentally:

def __init__(self, level=None):
    self.level = [] if level is None else level

… or, is there really any reason to allow passing in a value at all? If not:

def __init__(self):
    self.level = []

Upvotes: 3

Related Questions