如何从text.file中读取数组? Python,诅咒

时间:2014-11-09 09:48:20

标签: python arrays 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()

1 个答案:

答案 0 :(得分:0)

您可以尝试使用python pickle module存储数据。它用于像这样的数据结构的序列化。稍后您可以再次使用pickle重新加载结构