-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsave.py
68 lines (59 loc) · 1.76 KB
/
save.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import os
import re
#TODO: identificar o tipo do dado com regex
#
#Regex patterns to capture the content of the file
#These will be inside the functions that loads the save file
load_regex = '([\w\d]+)\s?=\s?([\w\d]+ ?|{[\s\S]*?}\s|\[[\s\S]*?\]\s|\([\s\S]*?\)\s)'
dict_regex = '{[\s\S]*}\s?'
list_regex = '\[[\s\S]*\]\s?'
tuple_regex = '\([\s\S]*\)\?'
def text_or_number(text):
try:
return float(text)
except ValueError:
return text.strip()
def text2python(content):
"""convert the content of the save file to python objects using regex"""
if re.match(dict_regex, content):
result = dict(re.findall('([\w\d]+) ?: ?([\w\d\{\}\[\]\(\),: ]+[\w\d\{\}\[\]\(\)])', content.strip()[1:-1]))
elif re.match(list_regex,content):
result = [text_or_number(i) for i in content.strip()[1:-1].split(',')]
elif re.match(tuple_regex,content):
result = [text_or_number(i) for i in tuple(content.strip()[1:-1].split(','))]
else:
result = text_or_number(content)
return result
def load(filename):
save_file = open(filename,'r').read()
m = re.findall(load_regex, save_file)
return dict(m)
def save(char, place, milestones, money, robots):
savedfiles = os.listdir('saves')
filenumber = len([i for i in savedfiles if i[-7:]=='.bobots'])+1
new_save_name = 'slot%0*d.bobots' % (2, filenumber)
if new_save_name not in savedfiles:
new_save_file = open(os.path.join('saves', new_save_name), 'w')
str_robots = ""
for i in robots:
str_robots+="""
"""+str(i)
save_content = """
char = %s
place = %s
milestones = %s
money = %s
%s
""" % ( char,
place,
milestones,
money,
str_robots
)
new_save_file.write(save_content)
class Saved_Game():
def __init__(self, filename):
from_file = load(filename).items()
self.bode =5
for k,v in from_file:
self.__dict__[k] = text2python(v)