-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py
357 lines (277 loc) · 11.8 KB
/
test.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import asyncio
import websockets
import threading
import time, sys
import queue
import ast
from itertools import cycle
import tkinter as tk
from tkinter import font as tkfont
class Cache:
data = {}
ws = None
def remove(self, request):
if request in self.data:
del self.data[request]
async def get_or_retrieve(self, request):
if request not in self.data:
try:
print('[%s] Requesting "%s" from server.' % (self.ws.remote_address[0], request))
await self.ws.send('data.request')
await self.ws.send(request)
resp = await self.ws.recv()
except:
resp = None
if resp:
self.data[request] = resp
else:
return None
return self.data[request]
class Net:
def __init__(self, address, nickname, frame=None):
self.address = address
if ':' not in address:
self.address = '%s:6999' % self.address
self.defaultIcon = None
self.nick = nickname
self.frame = frame
self.players = []
self.avatars = []
self.format = [
[2, ],
[2, 7],
[1, 2, 3],
[1, 2, 3, 7],
[1, 6, 2, 3, 8],
[1, 2, 3, 6, 7, 8],
[0, 1, 2, 3, 4, 6, 8],
[0, 1, 2, 3, 4, 6, 7, 8],
[0, 1, 2, 3, 4, 5, 7, 8, 9],
range(10)
]
self.closed = False
self.thread = None
self.loop = asyncio.get_event_loop()
self.connect_status = 0
self.tasks = []
self.cache = Cache()
def set_frame(self, frame):
self.frame = frame
def console_output(self, message):
print('[%s]: %s' % (self.cache.ws.remote_address[0], message))
def connect(self):
self.thread = threading.Thread(target=Net._asyncio_thread, args=(self, self.loop))
self.thread.start()
def _asyncio_thread(self, loop):
async def send():
try:
async with websockets.connect(
'ws://%s' % self.address) as websocket:
self.connect_status = 1
self.cache.ws = websocket
await websocket.send(self.nick)
while not websocket.closed:
try:
cmd = await websocket.recv()
except asyncio.CancelledError:
print('Waiting thread to kill itself...')
await websocket.close(reason='bye')
sys.exit(0)
self.console_output(cmd)
if cmd == 'hs.players':
self.players = ast.literal_eval(await websocket.recv())
self.avatars = ast.literal_eval(await websocket.recv())
if cmd == 'hs.default':
dat = await websocket.recv()
self.frame.placeholder = tk.PhotoImage(data=dat)
if cmd == 'hs.ended':
self.frame.placeholders()
await self.frame.updatePlayers(self.format, self.cache, self.avatars, self.players)
if cmd == 'hs.you':
self.frame.playerid = int(await websocket.recv())
print(self.frame.playerid)
if cmd == 'player.join':
dat = ast.literal_eval(await websocket.recv())
print(dat)
self.players.append(dat[0])
self.avatars.append(dat[1])
await self.frame.updatePlayers(self.format, self.cache, self.avatars, self.players)
if cmd == 'player.leave':
dat = int(await websocket.recv())
del self.players[dat]
del self.avatars[dat]
if self.frame.playerid > dat:
self.frame.playerid -= 1
await self.frame.updatePlayers(self.format, self.cache, self.avatars, self.players)
except asyncio.CancelledError:
raise
else:
self.connect_status = -1
try:
loop.run_until_complete(send())
except KeyboardInterrupt:
pass
class MainWindow(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.geometry("1280x720")
self.resizable(0, 0)
self.container = tk.Frame(bg='#36393f')
self.container.place(relheight=1, relwidth=1, relx=0.5, rely=0.5, anchor='c')
self.container.grid_rowconfigure(0, weight=1)
self.container.grid_columnconfigure(0, weight=1)
self.net = None
self.title("Secret Utkin || Test")
self.frames = {}
for F in (MainPage, GamePage, ClosingPage):
page_name = F.__name__
frame = F(parent=self.container, controller=self)
self.frames[page_name] = frame
self.show_frame("MainPage")
def show_frame(self, page_name):
for f in self.frames.values():
f.grid_forget()
frame = self.frames[page_name]
frame.grid(row=0, column=0)
return frame
def on_closing(self):
self.show_frame('ClosingPage')
self.frames['ClosingPage'].update()
pending = asyncio.Task.all_tasks(loop=self.net.loop)
gathered = asyncio.gather(*pending, loop=self.net.loop)
try:
gathered.cancel()
self.net.loop.run_until_complete(gathered)
# we want to retrieve any exceptions to make sure that
# they don't nag us about it being un-retrieved.
gathered.exception()
except:
pass
finally:
sys.exit(0)
class GamePage(tk.Frame):
async def updatePlayers(self, f, cache, images, names):
self.placeholders()
fmt = f[len(names)-1]
for i in range(len(names)):
a = self.avatars[fmt[i]]
img = await cache.get_or_retrieve(images[i])
a.avatar = tk.PhotoImage(data=img)
a.nickname = names[i]
a.upd()
if i == self.playerid:
a.changeStatus('player')
def placeholders(self):
for ava in self.avatars:
ava.avatar = self.placeholder
ava.avaLabel.configure(image=self.placeholder)
ava.nickLabel.configure(text="Свободно")
ava.changeStatus('alive')
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.ready = False
self.controller = controller
self.playerid = 0
self.configure(bg='#36393f')
self.placeholder = tk.PhotoImage()
self.avatars = [Avatar(self, self.placeholder, "") for _ in range(10)]
self.factions = ['#0067bf', '#97612b', '#bfa200', 'black']
for i, avatar in enumerate(self.avatars):
avatar.grid(row=(i//5)+1, column=(i % 5)+1, padx=10, pady=5)
avatar.avaLabel.bind("<Button-1>", lambda _, s=avatar.nickname: print(s))
avatar.nickLabel.bind("<Button-1>", lambda _, col=cycle(self.factions), a=avatar: a.nickLabel.configure(fg=next(col)))
self.ready = True
class Avatar(tk.Frame):
def __init__(self, parent, avatar, nickname, status="alive"):
tk.Frame.__init__(self, parent)
self.avatar = avatar
self.nickname = nickname
self.status = status
self.colors = {
'alive': "#f0f0f0",
'alpaca': 'gray',
'player': 'green',
'clear': '#92b6ef'
}
self.configure(highlightthickness=5, highlightbackground="black", borderwidth=2, relief="ridge")
nickFont = tkfont.Font(family='Helvetica', size=18, weight="bold")
self.avaLabel = tk.Label(self, image=self.avatar)
self.nickLabel = tk.Label(self, text=nickname, font=nickFont, bg=self.colors[self.status])
self.avaLabel.pack(side="bottom", fill="both")
self.nickLabel.pack(fill="x")
def changeStatus(self, status, president=False, chancellor=False):
if status != self.status:
self.status = status
self.nickLabel.configure(bg=self.colors[self.status])
if president:
self.configure(highlightbackground="#10afe4")
elif chancellor:
self.configure(highlightbackground="#f5c976")
else:
self.configure(highlightbackground="black")
def upd(self):
self.avaLabel.configure(image=self.avatar)
self.nickLabel.configure(text=self.nickname)
class MainPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.bg_col = '#36393f'
self.configure(bg=self.bg_col, borderwidth=2, relief='solid')
self.e1 = tk.Entry(self, font='Helvetica 10', width=20, fg='grey')
self.e2 = tk.Entry(self, font='Helvetica 10', width=20, fg='grey')
def_text = ['test', 'test2']
self.def_e = {}
for i, e in enumerate((self.e1, self.e2)):
e.insert(0, def_text[i])
self.def_e[e] = def_text[i]
e.bind('<FocusIn>', self.entry_focus_in)
e.bind('<FocusOut>', self.entry_focus_out)
self.e1.grid(row=0, column=1, padx=5)
self.e2.grid(row=1, column=1, padx=5)
l1 = tk.Label(self, text='Никнейм', bg=self.bg_col, font='Helvetica 10 bold', fg='white')
l1.grid(row=0, column=0, sticky='e', padx=5, pady=5)
l2 = tk.Label(self, text='IP', bg=self.bg_col, font='Helvetica 10 bold', fg='white')
l2.grid(row=1, column=0, sticky='e', padx=5, pady=5)
self.b = tk.Button(self, text="Войти", font='Helvetica 12', width=20)
self.b.grid(row=2, column=0, columnspan=2, pady=10)
self.b.bind('<Button-1>', self.login)
def login(self, event):
if event.widget['state'] == 'normal':
nick = 'Anon'
if self.e1.get() != '':
nick = self.e1.get()
if self.e2.get() != '':
self.controller.net = Net(self.e2.get(), nick)
self.controller.net.connect()
while not self.controller.net.connect_status:
pass
if self.controller.net.connect_status == 1:
print('Connection successful!')
self.controller.show_frame("GamePage")
self.controller.net.frame = self.controller.frames["GamePage"]
else:
print('Connection to %s failed...' % self.e2.get())
self.b.configure(text='Упс...')
self.controller.net.connect_status = 0
def entry_focus_in(self, event):
if event.widget.get() == self.def_e[event.widget]:
event.widget.configure(fg='black')
event.widget.delete(0, 'end')
event.widget.insert(0, '')
def entry_focus_out(self, event):
if event.widget.get() == '':
event.widget.insert(0, self.def_e[event.widget])
event.widget.configure(fg='grey')
class ClosingPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(bg='#36393f')
label = tk.Label(self, text='Подождите, закрывается...', font='Helvetica 24', bg='black', fg='white')
label.pack()
if __name__ == "__main__":
app = MainWindow()
flags = []
app.protocol("WM_DELETE_WINDOW", app.on_closing)
app.mainloop()