File: save_game.py

package info (click to toggle)
lightyears 1.4-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, jessie, jessie-kfreebsd, sid, stretch
  • size: 1,324 kB
  • ctags: 454
  • sloc: python: 3,499; makefile: 2
file content (70 lines) | stat: -rw-r--r-- 1,527 bytes parent folder | download | duplicates (4)
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
68
69
70
# 
# 20,000 Light Years Into Space
# This game is licensed under GPL v2, and copyright (C) Jack Whitham 2006-07.
# 

import pickle, extra, os


HEADER_SIZE = 100
NUM_SLOTS = 10

def Make_Save_Name(num):
    name = "save" + str(num) + ".dat"
    home = extra.Get_Home()
    if ( home == None ):
        return name
    else:
        return os.path.join(home, ".lightyears." + name)

def Load(g, num):
    name = Make_Save_Name(num)
    try:
        f = file(name, "rb")
        header = f.read( HEADER_SIZE )
        g2 = pickle.load(f)
        f.close()
    except Exception, x:
        y = ("Error restoring file: " + repr(x) + str(x))
        print y
        return (None, y)
    
    if ( g2.version != g.version ):
        return (None, "Restore error: wrong version")

    return (g2, None)
    
def Save(g, num, label):
    l = len(label)
    if ( l > HEADER_SIZE ):
        label = label[ 0:HEADER_SIZE ]
    else:
        label += ( " " * ( HEADER_SIZE - l ))

    name = Make_Save_Name(num)
    try:
        f = file(name, "wb")
        f.write(label)
        pickle.dump(g,f)
        f.close()
    except Exception, x:
        return "Error saving file: " + repr(x) + str(x)
    
    return None

def Get_Info(num):
    name = Make_Save_Name(num)
    label = ""
    try:
        f = file(name, "rb")
        label = f.read( HEADER_SIZE )
        f.close()
    except Exception, x:
        # File not found, probably.. who cares.
        return None

    if ( len(label) == 0 ):
        return None
    return label