-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathServer.py
206 lines (140 loc) · 5.77 KB
/
Server.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
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import socket
import threading
import json
from time import sleep
from logic.GameLogic import GameLogic
from logic.entities.Character import Character
from logic.entities.Player import Player
from logic.entities.Npc import Npc
from logic.entities.Fireball import Fireball
from logic.vectors import SquareVector, PixelVector
LOOP_DELAY = 1/240 #1/60
END_OF_MESSAGE = "|"
def obj_to_str(obj):
if type(obj) is Player:
return "p"
elif type(obj) is Npc:
return "n"
elif type(obj) is Fireball:
return "f"
else:
return "u" # unknown
class Server:
def __init__(self):
self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__totalConnections = 0
self.__connections = []
self.logic = GameLogic("server")
self.logic.create_map()
def start(self, address):
self.__socket.bind(address)
self.__socket.listen(5)
self.__waitForConnectionsThread = threading.Thread(
target = self.wait_for_connections)
self.__waitForConnectionsThread.start()
print("Server started...")
while True:
self.update()
sleep(LOOP_DELAY)
def wait_for_connections(self):
while True:
clientSock, clientAddress = self.__socket.accept()
clientId = len(self.__connections)
self.__connections.append(ClientHandler(clientSock, clientAddress,
clientId, self))
print("New connection at ID " + str(clientId))
self.__connections[clientId].start()
self.__totalConnections += 1
def get_connections(self):
return self.__connections
def update(self):
self.logic.update()
def broadcast(self, data, exceptionClientId=None): # TODO: exceptionId
for client in self.__connections:
client.sendJson(data)
class ClientHandler(threading.Thread):
def __init__(self, socket, address, clientId, server):
threading.Thread.__init__(self)
self.socket = socket
self.address = address
self.clientId = clientId
self.server = server
self.signal = True
self.playerId = -1
def run(self):
while self.signal:
try:
data = self.socket.recv(32)
except:
print("Client " + str(self.address) + " has disconnected")
self.signal = False
self.server.get_connections().remove(self)
break
if data != "" and data.decode("utf-8") != "":
dataSplited = data.decode("utf-8").split(END_OF_MESSAGE)
for message in dataSplited:
if message != "":
# if message != "info":
# print("ID " + str(self.clientId) + ": " +
# str(message))
self.__on_command(message)
self.__send_deleted_entities()
def __on_command(self, command):
if command == "info":
self.__send_info()
elif command == "connect":
self.__create_player()
if self.playerId == -1: # TODO: exception
return
if command == "walking" or command == "standing":
self.server.logic.get_entity(self.playerId).set_action(command)
elif command == "right" or command == "left" or \
command == "down" or command == "up":
self.server.logic.get_entity(self.playerId).set_direction(command)
elif command == "cast":
self.server.logic.get_entity(self.playerId).cast()
def sendJson(self, messageDict):
messageJson = json.dumps(messageDict)
self.socket.sendall(messageJson.encode())
def __send_info(self):
for entityId, entity in self.server.logic.get_entities().items():
entityPos = entity.get_position()
# maybe: positionPacket and changeDir/StatusPacket
messageDict = {"type": "i", # info
"e": entityId, # entity_id
"x": entityPos.x,
"y": entityPos.y,
"s": entity.get_action(), # status
"d": entity.get_direction(), # direction
"o": obj_to_str(entity)} # object type
self.sendJson(messageDict)
# self.__send_deleted_entities()
def __send_deleted_entities(self):
for entityId in self.server.logic.get_deleted_entities():
messageDict = {"type": "d", # deleted entities
"e": entityId}
self.server.broadcast(messageDict)
self.server.logic.clear_deleted_entities()
def __create_player(self):
self.playerId = self.server.logic.add_player(PixelVector(100,100))
print("Player created...")
self.__send_player_id()
self.__send_info()
for entityId, entity in self.server.logic.get_entities().items():
if issubclass(type(entity), Character):
self.__send_character(entity, entityId)
def __send_player_id(self):
messageDict = {"type": "connect",
"player_id": self.playerId}
self.sendJson(messageDict)
print("Player ID " + str(self.playerId) + " is send to client " +
str(self.clientId) + "...")
def __send_character(self, character, entityId):
messageDict = {"type": "ch", # character
"e": entityId, # entity id
"n": character.get_name() # name
} # skin, abilities
self.sendJson(messageDict)
if __name__ == '__main__':
server = Server()
server.start(("localhost", 666))