I am using curses in python, and I am trying to create a game where you print out characters in the terminal window. the field is then supposed to be saved in a text file if you press 's' and if you press 'o' the saved playing field is supposed to be uploaded. I manage to store all characters in an array, but i don't know how to upload the file back/print it on the terminal window.
So the problem is that i don't know how to 'reload' the characters i have stored. The saved txt.file looks like this:
[' ', ' ', 'f', 'i', ' '....]
[' ', 'f', ' ', ' ', ' '....]
[...
[...
etc
My program.....
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()
You can try to store your data with the python pickle module . It is intended for serialization of data structures like this. Later on you can reload your structure with pickle again
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.