我无法跟踪我得到的错误:
Traceback (most recent call last):
File "/Users/joelwilliams/Desktop/delete me", line 30, in <module>
v.writef( '======================', 10, 10 )
File "/Users/joelwilliams/Desktop/delete me", line 24, in writef
self.write( word )
File "/Users/joelwilliams/Desktop/delete me", line 15, in write
self.l[ self.y ] [ self.x : ( self.x + len( word ) ) ] = word
IndexError: list index out of range
主要代码在这里:
class board():
def __init__( self ):
self.x, self.y = 0, 0
self.l = []
self.screenWidth, self.screenHeight = 0, 0
def createBoard( self ):
listBig = [ ['`'] * self.screenWidth for _ in range( self.screenHeight ) ]
def setup( self, sw, sh ):
self.screenWidth = sw - 1
self.screenHeight = sh - 1
def write( self, word ):
self.l[ self.y ] [ self.x : ( self.x + len( word ) ) ] = word
def draw( self ):
for v in self.l:
print(''.join(v))
def writef( self, word, y, x ):
self.cursorPosX = x - 1
self.cursorPosY = y - 1
self.write( word )
v = board()
v.setup( 75, 20 )
v.createBoard()
v.writef( '======================', 10, 10 )
v.writef( '= =', 11, 10 )
v.writef( '= Pls Work. =', 12, 10 )
v.writef( '= =', 13, 10 )
v.writef( '======================', 14, 10 )
v.draw()
所需的结果是控制台显示:
======================
= =
= Pls Work. =
= =
======================
我使用this作为创建上述代码的指南 提前谢谢!
答案 0 :(得分:1)
在createBoard()
方法中:
def createBoard( self ):
listBig = [ ['`'] * self.screenWidth for _ in range( self.screenHeight ) ]
您正在创建正确长度和高度的列表,但您从未将其分配给self.l
。所以self.l
仍然是长度为0的列表。
另外,在write()
方法中:
def write( self, word ):
self.l[ self.y ] [ self.x : ( self.x + len( word ) ) ] = word
看起来你想要self.cursorPosX
(和Y)而不是self.x
和self.y
。
进行这两项更改,您的计划应该按照您的目标进行。
答案 1 :(得分:1)
您的代码
self.l == []
)bigList
;也许你打算设置self.l
(但仍然是self.l == []
)cursorPosX
和cursorPosY
;我假设您打算设置x
和y
(仍然是self.l == []
)self.l
(self.l == []
)如果你在某个地方实际初始化self.l
会有所帮助。我建议将.__init__()
,.setup()
和.createBoard()
合并为一个,与.write()
和.writef()
类似。像这样的东西::
class Board():
def __init__(self, width, height):
self.l = [['`'] * (width - 1) for _ in range(height - 1)]
def write(self, text, x, y):
dx = x + len(text)
self.l[y][x:dx] = text
def draw(self):
for row in self.l:
print(''.join(row))
请注意,无用的成员变量screenWidth
,screenHeight
,x
,y
,cursorPosX
和cursorPosY
都已被删除。
要使用此新代码:
board = Board(75, 20)
board.write('======================', 10, 10)
board.write('= =', 11, 10)
board.write('= Pls Work. =', 12, 10)
board.write('= =', 13, 10)
board.write('======================', 14, 10)
board.draw()