summaryrefslogtreecommitdiff
path: root/asciifarmclient/gameclient.py
blob: 8a91d754c70827c9d48c7cabce0fe446d6bbe2c1 (plain)
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
178
179
180
181
182
183
184


import os
import sys

import threading
from queue import Queue

import ratuil.inputs

from .inputhandler import InputHandler
from asciifarmclient.common import messages

class Client:
    
    def __init__(self, display, name, connection, keybindings, logFile=None):
        
        self.display = display
        self.name = name
        self.keepalive = True
        self.connection = connection
        self.logFile = logFile
        self.closeMessage = None
        
        self.inputHandler = InputHandler(self, keybindings["actions"])
        
        self.controlsString = keybindings.get("help", "")
        
        self.display.showInfo(self.controlsString)
        self.queue = Queue()
        
    
    def sendMessage(self, message):
        self.connection.send(message)
    
    def sendInput(self, inp):
        message = messages.InputMessage(inp)
        self.sendMessage(message)
    
    def sendChat(self, text):
        try:
            self.sendMessage(messages.ChatMessage(text))
        except messages.InvalidMessageError as e:
            self.log(e.description)
    
    def start(self):
        threading.Thread(target=self.listen, daemon=True).start()
        threading.Thread(target=self.getInput, daemon=True).start()
        
        self.command_loop()
    
    def listen(self):
        try:
            self.connection.listen(self.pushMessage, self.onConnectionError)
        except BaseException as error:
            self.queue.put(("error", error))
    
    def pushMessage(self, message):
        self.queue.put(("message", message))
    
    def onConnectionError(self, error):
        self.queue.put(("error", error))
    
    def getInput(self):
        try:
            while True:
                key = self.display.screen.get_key()
                self.queue.put(("input", key))
        except BaseException as error:
            self.queue.put(("error", error))
    
    def close(self, msg=None):
        self.keepalive = False
        self.closeMessage = msg
    
    
    def update(self, message):
        if message is None:
            self.close("Connection closed by server")
            return
        if isinstance(message, messages.ErrorMessage):
            error = message.errType
            if error == "nametaken":
                self.close("error: name is already taken")
                return
            if error == "invalidname":
                self.close("Invalid name error: "+ str(message.description))
                return
            self.log(message.errType + ": " + message.description)
        elif isinstance(message, messages.MessageMessage):
            self.log(message.text, message.type)
        elif isinstance(message, messages.WorldMessage):
            for msg in message.updates:
                self.handleWorldUpdate(msg)
    
    def handleWorldUpdate(self, msg):
        msgType = msg[0]
        if msgType == 'field':
            field = msg[1]
            fieldWidth = field['width']
            fieldHeight = field['height']
            self.display.resizeField((fieldWidth, fieldHeight))
            fieldCells = field['field']
            mapping = field['mapping']
            self.display.drawFieldCells(
                (
                    tuple(reversed(divmod(i, fieldWidth))),
                    mapping[spr]
                )
                for i, spr in enumerate(fieldCells))
        
        if msgType == 'changecells' and len(msg[1]):
            self.display.drawFieldCells(msg[1])
        
        if msgType == "playerpos":
            self.display.setFieldCenter(msg[1])
        
        if msgType == "health":
            health, maxHealth = msg[1]
            self.display.setHealth(health, maxHealth)
            if maxHealth is None:
                self.log("You have died. Restart the client to respawn")
        if msgType == "inventory":
            self.display.setInventory(msg[1])
        if msgType == "inv":
            self.display.setInv(msg[1])
        if msgType == "ground":
            self.display.setGround(msg[1])
        if msgType == "message":
            text, type = msg[1:3]
            self.log(text, type)
        if msgType == "messages":
            for message in msg[1]:
                type = message[0]
                text = message[1]
                arg = None
                if len(message) > 2:
                    arg = message[2]
                if type == "options":
                    self.log(arg["description"])
                    for (command, description) in arg["options"]:
                        self.log("/q {:<24}   - {}".format(command, description))
                else:
                    self.log(text, type)
        if msgType == "options":
            if msg[1] != None:
                description, options = msg[1]
                self.log(description)
                for option in options:
                    self.log(option)
        
    
    def log(self, text, type=None):
        if not isinstance(text, str):
            text = str(text)
        self.display.addMessage(text, type)
        if self.logFile:
            with(open(self.logFile, 'a')) as f:
                f.write("[{}] {}\n".format(type or "", text))
    
    
    def command_loop(self):
        while self.keepalive:
            self.display.update()
            action = self.queue.get()
            if action[0] == "message":
                self.update(action[1])
            elif action[0] == "input":
                if action[1] == "^C":
                    raise KeyboardInterrupt
                self.inputHandler.onInput(action[1])
            elif action[0] == "error":
                raise action[1]
            elif action[0] == "sigwinch":
                self.display.update_size()
            else:
                raise Exception("invalid action in queue")
    
    def onSigwinch(self, signum, frame):
        self.queue.put(("sigwinch", (signum, frame)))