簡體   English   中英

如何從txt.file中讀取數組? Python,詛咒

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM