Reindented all source code
This commit is contained in:
parent
17b9161813
commit
1aa7491624
@ -5,46 +5,46 @@ import enet
|
||||
|
||||
class client(object):
|
||||
|
||||
def __init__(self, host=b"localhost", port=33333, peer_count=1, channel_limit=4, incoming_bandwidth=0, outgoing_bandwidth=0):
|
||||
self.host = enet.Host(None, peer_count, channel_limit, incoming_bandwidth, outgoing_bandwidth)
|
||||
address = enet.Address(host, port)
|
||||
self.peer = self.host.connect(address, channel_limit)
|
||||
def __init__(self, host=b"localhost", port=33333, peer_count=1, channel_limit=4, incoming_bandwidth=0, outgoing_bandwidth=0):
|
||||
self.host = enet.Host(None, peer_count, channel_limit, incoming_bandwidth, outgoing_bandwidth)
|
||||
address = enet.Address(host, port)
|
||||
self.peer = self.host.connect(address, channel_limit)
|
||||
|
||||
def run(self):
|
||||
self.running = True
|
||||
while self.running:
|
||||
event = self.host.service(0)
|
||||
if event.type == enet.EVENT_TYPE_CONNECT:
|
||||
if hasattr(self, "connected"):
|
||||
self.connected(event.peer)
|
||||
elif event.type == enet.EVENT_TYPE_DISCONNECT:
|
||||
if hasattr(self, "disconnected"):
|
||||
self.disconnected(event.peer)
|
||||
elif event.type == enet.EVENT_TYPE_RECEIVE:
|
||||
data = event.packet.data
|
||||
data_dict = json.loads(data)
|
||||
self.network(event, data_dict)
|
||||
time.sleep(0.001)
|
||||
def run(self):
|
||||
self.running = True
|
||||
while self.running:
|
||||
event = self.host.service(0)
|
||||
if event.type == enet.EVENT_TYPE_CONNECT:
|
||||
if hasattr(self, "connected"):
|
||||
self.connected(event.peer)
|
||||
elif event.type == enet.EVENT_TYPE_DISCONNECT:
|
||||
if hasattr(self, "disconnected"):
|
||||
self.disconnected(event.peer)
|
||||
elif event.type == enet.EVENT_TYPE_RECEIVE:
|
||||
data = event.packet.data
|
||||
data_dict = json.loads(data)
|
||||
self.network(event, data_dict)
|
||||
time.sleep(0.001)
|
||||
|
||||
def send_data(self, channel, data, reliable=True):
|
||||
data_str = json.dumps(data, ensure_ascii=False)
|
||||
data_bytes = bytes(data_str, "utf-8")
|
||||
if reliable:
|
||||
flags = enet.PACKET_FLAG_RELIABLE
|
||||
else:
|
||||
flags = enet.PACKET_FLAG_UNSEQUENCED
|
||||
packet = enet.Packet(data_bytes, flags)
|
||||
self.peer.send(channel, packet)
|
||||
def send_data(self, channel, data, reliable=True):
|
||||
data_str = json.dumps(data, ensure_ascii=False)
|
||||
data_bytes = bytes(data_str, "utf-8")
|
||||
if reliable:
|
||||
flags = enet.PACKET_FLAG_RELIABLE
|
||||
else:
|
||||
flags = enet.PACKET_FLAG_UNSEQUENCED
|
||||
packet = enet.Packet(data_bytes, flags)
|
||||
self.peer.send(channel, packet)
|
||||
|
||||
def network(self, event, data):
|
||||
print(data)
|
||||
def network(self, event, data):
|
||||
print(data)
|
||||
|
||||
def disconnect(self):
|
||||
self.peer.disconnect()
|
||||
def disconnect(self):
|
||||
self.peer.disconnect()
|
||||
|
||||
def close(self):
|
||||
self.running = False
|
||||
def close(self):
|
||||
self.running = False
|
||||
|
||||
def __del__(self):
|
||||
del self.host
|
||||
del self.peer
|
||||
def __del__(self):
|
||||
del self.host
|
||||
del self.peer
|
||||
|
@ -4,82 +4,82 @@ import json
|
||||
|
||||
class channel(object):
|
||||
|
||||
def __init__(self, server, peer):
|
||||
self.peer = peer
|
||||
self.server = server
|
||||
def __init__(self, server, peer):
|
||||
self.peer = peer
|
||||
self.server = server
|
||||
|
||||
def send_data(self, channel, data, reliable=True):
|
||||
data_str = json.dumps(data, ensure_ascii=False)
|
||||
data_bytes = bytes(data_str, "utf-8")
|
||||
if reliable:
|
||||
flags = enet.PACKET_FLAG_RELIABLE
|
||||
else:
|
||||
flags = enet.PACKET_FLAG_UNSEQUENCED
|
||||
packet = enet.Packet(data_bytes, flags)
|
||||
self.peer.send(channel, packet)
|
||||
def send_data(self, channel, data, reliable=True):
|
||||
data_str = json.dumps(data, ensure_ascii=False)
|
||||
data_bytes = bytes(data_str, "utf-8")
|
||||
if reliable:
|
||||
flags = enet.PACKET_FLAG_RELIABLE
|
||||
else:
|
||||
flags = enet.PACKET_FLAG_UNSEQUENCED
|
||||
packet = enet.Packet(data_bytes, flags)
|
||||
self.peer.send(channel, packet)
|
||||
|
||||
def network(self, event, data):
|
||||
print(data)
|
||||
def network(self, event, data):
|
||||
print(data)
|
||||
|
||||
def disconnect(self):
|
||||
self.peer.disconnect()
|
||||
def disconnect(self):
|
||||
self.peer.disconnect()
|
||||
|
||||
class server(object):
|
||||
|
||||
def __init__(self, host=None, port=33333, peer_count=256, channel_limit=4, incoming_bandwidth=0, outgoing_bandwidth=0):
|
||||
address = enet.Address(host, port)
|
||||
self.host = enet.Host(address, peer_count, channel_limit, incoming_bandwidth, outgoing_bandwidth)
|
||||
self.peers = {}
|
||||
def __init__(self, host=None, port=33333, peer_count=256, channel_limit=4, incoming_bandwidth=0, outgoing_bandwidth=0):
|
||||
address = enet.Address(host, port)
|
||||
self.host = enet.Host(address, peer_count, channel_limit, incoming_bandwidth, outgoing_bandwidth)
|
||||
self.peers = {}
|
||||
|
||||
def run(self):
|
||||
self.running = True
|
||||
while self.running:
|
||||
event = self.host.service(0)
|
||||
if event.type == enet.EVENT_TYPE_CONNECT:
|
||||
self.connected(event.peer)
|
||||
elif event.type == enet.EVENT_TYPE_DISCONNECT:
|
||||
self.disconnected(event.peer)
|
||||
elif event.type == enet.EVENT_TYPE_RECEIVE:
|
||||
channel_object = self.get_channel(event.peer)
|
||||
if channel_object == None:
|
||||
print("Error receiving packet for invalid channel: %r" % (event.data))
|
||||
return
|
||||
data = event.packet.data
|
||||
data_dict = json.loads(data)
|
||||
channel_object.network(event, data_dict)
|
||||
time.sleep(0.0001)
|
||||
def run(self):
|
||||
self.running = True
|
||||
while self.running:
|
||||
event = self.host.service(0)
|
||||
if event.type == enet.EVENT_TYPE_CONNECT:
|
||||
self.connected(event.peer)
|
||||
elif event.type == enet.EVENT_TYPE_DISCONNECT:
|
||||
self.disconnected(event.peer)
|
||||
elif event.type == enet.EVENT_TYPE_RECEIVE:
|
||||
channel_object = self.get_channel(event.peer)
|
||||
if channel_object == None:
|
||||
print("Error receiving packet for invalid channel: %r" % (event.data))
|
||||
return
|
||||
data = event.packet.data
|
||||
data_dict = json.loads(data)
|
||||
channel_object.network(event, data_dict)
|
||||
time.sleep(0.0001)
|
||||
|
||||
def get_channel(self, peer):
|
||||
for channel in self.peers:
|
||||
if peer.incomingPeerID == channel.peer.incomingPeerID:
|
||||
return channel
|
||||
def get_channel(self, peer):
|
||||
for channel in self.peers:
|
||||
if peer.incomingPeerID == channel.peer.incomingPeerID:
|
||||
return channel
|
||||
|
||||
def connected(self, peer):
|
||||
p = channel(self, peer)
|
||||
self.peers[p] = True
|
||||
print(len(self.peers))
|
||||
p.send_data(0, dict(action="connected"), False)
|
||||
print("%s: CONNECTED" % peer.address)
|
||||
def connected(self, peer):
|
||||
p = channel(self, peer)
|
||||
self.peers[p] = True
|
||||
print(len(self.peers))
|
||||
p.send_data(0, dict(action="connected"), False)
|
||||
print("%s: CONNECTED" % peer.address)
|
||||
|
||||
def disconnected(self, peer):
|
||||
for channel in self.peers:
|
||||
if peer.incomingPeerID == channel.peer.incomingPeerID:
|
||||
del self.peers[channel]
|
||||
print("%s: DISCONNECT" % peer.address)
|
||||
break
|
||||
def disconnected(self, peer):
|
||||
for channel in self.peers:
|
||||
if peer.incomingPeerID == channel.peer.incomingPeerID:
|
||||
del self.peers[channel]
|
||||
print("%s: DISCONNECT" % peer.address)
|
||||
break
|
||||
|
||||
def send_to_all(self, channel, data, reliable=True):
|
||||
data_str = json.dumps(data, ensure_ascii=False)
|
||||
data_bytes = bytes(data_str, "utf-8")
|
||||
if reliable:
|
||||
flags = enet.PACKET_FLAG_RELIABLE
|
||||
else:
|
||||
flags = enet.PACKET_FLAG_UNSEQUENCED
|
||||
packet = enet.Packet(data_bytes, flags)
|
||||
self.host.broadcast(channel, packet)
|
||||
def send_to_all(self, channel, data, reliable=True):
|
||||
data_str = json.dumps(data, ensure_ascii=False)
|
||||
data_bytes = bytes(data_str, "utf-8")
|
||||
if reliable:
|
||||
flags = enet.PACKET_FLAG_RELIABLE
|
||||
else:
|
||||
flags = enet.PACKET_FLAG_UNSEQUENCED
|
||||
packet = enet.Packet(data_bytes, flags)
|
||||
self.host.broadcast(channel, packet)
|
||||
|
||||
def close(self):
|
||||
self.running = False
|
||||
def close(self):
|
||||
self.running = False
|
||||
|
||||
def __del__(self):
|
||||
del self.host
|
||||
def __del__(self):
|
||||
del self.host
|
||||
|
@ -7,20 +7,19 @@ from pubsub import pub
|
||||
|
||||
class client(client.client):
|
||||
|
||||
def network(self, event, data):
|
||||
""" This functions receives data from an enet server in the following protocol:
|
||||
dict(action="some_command", **kwargs)
|
||||
This function will send all data to whatever listener in the pubsub stack by using the topic "response".
|
||||
"""
|
||||
f = data.get("action")
|
||||
if f == None:
|
||||
print("Error: Invalid data in protocol. %r" % (data))
|
||||
return
|
||||
pub.sendMessage("response", data=data)
|
||||
def network(self, event, data):
|
||||
""" This functions receives data from an enet server in the following protocol:
|
||||
dict(action="some_command", **kwargs)
|
||||
This function will send all data to whatever listener in the pubsub stack by using the topic "response".
|
||||
"""
|
||||
f = data.get("action")
|
||||
if f == None:
|
||||
print("Error: Invalid data in protocol. %r" % (data))
|
||||
return
|
||||
pub.sendMessage("response", data=data)
|
||||
|
||||
def connected(self, peer):
|
||||
pub.sendMessage("ask_login")
|
||||
|
||||
def disconnected(self, peer):
|
||||
pub.sendMessage("disconnected")
|
||||
def connected(self, peer):
|
||||
pub.sendMessage("ask_login")
|
||||
|
||||
def disconnected(self, peer):
|
||||
pub.sendMessage("disconnected")
|
||||
|
@ -4,101 +4,101 @@ import wx
|
||||
|
||||
class loginDialog(wx.Dialog):
|
||||
|
||||
def __init__(self, title="Login"):
|
||||
super(loginDialog, self).__init__(parent=None, id=wx.ID_ANY)
|
||||
self.SetTitle(title)
|
||||
panel = wx.Panel(self)
|
||||
sizer = wx.BoxSizer(wx.VERTICAL)
|
||||
label1 = wx.StaticText(panel, wx.ID_ANY, "Username: ")
|
||||
self.username = wx.TextCtrl(panel, wx.ID_ANY, size=(380, -1))
|
||||
s = wx.BoxSizer(wx.HORIZONTAL)
|
||||
s.Add(label1, 0, wx.ALL, 5)
|
||||
s.Add(self.username, 0, wx.ALL, 5)
|
||||
sizer.Add(s, 0, wx.ALL, 5)
|
||||
label1 = wx.StaticText(panel, wx.ID_ANY, "Server: ")
|
||||
self.server = wx.TextCtrl(panel, wx.ID_ANY, "localhost", size=(380, -1))
|
||||
s = wx.BoxSizer(wx.HORIZONTAL)
|
||||
s.Add(label1, 0, wx.ALL, 5)
|
||||
s.Add(self.server, 0, wx.ALL, 5)
|
||||
sizer.Add(s, 0, wx.ALL, 5)
|
||||
label1 = wx.StaticText(panel, wx.ID_ANY, "Port: ")
|
||||
self.port = wx.SpinCtrl(panel, wx.ID_ANY, size=(380, -1))
|
||||
self.port.SetRange(1024, 65000)
|
||||
self.port.SetValue(33333)
|
||||
s = wx.BoxSizer(wx.HORIZONTAL)
|
||||
s.Add(label1, 0, wx.ALL, 5)
|
||||
s.Add(self.port, 0, wx.ALL, 5)
|
||||
sizer.Add(s, 0, wx.ALL, 5)
|
||||
def __init__(self, title="Login"):
|
||||
super(loginDialog, self).__init__(parent=None, id=wx.ID_ANY)
|
||||
self.SetTitle(title)
|
||||
panel = wx.Panel(self)
|
||||
sizer = wx.BoxSizer(wx.VERTICAL)
|
||||
label1 = wx.StaticText(panel, wx.ID_ANY, "Username: ")
|
||||
self.username = wx.TextCtrl(panel, wx.ID_ANY, size=(380, -1))
|
||||
s = wx.BoxSizer(wx.HORIZONTAL)
|
||||
s.Add(label1, 0, wx.ALL, 5)
|
||||
s.Add(self.username, 0, wx.ALL, 5)
|
||||
sizer.Add(s, 0, wx.ALL, 5)
|
||||
label1 = wx.StaticText(panel, wx.ID_ANY, "Server: ")
|
||||
self.server = wx.TextCtrl(panel, wx.ID_ANY, "localhost", size=(380, -1))
|
||||
s = wx.BoxSizer(wx.HORIZONTAL)
|
||||
s.Add(label1, 0, wx.ALL, 5)
|
||||
s.Add(self.server, 0, wx.ALL, 5)
|
||||
sizer.Add(s, 0, wx.ALL, 5)
|
||||
label1 = wx.StaticText(panel, wx.ID_ANY, "Port: ")
|
||||
self.port = wx.SpinCtrl(panel, wx.ID_ANY, size=(380, -1))
|
||||
self.port.SetRange(1024, 65000)
|
||||
self.port.SetValue(33333)
|
||||
s = wx.BoxSizer(wx.HORIZONTAL)
|
||||
s.Add(label1, 0, wx.ALL, 5)
|
||||
s.Add(self.port, 0, wx.ALL, 5)
|
||||
sizer.Add(s, 0, wx.ALL, 5)
|
||||
|
||||
# label2 = wx.StaticText(panel, wx.ID_ANY, "Password: ")
|
||||
# self.password = wx.TextCtrl(panel, wx.ID_ANY, size=(380, -1), style=wx.TE_PASSWORD)
|
||||
# ss = wx.BoxSizer(wx.HORIZONTAL)
|
||||
# ss.Add(label2, 0, wx.ALL, 5)
|
||||
# ss.Add(self.password, 0, wx.ALL, 5)
|
||||
# sizer.Add(ss, 0, wx.ALL, 5)
|
||||
ok = wx.Button(panel, wx.ID_OK, "Log in")
|
||||
ok.SetDefault()
|
||||
cancel = wx.Button(panel, wx.ID_CANCEL)
|
||||
self.SetEscapeId(wx.ID_CANCEL)
|
||||
bs = wx.BoxSizer(wx.HORIZONTAL)
|
||||
bs.Add(ok, 0, wx.ALL, 5)
|
||||
bs.Add(cancel, 0, wx.ALL, 5)
|
||||
sizer.Add(bs, 0, wx.ALL, 5)
|
||||
panel.SetSizer(sizer)
|
||||
self.SetClientSize(sizer.CalcMin())
|
||||
# label2 = wx.StaticText(panel, wx.ID_ANY, "Password: ")
|
||||
# self.password = wx.TextCtrl(panel, wx.ID_ANY, size=(380, -1), style=wx.TE_PASSWORD)
|
||||
# ss = wx.BoxSizer(wx.HORIZONTAL)
|
||||
# ss.Add(label2, 0, wx.ALL, 5)
|
||||
# ss.Add(self.password, 0, wx.ALL, 5)
|
||||
# sizer.Add(ss, 0, wx.ALL, 5)
|
||||
ok = wx.Button(panel, wx.ID_OK, "Log in")
|
||||
ok.SetDefault()
|
||||
cancel = wx.Button(panel, wx.ID_CANCEL)
|
||||
self.SetEscapeId(wx.ID_CANCEL)
|
||||
bs = wx.BoxSizer(wx.HORIZONTAL)
|
||||
bs.Add(ok, 0, wx.ALL, 5)
|
||||
bs.Add(cancel, 0, wx.ALL, 5)
|
||||
sizer.Add(bs, 0, wx.ALL, 5)
|
||||
panel.SetSizer(sizer)
|
||||
self.SetClientSize(sizer.CalcMin())
|
||||
|
||||
class appFrame(wx.Frame):
|
||||
menu_items = [
|
||||
("create_room", "Create new room"),
|
||||
("join_room", "Join a room")
|
||||
]
|
||||
secondary_menu_items = list()
|
||||
menu_items = [
|
||||
("create_room", "Create new room"),
|
||||
("join_room", "Join a room")
|
||||
]
|
||||
secondary_menu_items = list()
|
||||
|
||||
def __init__(self):
|
||||
super(appFrame, self).__init__(parent=None, title="Chat Window")
|
||||
self.Maximize(True)
|
||||
self.panel = wx.Panel(self)
|
||||
self.sizer = wx.BoxSizer(wx.VERTICAL)
|
||||
self.sb = self.CreateStatusBar()
|
||||
lbl = wx.StaticText(self.panel, wx.ID_ANY, "menu")
|
||||
self.list = wx.ListBox(self.panel, wx.ID_ANY)
|
||||
self.sizer.Add(lbl, 0, wx.GROW)
|
||||
self.sizer.Add(self.list, 1, wx.GROW)
|
||||
lbl = wx.StaticText(self.panel, -1, "Chat")
|
||||
self.chat = wx.TextCtrl(self.panel, -1)
|
||||
self.chat.Enable(False)
|
||||
sizerchat = wx.BoxSizer(wx.HORIZONTAL)
|
||||
sizerchat.Add(lbl, 0, wx.ALL, 5)
|
||||
sizerchat.Add(self.chat, 0, wx.ALL, 5)
|
||||
self.sizer.Add(sizerchat, 0, wx.ALL, 5)
|
||||
lbl1 = wx.StaticText(self.panel, wx.ID_ANY, "History")
|
||||
self.history = wx.TextCtrl(self.panel, wx.ID_ANY, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(500, 300))
|
||||
self.history.Enable(False)
|
||||
box = wx.BoxSizer(wx.HORIZONTAL)
|
||||
box.Add(lbl1, 0, wx.ALL, 5)
|
||||
box.Add(self.history, 0, wx.ALL, 5)
|
||||
self.sizer.Add(box, 0, wx.ALL, 5)
|
||||
self.panel.SetSizerAndFit(self.sizer)
|
||||
def __init__(self):
|
||||
super(appFrame, self).__init__(parent=None, title="Chat Window")
|
||||
self.Maximize(True)
|
||||
self.panel = wx.Panel(self)
|
||||
self.sizer = wx.BoxSizer(wx.VERTICAL)
|
||||
self.sb = self.CreateStatusBar()
|
||||
lbl = wx.StaticText(self.panel, wx.ID_ANY, "menu")
|
||||
self.list = wx.ListBox(self.panel, wx.ID_ANY)
|
||||
self.sizer.Add(lbl, 0, wx.GROW)
|
||||
self.sizer.Add(self.list, 1, wx.GROW)
|
||||
lbl = wx.StaticText(self.panel, -1, "Chat")
|
||||
self.chat = wx.TextCtrl(self.panel, -1)
|
||||
self.chat.Enable(False)
|
||||
sizerchat = wx.BoxSizer(wx.HORIZONTAL)
|
||||
sizerchat.Add(lbl, 0, wx.ALL, 5)
|
||||
sizerchat.Add(self.chat, 0, wx.ALL, 5)
|
||||
self.sizer.Add(sizerchat, 0, wx.ALL, 5)
|
||||
lbl1 = wx.StaticText(self.panel, wx.ID_ANY, "History")
|
||||
self.history = wx.TextCtrl(self.panel, wx.ID_ANY, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(500, 300))
|
||||
self.history.Enable(False)
|
||||
box = wx.BoxSizer(wx.HORIZONTAL)
|
||||
box.Add(lbl1, 0, wx.ALL, 5)
|
||||
box.Add(self.history, 0, wx.ALL, 5)
|
||||
self.sizer.Add(box, 0, wx.ALL, 5)
|
||||
self.panel.SetSizerAndFit(self.sizer)
|
||||
|
||||
def get_item(self):
|
||||
return self.list.GetSelection()
|
||||
def get_item(self):
|
||||
return self.list.GetSelection()
|
||||
|
||||
def add_message(self, message, reverse=False):
|
||||
old_line = self.history.GetNumberOfLines()
|
||||
point = self.history.GetInsertionPoint()
|
||||
if reverse:
|
||||
self.history.SetValue(message+"\n"+self.history.GetValue())
|
||||
else:
|
||||
self.history.AppendText(message+"\n")
|
||||
self.history.SetInsertionPoint(point)
|
||||
new_line = self.history.GetNumberOfLines()#.count("\n")
|
||||
return (old_line, new_line)
|
||||
def add_message(self, message, reverse=False):
|
||||
old_line = self.history.GetNumberOfLines()
|
||||
point = self.history.GetInsertionPoint()
|
||||
if reverse:
|
||||
self.history.SetValue(message+"\n"+self.history.GetValue())
|
||||
else:
|
||||
self.history.AppendText(message+"\n")
|
||||
self.history.SetInsertionPoint(point)
|
||||
new_line = self.history.GetNumberOfLines()#.count("\n")
|
||||
return (old_line, new_line)
|
||||
|
||||
def enable_app(self):
|
||||
for i in self.menu_items:
|
||||
self.list.Append(i[1])
|
||||
self.chat.Enable(True)
|
||||
self.history.Enable(True)
|
||||
def enable_app(self):
|
||||
for i in self.menu_items:
|
||||
self.list.Append(i[1])
|
||||
self.chat.Enable(True)
|
||||
self.history.Enable(True)
|
||||
|
||||
def show_connection_error(self):
|
||||
msg = wx.MessageDialog(None, "Connection error. Try again", "error", style=wx.ICON_ERROR).ShowModal()
|
||||
def show_connection_error(self):
|
||||
msg = wx.MessageDialog(None, "Connection error. Try again", "error", style=wx.ICON_ERROR).ShowModal()
|
||||
|
@ -15,111 +15,111 @@ c = None
|
||||
t = None
|
||||
|
||||
class controller(object):
|
||||
def __init__(self, window):
|
||||
super(controller, self).__init__()
|
||||
self.window = window
|
||||
self.connect_events()
|
||||
self.window.Show()
|
||||
self.next_action = ""
|
||||
def __init__(self, window):
|
||||
super(controller, self).__init__()
|
||||
self.window = window
|
||||
self.connect_events()
|
||||
self.window.Show()
|
||||
self.next_action = ""
|
||||
|
||||
def connect_events(self):
|
||||
self.window.chat.Bind(wx.EVT_CHAR_HOOK, self.on_process)
|
||||
self.window.list.Bind(wx.EVT_LISTBOX_DCLICK, self.on_process_listbox_click)
|
||||
self.window.list.Bind(wx.EVT_CHAR_HOOK, self.on_process_listbox)
|
||||
pub.subscribe(self.response, "response")
|
||||
pub.subscribe(self.ask_login, "ask_login")
|
||||
pub.subscribe(self.disconnected, "disconnected")
|
||||
def connect_events(self):
|
||||
self.window.chat.Bind(wx.EVT_CHAR_HOOK, self.on_process)
|
||||
self.window.list.Bind(wx.EVT_LISTBOX_DCLICK, self.on_process_listbox_click)
|
||||
self.window.list.Bind(wx.EVT_CHAR_HOOK, self.on_process_listbox)
|
||||
pub.subscribe(self.response, "response")
|
||||
pub.subscribe(self.ask_login, "ask_login")
|
||||
pub.subscribe(self.disconnected, "disconnected")
|
||||
|
||||
def on_process(self, event):
|
||||
key = event.GetKeyCode()
|
||||
if key == wx.WXK_RETURN:
|
||||
self.send_message()
|
||||
event.Skip()
|
||||
def on_process(self, event):
|
||||
key = event.GetKeyCode()
|
||||
if key == wx.WXK_RETURN:
|
||||
self.send_message()
|
||||
event.Skip()
|
||||
|
||||
def on_process_listbox_click(self, event):
|
||||
selected_option = self.window.menu_items[self.window.list.GetSelection()][0]
|
||||
if selected_option == "create_room":
|
||||
data = dict(action="create_room")
|
||||
c.send_data(0, data)
|
||||
elif selected_option == "join_room":
|
||||
data = dict(action="request_room_list")
|
||||
c.send_data(0, data)
|
||||
if event != None:
|
||||
event.Skip()
|
||||
def on_process_listbox_click(self, event):
|
||||
selected_option = self.window.menu_items[self.window.list.GetSelection()][0]
|
||||
if selected_option == "create_room":
|
||||
data = dict(action="create_room")
|
||||
c.send_data(0, data)
|
||||
elif selected_option == "join_room":
|
||||
data = dict(action="request_room_list")
|
||||
c.send_data(0, data)
|
||||
if event != None:
|
||||
event.Skip()
|
||||
|
||||
def on_process_listbox(self, event):
|
||||
key = event.GetKeyCode()
|
||||
if key == wx.WXK_RETURN:
|
||||
self.on_process_listbox_click(None)
|
||||
event.Skip()
|
||||
def on_process_listbox(self, event):
|
||||
key = event.GetKeyCode()
|
||||
if key == wx.WXK_RETURN:
|
||||
self.on_process_listbox_click(None)
|
||||
event.Skip()
|
||||
|
||||
def send_message(self):
|
||||
global c
|
||||
message = self.window.chat.GetValue()
|
||||
if message == "" or message == None:
|
||||
return wx.Bell()
|
||||
# Otherwise, message does exist.
|
||||
data = dict(action="send_message", message=message)
|
||||
c.send_data(0, data)
|
||||
self.window.chat.ChangeValue("")
|
||||
def send_message(self):
|
||||
global c
|
||||
message = self.window.chat.GetValue()
|
||||
if message == "" or message == None:
|
||||
return wx.Bell()
|
||||
# Otherwise, message does exist.
|
||||
data = dict(action="send_message", message=message)
|
||||
c.send_data(0, data)
|
||||
self.window.chat.ChangeValue("")
|
||||
|
||||
def response(self, data):
|
||||
command = data.get("action")
|
||||
if hasattr(self, "cmd_"+command):
|
||||
getattr(self, "cmd_"+command)(data)
|
||||
def response(self, data):
|
||||
command = data.get("action")
|
||||
if hasattr(self, "cmd_"+command):
|
||||
getattr(self, "cmd_"+command)(data)
|
||||
|
||||
def cmd_connected(self, data):
|
||||
self.window.enable_app()
|
||||
connected = data.get("nickname")
|
||||
msg = "{} has entered this platform".format(connected)
|
||||
self.window.add_message(msg)
|
||||
def cmd_connected(self, data):
|
||||
self.window.enable_app()
|
||||
connected = data.get("nickname")
|
||||
msg = "{} has entered this platform".format(connected)
|
||||
self.window.add_message(msg)
|
||||
|
||||
def cmd_message(self, data):
|
||||
msg = data.get("message")
|
||||
nickname = data.get("nickname")
|
||||
msg = "{0}: {1}".format(nickname, msg)
|
||||
output.speak(msg)
|
||||
sound.sound.play("chat.ogg")
|
||||
self.window.add_message(msg)
|
||||
def cmd_message(self, data):
|
||||
msg = data.get("message")
|
||||
nickname = data.get("nickname")
|
||||
msg = "{0}: {1}".format(nickname, msg)
|
||||
output.speak(msg)
|
||||
sound.sound.play("chat.ogg")
|
||||
self.window.add_message(msg)
|
||||
|
||||
def cmd_create_room(self, data):
|
||||
self.window.list.Clear()
|
||||
msg = "{} Has created a room.".format(data.get("nickname"))
|
||||
self.window.add_message(msg)
|
||||
output.speak(msg)
|
||||
def cmd_create_room(self, data):
|
||||
self.window.list.Clear()
|
||||
msg = "{} Has created a room.".format(data.get("nickname"))
|
||||
self.window.add_message(msg)
|
||||
output.speak(msg)
|
||||
|
||||
def cmd_room_list(self, data):
|
||||
print(data)
|
||||
def cmd_room_list(self, data):
|
||||
print(data)
|
||||
|
||||
|
||||
def ask_login(self):
|
||||
global c
|
||||
data = dict(action="login", nickname=self.username)
|
||||
c.send_data(0, data)
|
||||
def ask_login(self):
|
||||
global c
|
||||
data = dict(action="login", nickname=self.username)
|
||||
c.send_data(0, data)
|
||||
|
||||
def disconnected(self):
|
||||
self.window.show_connection_error()
|
||||
wx.GetApp().ExitMainLoop()
|
||||
def disconnected(self):
|
||||
self.window.show_connection_error()
|
||||
wx.GetApp().ExitMainLoop()
|
||||
|
||||
def setup():
|
||||
global c, t
|
||||
output.setup()
|
||||
sound.setup()
|
||||
app = wx.App()
|
||||
d = gui.loginDialog()
|
||||
f = gui.appFrame()
|
||||
mainController = controller(f)
|
||||
if d.ShowModal() != wx.ID_OK:
|
||||
return
|
||||
username = d.username.GetValue()
|
||||
server = bytes(d.server.GetValue(), "utf-8")
|
||||
port = int(d.port.GetValue())
|
||||
mainController.username = username
|
||||
d.Destroy()
|
||||
c = client.client(host=server, port=port)
|
||||
t = threading.Thread(target=c.run)
|
||||
t.start()
|
||||
app.MainLoop()
|
||||
c.close()
|
||||
global c, t
|
||||
output.setup()
|
||||
sound.setup()
|
||||
app = wx.App()
|
||||
d = gui.loginDialog()
|
||||
f = gui.appFrame()
|
||||
mainController = controller(f)
|
||||
if d.ShowModal() != wx.ID_OK:
|
||||
return
|
||||
username = d.username.GetValue()
|
||||
server = bytes(d.server.GetValue(), "utf-8")
|
||||
port = int(d.port.GetValue())
|
||||
mainController.username = username
|
||||
d.Destroy()
|
||||
c = client.client(host=server, port=port)
|
||||
t = threading.Thread(target=c.run)
|
||||
t.start()
|
||||
app.MainLoop()
|
||||
c.close()
|
||||
|
||||
setup()
|
@ -9,23 +9,23 @@ speaker = None
|
||||
retries = 0
|
||||
|
||||
def speak(text, interrupt=0):
|
||||
global speaker, retries
|
||||
if not speaker:
|
||||
setup()
|
||||
try:
|
||||
speaker.speak(text, interrupt)
|
||||
except:
|
||||
if retries < 5:
|
||||
retries = retries + 1
|
||||
speak(text)
|
||||
global speaker, retries
|
||||
if not speaker:
|
||||
setup()
|
||||
try:
|
||||
speaker.speak(text, interrupt)
|
||||
except:
|
||||
if retries < 5:
|
||||
retries = retries + 1
|
||||
speak(text)
|
||||
|
||||
def setup ():
|
||||
global speaker
|
||||
logger.debug("Initializing output subsystem.")
|
||||
try:
|
||||
speaker = outputs.auto.Auto()
|
||||
except:
|
||||
logger.exception("Output: Error during initialization.")
|
||||
global speaker
|
||||
logger.debug("Initializing output subsystem.")
|
||||
try:
|
||||
speaker = outputs.auto.Auto()
|
||||
except:
|
||||
logger.exception("Output: Error during initialization.")
|
||||
|
||||
def enable_sapi():
|
||||
speaker = outputs.sapi.SAPI5()
|
||||
speaker = outputs.sapi.SAPI5()
|
||||
|
@ -3,10 +3,10 @@ import os
|
||||
from platform_utils import paths as paths_
|
||||
|
||||
def app_path():
|
||||
return paths_.app_path()
|
||||
return paths_.app_path()
|
||||
|
||||
def locale_path():
|
||||
return os.path.join(app_path(), "locales")
|
||||
return os.path.join(app_path(), "locales")
|
||||
|
||||
def sound_path():
|
||||
return os.path.join(app_path(), "sounds")
|
||||
return os.path.join(app_path(), "sounds")
|
||||
|
@ -9,76 +9,76 @@ from sound_lib import recording, stream
|
||||
from sound_lib import output, input
|
||||
|
||||
def recode_audio(filename, quality=10):
|
||||
subprocess.call(r'"%s" --downmix -q %r "%s"' % (os.path.join(paths.app_path(), 'oggenc2.exe'), quality, filename))
|
||||
subprocess.call(r'"%s" --downmix -q %r "%s"' % (os.path.join(paths.app_path(), 'oggenc2.exe'), quality, filename))
|
||||
|
||||
def get_recording(filename):
|
||||
val = recording.WaveRecording(filename=filename)
|
||||
return val
|
||||
val = recording.WaveRecording(filename=filename)
|
||||
return val
|
||||
|
||||
class RepeatingTimer(threading.Thread):
|
||||
"""Call a function after a specified number of seconds, it will then repeat again after the specified number of seconds
|
||||
Note: If the function provided takes time to execute, this time is NOT taken from the next wait period
|
||||
"""Call a function after a specified number of seconds, it will then repeat again after the specified number of seconds
|
||||
Note: If the function provided takes time to execute, this time is NOT taken from the next wait period
|
||||
|
||||
t = RepeatingTimer(30.0, f, args=[], kwargs={})
|
||||
t.start()
|
||||
t.cancel() # stop the timer's actions
|
||||
"""
|
||||
t = RepeatingTimer(30.0, f, args=[], kwargs={})
|
||||
t.start()
|
||||
t.cancel() # stop the timer's actions
|
||||
"""
|
||||
|
||||
def __init__(self, interval, function, daemon=True, *args, **kwargs):
|
||||
threading.Thread.__init__(self)
|
||||
self.daemon = daemon
|
||||
self.interval = float(interval)
|
||||
self.function = function
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
self.finished = threading.Event()
|
||||
def __init__(self, interval, function, daemon=True, *args, **kwargs):
|
||||
threading.Thread.__init__(self)
|
||||
self.daemon = daemon
|
||||
self.interval = float(interval)
|
||||
self.function = function
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
self.finished = threading.Event()
|
||||
|
||||
def cancel(self):
|
||||
"""Stop the timer if it hasn't finished yet"""
|
||||
self.finished.set()
|
||||
def cancel(self):
|
||||
"""Stop the timer if it hasn't finished yet"""
|
||||
self.finished.set()
|
||||
|
||||
stop = cancel
|
||||
stop = cancel
|
||||
|
||||
def run(self):
|
||||
while not self.finished.is_set():
|
||||
self.finished.wait(self.interval)
|
||||
if not self.finished.is_set(): #In case someone has canceled while waiting
|
||||
try:
|
||||
self.function(*self.args, **self.kwargs)
|
||||
except:
|
||||
print("Execution failed. Function: %r args: %r and kwargs: %r" % (self.function, self.args, self.kwargs))
|
||||
def run(self):
|
||||
while not self.finished.is_set():
|
||||
self.finished.wait(self.interval)
|
||||
if not self.finished.is_set(): #In case someone has canceled while waiting
|
||||
try:
|
||||
self.function(*self.args, **self.kwargs)
|
||||
except:
|
||||
print("Execution failed. Function: %r args: %r and kwargs: %r" % (self.function, self.args, self.kwargs))
|
||||
|
||||
class soundSystem(object):
|
||||
|
||||
def __init__(self):
|
||||
""" Sound Player."""
|
||||
# Set the output and input default devices.
|
||||
try:
|
||||
self.output = output.Output()
|
||||
self.input = input.Input()
|
||||
except:
|
||||
pass
|
||||
self.files = []
|
||||
self.cleaner = RepeatingTimer(60, self.clear_list)
|
||||
self.cleaner.start()
|
||||
def __init__(self):
|
||||
""" Sound Player."""
|
||||
# Set the output and input default devices.
|
||||
try:
|
||||
self.output = output.Output()
|
||||
self.input = input.Input()
|
||||
except:
|
||||
pass
|
||||
self.files = []
|
||||
self.cleaner = RepeatingTimer(60, self.clear_list)
|
||||
self.cleaner.start()
|
||||
|
||||
def clear_list(self):
|
||||
if len(self.files) == 0: return
|
||||
try:
|
||||
for i in range(0, len(self.files)):
|
||||
if self.files[i].is_playing == False:
|
||||
self.files[i].free()
|
||||
self.files.pop(i)
|
||||
except IndexError:
|
||||
pass
|
||||
def clear_list(self):
|
||||
if len(self.files) == 0: return
|
||||
try:
|
||||
for i in range(0, len(self.files)):
|
||||
if self.files[i].is_playing == False:
|
||||
self.files[i].free()
|
||||
self.files.pop(i)
|
||||
except IndexError:
|
||||
pass
|
||||
|
||||
def play(self, sound, argument=False):
|
||||
sound_object = stream.FileStream(file="%s/%s" % (paths.sound_path(), sound))
|
||||
self.files.append(sound_object)
|
||||
sound_object.play()
|
||||
def play(self, sound, argument=False):
|
||||
sound_object = stream.FileStream(file="%s/%s" % (paths.sound_path(), sound))
|
||||
self.files.append(sound_object)
|
||||
sound_object.play()
|
||||
|
||||
sound = None
|
||||
|
||||
def setup():
|
||||
global sound
|
||||
sound = soundSystem()
|
||||
global sound
|
||||
sound = soundSystem()
|
||||
|
@ -4,78 +4,78 @@ from enetcomponents import server
|
||||
|
||||
class channel(server.channel):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(channel, self).__init__(*args, **kwargs)
|
||||
self.nickname = None
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(channel, self).__init__(*args, **kwargs)
|
||||
self.nickname = None
|
||||
|
||||
def network(self, event, data):
|
||||
f = data.get("action")
|
||||
if f == None:
|
||||
print("Error: Invalid data in protocol. %r" % (data))
|
||||
return
|
||||
if hasattr(self, "cmd_"+f) == False:
|
||||
print("Error: function cmd_{} does not exist".format(f))
|
||||
return
|
||||
getattr(self, "cmd_"+f)(data)
|
||||
def network(self, event, data):
|
||||
f = data.get("action")
|
||||
if f == None:
|
||||
print("Error: Invalid data in protocol. %r" % (data))
|
||||
return
|
||||
if hasattr(self, "cmd_"+f) == False:
|
||||
print("Error: function cmd_{} does not exist".format(f))
|
||||
return
|
||||
getattr(self, "cmd_"+f)(data)
|
||||
|
||||
def cmd_login(self, data):
|
||||
nickname = data.get("nickname")
|
||||
self.nickname = nickname
|
||||
self.room = "public"
|
||||
d = dict(action="connected", nickname=nickname)
|
||||
self.server.send_to_all(0, d)
|
||||
def cmd_login(self, data):
|
||||
nickname = data.get("nickname")
|
||||
self.nickname = nickname
|
||||
self.room = "public"
|
||||
d = dict(action="connected", nickname=nickname)
|
||||
self.server.send_to_all(0, d)
|
||||
|
||||
def cmd_send_message(self, data):
|
||||
data.update(nickname=self.nickname, action="message")
|
||||
for channel in self.server.peers:
|
||||
if channel.room == self.room:
|
||||
channel.send_data(0, data)
|
||||
def cmd_send_message(self, data):
|
||||
data.update(nickname=self.nickname, action="message")
|
||||
for channel in self.server.peers:
|
||||
if channel.room == self.room:
|
||||
channel.send_data(0, data)
|
||||
|
||||
def cmd_create_room(self, data):
|
||||
code = ''.join(random.choices(string.ascii_uppercase +string.digits, k = 10))
|
||||
existing = True
|
||||
while existing:
|
||||
existing = self.server.room_exists(code)
|
||||
if existing == True:
|
||||
code = ''.join(random.choices(string.ascii_uppercase +string.digits, k = 10))
|
||||
self.server.rooms.append(code)
|
||||
data.update(nickname=self.nickname)
|
||||
self.room = code
|
||||
self.send_data(0, data)
|
||||
def cmd_create_room(self, data):
|
||||
code = ''.join(random.choices(string.ascii_uppercase +string.digits, k = 10))
|
||||
existing = True
|
||||
while existing:
|
||||
existing = self.server.room_exists(code)
|
||||
if existing == True:
|
||||
code = ''.join(random.choices(string.ascii_uppercase +string.digits, k = 10))
|
||||
self.server.rooms.append(code)
|
||||
data.update(nickname=self.nickname)
|
||||
self.room = code
|
||||
self.send_data(0, data)
|
||||
|
||||
def cmd_request_room_list(self, data):
|
||||
rooms = dict()
|
||||
for room in self.server.rooms:
|
||||
players = self.server.get_players_in_room(room)
|
||||
rooms[room]= players
|
||||
self.send_data(0, dict(action="room_list", rooms=rooms))
|
||||
def cmd_request_room_list(self, data):
|
||||
rooms = dict()
|
||||
for room in self.server.rooms:
|
||||
players = self.server.get_players_in_room(room)
|
||||
rooms[room]= players
|
||||
self.send_data(0, dict(action="room_list", rooms=rooms))
|
||||
|
||||
class server(server.server):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(server, self).__init__(*args, **kwargs)
|
||||
self.rooms = list()
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(server, self).__init__(*args, **kwargs)
|
||||
self.rooms = list()
|
||||
|
||||
def connected(self, peer):
|
||||
p = channel(self, peer)
|
||||
self.peers[p] = True
|
||||
def connected(self, peer):
|
||||
p = channel(self, peer)
|
||||
self.peers[p] = True
|
||||
|
||||
def disconnected(self, peer):
|
||||
for channel in self.peers:
|
||||
if peer.incomingPeerID == channel.peer.incomingPeerID:
|
||||
del self.peers[channel]
|
||||
break
|
||||
def disconnected(self, peer):
|
||||
for channel in self.peers:
|
||||
if peer.incomingPeerID == channel.peer.incomingPeerID:
|
||||
del self.peers[channel]
|
||||
break
|
||||
|
||||
def room_exists(self, room_id):
|
||||
for i in self.rooms:
|
||||
if room_id == i:
|
||||
return True
|
||||
return False
|
||||
def room_exists(self, room_id):
|
||||
for i in self.rooms:
|
||||
if room_id == i:
|
||||
return True
|
||||
return False
|
||||
|
||||
def get_players_in_room(self, room_id):
|
||||
return [player.nickname for player in self.peers if player.room == room_id]
|
||||
def get_players_in_room(self, room_id):
|
||||
return [player.nickname for player in self.peers if player.room == room_id]
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Starting chat server...")
|
||||
s = server()
|
||||
s.run()
|
||||
print("Starting chat server...")
|
||||
s = server()
|
||||
s.run()
|
||||
|
Loading…
Reference in New Issue
Block a user