我不明白为什么列表不能迭代。我们初始化了这个列表,并在其中添加了拼图的各个部分。
用户需要输入他们想要的棋盘行数和列数。每一行是一个新的拼图部分,每一列也是一个新的拼图部分。每个拼图部分都是一个由3个列表组成的矩阵。我的想法是创建一个pieces=[]列表,并将每个新生成的拼图部分附加到该列表中。
我的问题是,我无法让str()打印出整个棋盘。我想我们应该打印pieces列表中每个拼图部分的三个列表中的第一个列表,然后是第二个列表,最后是第三个列表。并且在一个新行开始。虽然我不知道如何实施它。
或者我可以先单独打印每个拼图部分,然后将这些拼图部分添加到字符串中以打印整个棋盘。所以我将不使用pieces=[]列表。我不知道哪个方法更好,也不知道如何实现它们。
我尝试查看其他问题,但是我找不到答案,我试图打印类的字符串表示:
from random import randint
from pprint import pprint
class Jigsaw:
def __init__(self, r, c):
self.pieces = []
self.row = r
self.col = c
def __str__(self):
"""
Writes the state and value to a string.
"""
s =" "
d = ""
f = ""
g = ""
for row in self.pieces:
#print(row)
for col in row:
#print(col)
d = d +" "+ format(col[0])
print(d)
for row in self.pieces:
#print(row)
for col in row:
#print(col)
f = f +" " + format(col[1])
print(f)
for row in self.pieces:
#print(row)
for col in row:
#print(col)
g = g +" "+ format(col[2])
print(g)
# return pce
# result = 'ball : %s' \
# % (pce)
#return r
def __repr__(self):
"""
Returns the string representation.
"""
return str(self)
def puzzle_board(self):
for c in range(self.row):
for d in range(self.col):
self.pieces.append(self.add_piece)
return self.pieces
def add_piece(self):
a = PieceGenerator()
b = self.a_piece(a.idn,a.top,a.left,a.right,a.bottom)
self.pieces.append(b)
return(b)
def mis(self):
self.add_piece()
# def boardShuffle(self,board):
def a_piece(self, id, top,left,right,bottom):
"""
Returns the piece values.
"""
pce = [[" ", top, " "], [left, id, right], [" ", bottom, " "]]
return(pce)
# def puzzleSolve(self,board):
class PieceGenerator:
"""
Creates new puzzle pieces with their values.
"""
idn = 0 #Global variable to keep track of all the pieces
def __init__(self):
"""
A piece have top, bottom, right, left values and puzzle piece it self
"""
self.top = randint(10,99)
self.bottom = randint(10,99)
self.right = randint(10,99)
self.left = randint(10,99)
PieceGenerator.idn += 1
print(Jigsaw(3,5).puzzle_board())
这是我得到的错误信息:
Traceback (most recent call last):
File "C:/Users/HP/PycharmProjects/untitled/.idea/jigsaw.py", line 102, in <module>
print(Jigsaw(3,5).puzzle_board())
File "C:/Users/HP/PycharmProjects/untitled/.idea/jigsaw.py", line 56, in __repr__
return str(self)
File "C:/Users/HP/PycharmProjects/untitled/.idea/jigsaw.py", line 22, in __str__
for col in row:
TypeError: 'method' object is not iterable