Skalex
Skalex

Reputation: 146

Console grid not printing correctly

I have made a grid in python that can be printed out. It displays a series or columns and rows correctly. However, when i want to change an element in the grid, it seems to add it on to the list rather than replacing the required index. Here is the code:

empty = "X"
wall = "O"

rows = 20
columns = 40
grid = ""

def GetIndexFromPosition(x,y):
    index = 0
    for i in range(0,y):
        index += (columns)
    index += x
    print(index)
    return index


for i in range(0,rows):
    row = ""
    for i in range(0,columns):
        row += empty
    grid += """
""" + row

l = list(grid)

l[GetIndexFromPosition(0,0)] = wall

grid = "".join(l)
print(grid)

The grid should remain at a 40 by 20 screen instead of rows I have changed being 21 units long.

Upvotes: 0

Views: 101

Answers (2)

mkiever
mkiever

Reputation: 891

Your GetIndexFromPosition function does not count the line break elements you inserted in the grid string.

Corrected function accounting for line breaks:

def GetIndexFromPosition(x,y):
    index = 1
    for i in range(0,y):
        index += (columns + 1)
    index += x
    print(index)
    return index

Upvotes: 1

Axiumin_
Axiumin_

Reputation: 2145

I suspect it is adding a new element instead of replacing, and shifting everything by one index. To fix this, just remove the element, then add the new one, which is just del l[GetIndexFromPosition(0,0)]

Code:

empty = "X"
wall = "O"

rows = 20
columns = 40
grid = ""

def GetIndexFromPosition(x,y):
    index = 0
    for i in range(0,y):
        index += (columns)
    index += x
    print(index)
    return index


for i in range(0,rows):
    row = ""
    for i in range(0,columns):
        row += empty
    grid += "\n" + row

l = list(grid)

#new code beneath
del l[GetIndexFromPosition(0,0)]

l[GetIndexFromPosition(0,0)] = wall

grid = "".join(l)

print grid

Function:

To make it into a function:

def replace(list, index, new_val):
    del list[index]
    list[index] = new_val

To use it in your case:

replace(l, GetIndexFromPosition(0,0), wall)

Upvotes: 1

Related Questions