[英]how to read an array from txt.file? Python, curses
我在python中使用curses,并且尝试创建一个在终端窗口中打印出字符的游戏。 如果您按“ s”,则该字段应保存在文本文件中;如果您按“ o”,则应上载已保存的比赛字段。 我设法将所有字符存储在一个数组中,但是我不知道如何将文件上传回/在终端窗口上打印。
所以问题是我不知道如何“重新加载”我存储的字符。 保存的txt.file看起来像这样:
['','','f','i','....]
[' ', 'F', ' ', ' ', ' '....]
[...
[...
等等
我的程序.....
import curses
def main(scr):
"""
Draw a border around the screen, move around using the cursor and leave a mark
of the latest pressed character on the keyboard.
Quit using 'q'.
"""
# Clear the screen of any output
scr.clear()
# Get screen dimensions
y1, x1 = scr.getmaxyx()
y1 -= 1
x1 -= 1
y0, x0 = 0, 0 #min
# Get center position
yc, xc = (y1-y0)//2, (x1-x0)//2
# Draw a border
scr.border()
# Move cursor to center
scr.move(yc, xc)
# Refresh to draw out
scr.refresh()
#Make a copy of the playing field
array = [[' ' for _ in range(x1-1)] for _ in range(y1-1)]
# Main loop
x = xc
y = yc
ch = 'j'
while True:
key = scr.getkey()
if key == 'q':
break
elif key == 'KEY_UP' and (y-1) > y0:
y -= 1
elif key == 'KEY_DOWN' and (y+1) < y1:
y += 1
elif key == 'KEY_LEFT' and (x-1) > x0:
x -= 1
elif key == 'KEY_RIGHT' and (x+1) < x1:
x += 1
elif key == 's':
text_file = open("border.txt", "w")
for char in array:
text_file.write("%s\n" % char)
text_file.close()
elif key == 'o':
scr.clear()
saved_file = open("border.txt", "r")
scr.addstr... # this is the part that don't work.
scr.refresh()
else:
if key != 'KEY_UP' and key != 'KEY_DOWN' and key != 'KEY_LEFT' and key != 'KEY_RIGHT':
ch = key
#place the key in the array
posY = y
posX = x
if y >= y0 and x >= x0 and y <= (y1) and x <= (x1):
array[int(posY-1)][int(posX-1)] = ch
# Draw out the char at cursor positino
scr.addstr(ch)
# Move cursor to new position
if y < y1 and y > y0 and x > x0 and x < x1:
scr.move(y, x)
# Redraw all items on the screen
scr.refresh()
您可以尝试使用python pickle模块存储数据。 它旨在像这样对数据结构进行序列化。 稍后,您可以再次用泡菜重新加载您的结构
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.