File size: 4,937 Bytes
15f5485
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#userInput.py
try:
    import readline
except ImportError:
    try:
        import pyreadline
    except ImportError:
        pass
import os, sys, colorama, shutil
import random
import textwrap
import pip
global gameFiles
gameFiles = 'gameFiles'

def pythonVersion():
    '''
    return the python version
    '''
    return sys.version.split(' ')[0]

def checkForPackage(packageName):
    '''
    returns true if a package is installed
    '''
    installed_packages = pip.get_installed_distributions()
    flat_installed_packages = [package.project_name for package in installed_packages]
    if packageName in flat_installed_packages:
        return True
    else:
        return False

def inputUniversal(arg = None):
    '''
    uses the appropriate form of input or raw_input
    '''
    version = (pythonVersion().split('.')[0])
    if version == '3':
        return input(arg + '/>')
    else:
        return raw_input(arg + '/>')

class Command(object):
    def __init__(self, func= None, takesArgs = False, descrip = '', hide = False):
        self.func = func
        self.takesArgs = takesArgs
        self.descrip = descrip
        self.hide = hide

    def run(self, *args, **kwargs):
        try:
            self.func(*args, **kwargs)
        except UserWarning as uw:
            print(uw)

def userInput(commands, userIn):
    '''
    take user input, conditions it, returns the command instance
    '''
    userIn = userIn.replace('to ','').replace('with ','').replace('the ','').strip().split(' ')
    #check inspect commands
    #check game commands
    try:
        command = commands[userIn[0]]
        if len(userIn) == 1 or command.takesArgs == False:
            command.run()
        else:
            command.run(userIn[1:])
    except UserWarning as uw:
        print(uw)
        return False
    except KeyError:
        return False

def parseCSVNumString(stringIn):
    if stringIn in [None, '', 'None','NULL','Null','null']:
        return None
    ret = []
    for entry in stringIn.strip().split(','):
        try:
            ret.append(int(entry))
        except ValueError:
            raise UserWarning("CSV number String passed to parseCSVNumString is not just numbers ", stringIn)
    return ret

def loadObjList(db, codeString, stage, factory):
    if codeString != None:
        codes = parseCSVNumString(codeString)
        if codes is None:
            return
        objList = []
        for code in codes:
            objList.append(factory(db, code, stage))
        return objList

def genInsult():
    lines = []
    lineCount = 0
    with open(os.path.join(gameFiles, "insults.txt"), 'r') as f:
        for line in f:
            lineCount += 1
            lines.append(line.strip())
    insultLine = random.randint(0,lineCount-1)
    return lines[insultLine]    

def printSelect(options = None, cursor = ''):
    #options are an array of strings
    uniqueOptions = set(options)
    if(len(uniqueOptions) != len(options)):
        print(uniqueOptions, options)
        raise UserWarning("None unique options")

    for i in range(len(options)):
        printToScreen("\t%d) %s"%(i, options[i]))

    while True:
        resp = inputUniversal(cursor)
        if(resp.isdigit() and int(resp) < len(uniqueOptions) and int(resp) >= 0):
            return int(resp)
        else:
            try:
                float(resp)
                printToScreen("Look at the options you {}".format(genInsult()))
            except:
                printToScreen("You gotta type a number you {}".format(genInsult()))

def printSelectGetOption(options = None, cursor = '', exitPrompt = 'Exit'):
    '''
    uses print select to return the actual option chosen, returns None if exit selected
    '''
    listOptions = [exitPrompt] + options

    selection = printSelect(options = listOptions, cursor = cursor)
    if(selection == 0):
        return None
    else:
        return options[selection - 1]

def clearScreen():
    cols, rows = getTerminalSize()
    clearLines(rows + 1)

def getTerminalSize():
    '''
    returns columns, rows
    '''
    if True:
        return shutil.get_terminal_size((80, 20))
    else:
        return 70, 40
        
        
def clearLines(lines):
    printToScreen("\033[F\033[2K", end = '')
    printToScreen("\033[F\033[K" * lines, end = '')

def printToScreen(text, color='LIGHTGREEN', backColor='BLACK', end = None):     

    width = getTerminalSize()[0]
    lines = 0
    colorama.init()
    
    try:
        print(colorama.ansi.Fore.__dict__[color], end = '')
        print(colorama.ansi.Back.__dict__[backColor], end = '')
    except KeyError:
        pass

    for par in text.split('\n'):
        wrappedLines = (textwrap.wrap(par, width=width, tabsize=4))
        lines += len(wrappedLines)
        print('\n'.join(wrappedLines), end = end)

    print(colorama.ansi.Fore.RESET, end = '')
    print(colorama.ansi.Back.RESET, end = '')
    return lines