我设置了一个游戏板,可以获得给定的某些值。最后,董事会将充满价值。我想把最后一块板写成txt文件。每当我尝试它时,它会打印出游戏牌,如[“”,“x”,“o”,“”,“x”,“”,“”,“x”,“”]。但我希望它在实际的板子里打印!
gameboard = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def drawBoard(gameboard):
print(" " "a" " " "b" " " "c")
print(" ""-------------")
print(("1"),("|"),gameboard[0],"|",gameboard[1], "|" ,gameboard[2], "|")
print(" ""-------------")
print(("2"),("|"),gameboard[3],"|",gameboard[4], "|" ,gameboard[5], "|")
print(" ""-------------")
print(("3"),("|"),gameboard[6],"|",gameboard[7], "|" ,gameboard[8], "|")
print(" ""-------------")
return gameboard
def writeFinal(gameboard,filename):
y= str(drawBoard(gameboard))
filename.write(y)
filename.close()
filename = open("final.txt", "w")
writeFinal(gameboard,filename):
答案 0 :(得分:0)
目前,您只是将游戏板打印到屏幕上,并将列表的默认字符串解释写入文件。您应该让drawBoard方法返回正在打印的字符串,而不是游戏板数据本身。
答案 1 :(得分:0)
你的drawBoard会返回未修改的输入参数,一个列表,而不是print语句的结果,它们会进入控制台。
也许你应该做这样的事情(未经测试):
def getBoard(gameboard):
linesep = ' -------------\n'
res = linsep.join([
' a b c',
'1 | %s | %s | %s |' % gameboard[0:2],
'2 | %s | %s | %s |' % gameboard[3:5],
'3 | %s | %s | %s |' % gameboard[6:8],
])
return '%s%s' % (res, linesep)
def drawBoard(gameboard):
print getBoard(gameboard)
def writeFinal(gameboard, filename):
open(filename, 'w').write(getBoard(gameboard))
答案 2 :(得分:0)
一种选择是将要写入的文件句柄作为参数传递给drawBoard
并打印到:
def drawBoard(gameboard, outfile=sys.stdout):
print(" " "a" " " "b" " " "c", file=outfile)
print(" ""-------------", file=outfile)
print(("1"),("|"),gameboard[0],"|",gameboard[1], "|" ,gameboard[2], "|", file=outfile)
print(" ""-------------", file=outfile)
print(("2"),("|"),gameboard[3],"|",gameboard[4], "|" ,gameboard[5], "|", file=outfile)
print(" ""-------------", file=outfile)
print(("3"),("|"),gameboard[6],"|",gameboard[7], "|" ,gameboard[8], "|", file=outfile)
print(" ""-------------", file=outfile)
with open('/tmp/foo', 'w') as output_file:
drawBoard(gameboard, output_file)
此版本默认为打印到屏幕,但可以轻松打印到任何其他可写文件对象。