-
Notifications
You must be signed in to change notification settings - Fork 1
/
gui.py
1512 lines (1143 loc) · 55.3 KB
/
gui.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time
import pygame
import tkMessageBox
import Queue
from Tkinter import *
from ScrolledText import *
from threading import Thread, Lock
from client import lock
# Local import
from common import *
######################
# Globals for Pygame
# This sets the WIDTH and HEIGHT of each grid location
HEIGHT = 12
WIDTH = 12
# This sets the margin between each cell
MARGIN = 2
# Define some general colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
class GUI(object):
nickname_root = None
server_root = None
select_map_root = None
create_new_map_root = None
players_root = None
my_turn_to_move = False
selected_player, selected_player_id = None, None
pygame_done = True
players_on_map = {}
players_l = None # Players list
def __init__(self):
# Queue to collect and proceed the tasks from server
self.tasks = Queue.Queue()
self.client = None
self.root = None
self.frame = None
self.popup_msg = None
self.selected_server = None
self.selected_server_id = None
self.maps = {}
self.selected_map = None
self.selected_map_id = None
# self.selected_map_size = None
self.maps_list = None
self.connect_to_map_b = None
self.create_new_game_b = None
self.field_size = None
def notification_window(self):
self.root = Tk()
self.root.title("Notification Center")
frame = Frame(self.root)
frame.grid(column=0, row=0, sticky=(N, W, E, S))
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)
frame.pack(pady=10, padx=10)
notification = Label(self.root, text=">> Notification Center <<")
notification.pack()
# Notification area
self.notifications = ScrolledText(self.root, width=30, height=20, state=NORMAL)
self.notifications.pack()
while True:
# Put received task into the queue to process it
try:
task = self.tasks.get(False)
# Handle empty queue here
except Queue.Empty:
pass
else:
self.process_task(task)
self.tasks.task_done()
# Equivalent to self.mainloop().
# Because we need to check our queue with tasks, we used this construction
try:
self.root.update_idletasks()
self.root.update()
# Catch error "can't invoke "update" command:
# application has been destroyed
except TclError, KeyboardInterrupt:
return
except AttributeError:
print "Error: root can't be NoneType"
break
time.sleep(0.1)
def nickname_window(self):
self.nickname_root = Tk()
self.nickname_root.title("Enter a nickname")
self.frame = Frame(self.nickname_root)
self.frame.grid(column=0, row=0, sticky=(N, W, E, S))
self.frame.columnconfigure(0, weight=1)
self.frame.rowconfigure(0, weight=1)
self.frame.pack(pady=10, padx=10)
self.name = Label(self.nickname_root, text="Enter a nickname")
self.name.pack()
self.nickname = StringVar()
self.e = Entry(self.nickname_root, textvariable=self.nickname)
self.e.pack()
self.check_nick_button = Button(self.nickname_root, text="Choose", command=self.on_nickname_submit)
self.check_nick_button.pack()
def choose_server_window(self):
# Destroy previous window
self.destroy_previous_root()
# Update server_id to avoid conflicts in queries
self.client.selected_server_id = None
self.selected_server = None
self.server_root = Tk()
self.server_root.title("Choose a server")
self.frame = Frame(self.server_root)
self.frame.grid(column=0, row=0, sticky=(N, W, E, S))
self.frame.columnconfigure(0, weight=1)
self.frame.rowconfigure(0, weight=1)
self.frame.pack(pady=10, padx=10)
self.server = Label(self.server_root, text="Choose a server")
self.server.pack()
# Servers on-line list
self.servers_list = Listbox(self.server_root, height=12)
self.servers_list.pack()
self.servers_list.bind('<<ListboxSelect>>', self.on_server_selection)
# Join server button
self.join_server_b = Button(self.server_root, text="Connect", command=self.choose_map_window, state=DISABLED)
self.join_server_b.pack()
# Show client which servers are on-line (get from Redis)
self.servers_online = self.client.available_servers()
for server_name in self.servers_online.values():
self.servers_list.insert(END, server_name + "\n")
def choose_map_window(self):
''' In this window, player can either create a new game or join existing game '''
# Destroy previous window
self.destroy_previous_root()
self.selected_map = None
self.select_map_root = Tk()
self.select_map_root.title("Choose a map")
self.frame = Frame(self.select_map_root)
self.frame.grid(column=0, row=0, sticky=(N, W, E, S))
self.frame.columnconfigure(0, weight=1)
self.frame.rowconfigure(0, weight=1)
self.frame.pack(pady=10, padx=10)
self.game_l = Label(self.select_map_root, text="Choose a map")
self.game_l.pack()
# Available maps
self.maps_list = Listbox(self.select_map_root, height=12)
self.maps_list.pack()
self.maps_list.bind('<<ListboxSelect>>', self.on_game_selection)
# Join server button
self.connect_to_map_b = Button(self.select_map_root, text="Connect to selected map",
command=self.on_connect_to_map, state=DISABLED)
# command=self.on_connect_to_map, state=DISABLED)
self.connect_to_map_b.pack()
self.create_new_game_b = Button(self.select_map_root, text="Create new map",
command=self.create_new_map_window)
self.create_new_game_b.pack()
go_to_servers_lobby_b = Button(self.select_map_root, text="Go to servers lobby",
command=self.choose_server_window)
go_to_servers_lobby_b.pack()
# Get available servers on this server
self.client.available_maps()
def create_new_map_window(self):
''' Player decided to create new map window '''
# Destroy previous window
self.destroy_previous_root()
self.create_new_map_root = Tk()
self.create_new_map_root.title("Create new game")
self.gamelistframe = Frame(self.create_new_map_root)
self.gamelistframe.grid(column=0, row=0, sticky=(N, W, E, S))
self.gamelistframe.columnconfigure(0, weight=1)
self.gamelistframe.rowconfigure(0, weight=1)
self.gamelistframe.pack(pady=10, padx=10)
self.field = Label(self.create_new_map_root, text="Select a size of the field")
self.field.pack()
self.field_size = 20
choices = {
'S',
'M',
'L'
}
self.field_size_option = StringVar(self.create_new_map_root)
self.option = OptionMenu(self.gamelistframe, self.field_size_option, *choices)
# Set default field size to "Small"
self.field_size_option.set('S')
self.option.grid(row=1, column=1)
def change_size(*args):
global size
choice = self.field_size_option.get()
if choice == "S":
self.field_size = 20
elif choice == "M":
self.field_size = 40
elif choice == "L":
self.field_size = 50
# trace the change of var
self.field_size_option.trace('w', change_size)
label = Label(self.nickname_root, text="Enter a map name")
label.pack()
self.new_map_name = StringVar()
self.new_map_name_t = Entry(self.create_new_map_root, textvariable=self.new_map_name)
self.new_map_name_t.pack()
self.create_map_b = Button(self.create_new_map_root, text="Create map", command=self.on_create_map)
self.create_map_b.pack()
self.go_to_maps_b = Button(self.create_new_map_root, text="<< Go back to maps", command=self.choose_map_window)
self.go_to_maps_b.pack()
def players_on_map_window(self):
''' Window with current players on this map '''
self.players_root = Tk()
self.players_root.title("Players Online")
frame = Frame(self.players_root)
frame.grid(column=0, row=0, sticky=(N, W, E, S))
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)
frame.pack(pady=10, padx=10)
label = Label(self.players_root, text="Players Online")
label.pack()
# List of players on this map
self.players_l = Listbox(self.players_root, width=12, height=15)
self.players_l.pack()
self.players_l.bind('<<ListboxSelect>>', self.on_player_selection)
# "Start game" button
self.start_game_b = Button(self.players_root, state=DISABLED, text="Start game", command=self.on_start_game)
self.start_game_b.pack()
self.place_ships_b = Button(self.players_root, state=DISABLED, text="Place ships", command=self.on_place_ships)
self.place_ships_b.pack()
# Spectator mode
self.spectator_mode_b = Button(self.players_root, state=DISABLED, text="Spectator mode",
command=self.client.spectator_mode)
self.spectator_mode_b.pack(padx=5, pady=5)
# Kick player
self.kick_player_b = Button(self.players_root, state=DISABLED, text="Kick selected player",
command=self.on_kick_player)
self.kick_player_b.pack(padx=5, pady=5)
# Restart game button (can be pressed only after game finished)
self.restart_game_b = Button(self.players_root, state=DISABLED, text="Restart game",
command=self.on_restart_game)
self.restart_game_b.pack()
# Disconnect from the game
self.disconnect_b = Button(self.players_root, text="Disconnect", command=self.on_disconnect)
self.disconnect_b.pack()
# Quit
self.quit_b = Button(self.players_root, text="Quit from the game", command=self.on_quit)
self.quit_b.pack()
def run_game(self):
# Destroy previous window
self.destroy_previous_root()
# This var is responsible to make a move on the battlefield
self.my_turn_to_move = False
# Create new thread to draw field
field_t = Thread(target=self.draw_field)
field_t.setDaemon(True)
field_t.start()
self.players_on_map_window()
def draw_field(self):
'''' Here we draw our field and parse changes '''
# If the map_size is unknown, then exit
if self.field_size is None:
return
field_name = self.selected_map
self.my_ships_locations = []
self.players_on_map = dict() # key - player_id, value - dict("name":nickname, "disconnected":val)
########
# Request to get all players on the map and player's ships
with lock:
self.client.my_ships_on_map()
self.client.players_on_map()
########
# Save my presence on this map
self.players_on_map[self.client.my_player_id] = {
"name": self.client.nickname,
"disconnected": "0"
}
def get_colors():
''' Return list with 15 colors (as tuples) '''
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
BLUE = (0, 0, 255)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
MAROON = (128, 0, 0)
PURPLE = (128, 0, 128)
ORANGE = (255, 165, 0)
CHOCOLATE = (210, 105, 30)
LIGHT_GRAY = (119, 136, 153)
PINK = (255, 192, 203)
OLIVE = (128, 128, 0)
TEAL = (0, 128, 128)
DARK_GREEN = (0, 128, 0)
MIDNIGHT_BLUE = (25, 25, 112)
return [RED, YELLOW, BLUE, CYAN, MAGENTA, MAROON, PURPLE,
ORANGE, CHOCOLATE, LIGHT_GRAY, PINK, OLIVE,
TEAL, DARK_GREEN, MIDNIGHT_BLUE]
# Pre-defined dict with 15 possible colors
self.possible_colors = get_colors()
# To store colors for different ships (format key - player_id, val - color)
self.players_colors = {}
##############
# Colors for different types of shots
PAPAYA_WHIP = (255, 239, 213)
INDIAN_RED = (205, 92, 92)
LIME_GREEN = (50, 205, 50)
self.shots_colors = {
-10: INDIAN_RED, # My ship was damaged
-11: LIME_GREEN, # My hit was successful
-12: PAPAYA_WHIP, # I made shot, but I missed
}
##############
# By default color for my ships is GREEN
GREEN = (0, 255, 0)
self.players_colors[self.client.my_player_id] = GREEN
# Create a 2 dimensional array. A two dimensional
# array is simply a list of lists.
self.grid = []
# (Remember rows and column numbers start at zero.)
for row in range(self.field_size):
# Add an empty array that will hold each cell
# in this row
self.grid.append([])
for column in range(self.field_size):
self.grid[row].append(0) # Append a cell
# Initialize pygame
pygame.init()
# Set the HEIGHT and WIDTH of the screen
self.max_size = (WIDTH + MARGIN) * self.field_size + MARGIN
self.WINDOW_SIZE = [self.max_size, self.max_size]
self.screen = pygame.display.set_mode(self.WINDOW_SIZE)
# Set title of screen
pygame.display.set_caption("Battlefield: %s" % field_name)
# Loop until the user clicks the close button.
self.pygame_done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
def draw_dash(i, j):
x1 = (MARGIN + WIDTH) * i
x2 = (MARGIN + WIDTH) * i + MARGIN + WIDTH
y1 = (MARGIN + HEIGHT) * j + (MARGIN + HEIGHT) / 2
y2 = (MARGIN + HEIGHT) * j + (MARGIN + HEIGHT) / 2
# Draw dash (if someone missed)
pygame.draw.line(self.screen, BLACK, (x1, y1), (x2, y2), 3)
def draw_cross(i, j):
x1 = (MARGIN + WIDTH) * i
x2 = (MARGIN + WIDTH) * i + MARGIN + WIDTH
y1 = (MARGIN + HEIGHT) * j
y2 = (MARGIN + HEIGHT) * j + MARGIN + HEIGHT
# Draw cross (if shot was successful)
pygame.draw.line(self.screen, BLACK, (x1, y1), (x2, y2), 3)
pygame.draw.line(self.screen, BLACK, (x2, y1), (x1, y2), 3)
# -------- Main Program Loop -----------
while not self.pygame_done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
self.on_disconnect() # Flag that we are done so we exit this loop
elif event.type == pygame.MOUSEBUTTONDOWN:
# and self.my_turn_to_move
# User clicks the mouse. Get the position
pos = pygame.mouse.get_pos()
# Change the x/y screen coordinates to grid coordinates
target_column = pos[0] // (WIDTH + MARGIN)
target_row = pos[1] // (HEIGHT + MARGIN)
try:
cell = self.grid[target_row][target_column]
except IndexError:
break
# Request to register shot
# Here we need to check that player didn't shot in one cell twice
if cell not in self.players_colors.keys() \
and cell not in self.shots_colors.keys() \
and self.my_turn_to_move:
# Change state for my turn, until something will arrive from the server
with lock:
self.my_turn_to_move = False
self.client.make_shot(target_row, target_column)
print("Click ", pos, "Grid coordinates: ", target_row, target_column)
# Set the screen background
self.screen.fill(BLACK)
try:
# Draw the grid
for row in range(self.field_size):
for column in range(self.field_size):
key = self.grid[row][column]
# default color for cell is white
color = WHITE
# In this case 'key" = player_id
if key in self.players_colors.keys():
color = self.players_colors[key]
damaged_player_id = str((-1) * int(key))
# Damaged ships has also player_id but it's negative.
# Thus, we can recognize which shot we shot targeted in which player
if damaged_player_id in self.players_on_map.keys():
# If player still doesn't have color, assign new color to him
if damaged_player_id not in self.players_colors:
color = self.possible_colors.pop(0)
self.players_colors[damaged_player_id] = color
color = self.players_colors[damaged_player_id]
pygame.draw.rect(self.screen,
color,
[(MARGIN + WIDTH) * column + MARGIN,
(MARGIN + HEIGHT) * row + MARGIN,
WIDTH,
HEIGHT])
# For cases:
# - My ship was damaged
# - My hit was successful
if key in [-10, -11] or damaged_player_id in self.players_on_map.keys():
# draw_dash(column, row)
draw_cross(column, row)
# Someone made a shot, but missed
elif key == -12:
draw_dash(column, row)
except IndexError:
print "You clicked out of field"
pass
# Limit to 60 frames per second
clock.tick(60)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()
def place_ships_on_map(self):
''' Place ships on the pygame map (info about ships coords is from the server) '''
# ships_locations = [(x1, x2, y1, y2, ship_size), ...]
with lock:
try:
for x1, x2, y1, y2, ship_size in self.my_ships_locations:
x1, x2, y1, y2 = map(int, [x1, x2, y1, y2])
for i in range(x1, x2 + 1):
for j in range(y1, y2 + 1):
# Specify the color of my ships
self.grid[i][j] = self.client.my_player_id
# print x1, x2, y1, y2
except AttributeError:
pass
def go_to_spectator_mode(self, info):
''' Spectator mode allows to see all ships of all players '''
# Parse (player_id, x1, x2, y1, y2, and ship size) as tuple
with lock:
for k in range(0, len(info), 6):
# print "dsadas", info[k:k+6]
player_id = info[k]
x1, x2, y1, y2 = map(int, [info[k + 1], info[k + 2], info[k + 3], info[k + 4]])
ship_size = info[k + 5]
# If player's ships don't have color, generate a new color
if player_id not in self.players_colors:
color = self.possible_colors.pop(0)
self.players_colors[player_id] = color
# Place these ships on the map
for i in range(x1, x2 + 1):
for j in range(y1, y2 + 1):
self.grid[i][j] = player_id
def mark_cell(self, target_row, target_column, hit_successful, damaged_player_id=None):
'''
Mark ceil after shot or someone made a damage for my ship
:param target_row:
:param target_column:
:param hit_successful: (str)
:param my_ship_was_damaged: (bool)
'''
i, j = int(target_row), int(target_column)
with lock:
# Depending on whether the hit was successful or not, mark cell differently
if hit_successful == "1" and damaged_player_id is not None:
self.grid[i][j] = (-1) * int(damaged_player_id)
elif hit_successful == "1":
self.grid[i][j] = -11
# I made shot, but I missed
else:
self.grid[i][j] = -12
#################
# Handlers ============================================================================
#################
def on_nickname_submit(self):
nickname = self.nickname.get()
# Nickname received
if len(nickname):
# Block the button, until we receive the answer
self.check_nick_button.config(state=DISABLED)
# Put msg into MQ to register msg and wait until the server will register our nickname
self.client.register_nickname(nickname)
else:
tkMessageBox.showinfo("Error", "Please enter nickname")
def on_server_selection(self, event):
widget = self.servers_list
try:
index = int(widget.curselection()[0])
selected_server = widget.get(index).strip()
except:
selected_server = None
# Only 1 click to connect to particular server is allowed
if selected_server is not None and (self.selected_server != selected_server):
# Unblock "join server" button
self.join_server_b.config(state=NORMAL)
# Get selected server_id by selected server name
self.selected_server_id = self.servers_online.keys()[
self.servers_online.values().index(selected_server)]
self.client.selected_server_id = self.selected_server_id
# Save chosen server name
self.selected_server = selected_server
def on_game_selection(self, event):
self.connect_to_map_b.config(state=NORMAL)
widget = self.maps_list
try:
index = int(widget.curselection()[0])
selected_map = widget.get(index).strip()
except:
selected_map = None
# Only 1 click to connect to particular server is allowed
if selected_map is not None \
and (self.selected_map != selected_map) \
and self.connect_to_map_b.cget("state") == NORMAL:
# Save selected map name
self.selected_map = selected_map
# Get selected map_id by selected map name
for map_id, map_params in self.maps.items():
if map_params["name"] == self.selected_map:
self.selected_map_id = map_id
self.field_size = int(map_params["size"]) # list [rows, columns]
break
def on_player_selection(self, event):
widget = self.players_l # list of players
try:
index = int(widget.curselection()[0])
selected_player = widget.get(index).strip()
except:
selected_player = None
# Save selected nickname
if selected_player is not None and (self.selected_player != selected_player):
self.selected_player = selected_player
# params contains "name" and "disconnected" (0 or 1)
for player_id, params in self.players_on_map.items():
if params["name"] == selected_player:
self.selected_player_id = player_id
break
def on_connect_to_server(self):
''' When player click button "Connect to selected server" '''
if self.selected_server:
self.join_server_b.config(state=DISABLED)
# Run choose map window
self.choose_map_window()
def on_connect_to_map(self):
''' When player click button "Connect to selected map" '''
if self.selected_map:
self.connect_to_map_b.config(state=DISABLED)
self.create_new_game_b.config(state=DISABLED)
print "Waiting for response from server"
self.client.join_game()
def on_create_map(self):
# Send request to create new map
if self.new_map_name.get():
# Disable the button create new map with parameters
# until we will receive response from server
self.create_map_b.config(state=DISABLED)
self.go_to_maps_b.config(state=DISABLED)
# Save map name
self.selected_map = self.new_map_name.get()
# Request to create new game on server
self.client.create_new_game(game_name=self.new_map_name.get(), field_size=self.field_size)
else:
tkMessageBox.showinfo("Error", "Please enter map name")
def on_place_ships(self):
''' Player wants to place his ships '''
self.place_ships_b.config(state=DISABLED)
# Request to place ships
self.client.place_ships()
def on_kick_player(self):
''' Trigger client to send request with command "Kick selected palyer" '''
if self.selected_player_id:
self.kick_player_b.config(state=DISABLED)
self.client.kick_player(player_id=self.selected_player_id)
def on_start_game(self):
''' Trigger client to send request with command "Start game" '''
# Set button state to disable, until we will receive the response
self.start_game_b.config(state=DISABLED)
self.client.start_game()
def on_restart_game(self):
''' Trigger client to send request with command "Restart game" '''
# Set button state to disable, until we will receive the response
self.restart_game_b.config(state=DISABLED)
self.client.restart_game()
def on_disconnect(self):
''' Player wants to disconnect from the game. Should redirect to maps '''
self.place_ships_b.config(state=DISABLED)
self.spectator_mode_b.config(state=DISABLED)
self.kick_player_b.config(state=DISABLED)
self.start_game_b.config(state=DISABLED)
self.restart_game_b.config(state=DISABLED)
self.client.disconnect_from_game()
def on_quit(self):
''' Player wants to quit from the game. Should redirect to maps '''
self.client.quit_from_game()
#############################################
# Other methods
#############################################
def destoy_root(self):
# Destroy previous window
if self.root:
self.root.destroy()
self.root = None
self.client.resp = None
def unfreeze_connect_to_map_buttons(self):
''' Unblock buttons to create or join to the server '''
if self.connect_to_map_b and self.create_new_game_b:
self.connect_to_map_b.config(state=NORMAL)
self.create_new_game_b.config(state=NORMAL)
def add_notification(self, msg):
msg = "> " + str(msg) + "\n"
self.notifications.insert(0.0, msg)
def update_maps_list(self):
''' Update list of maps inside window "choose map '''
if self.maps_list:
# delete all previous items from previous list
self.maps_list.delete(0, END)
try:
pos = 0
for map_params in self.maps.values():
self.maps_list.insert(END, map_params["name"] + "\n")
self.mark_map_in_list(
map_name=map_params["name"], game_started=map_params["game_started"], pos_in_list=pos)
pos += 1
except TclError as e:
print "Error in update maps list"
return
def mark_map_in_list(self, map_name, game_started, pos_in_list=None):
'''
Mark map in list depending on its current status
:param map_name: (str)
:param game_started: (str) 0 - no, 1 - yes, 2 - game finished
:param pos_in_list: (int) (position of map in the list)
'''
if pos_in_list is None:
all_maps = self.maps_list.get(0, END)
pos_in_list = -1
# Find player in list by his nickname
for i, el in enumerate(all_maps):
if el.strip() == map_name:
pos_in_list = i
break
# If player was found, then mark him
if pos_in_list != -1:
if game_started == "0":
self.maps_list.itemconfig(pos_in_list, bg='green')
elif game_started == "1":
self.maps_list.itemconfig(pos_in_list, bg='red')
elif game_started == "2":
self.maps_list.itemconfig(pos_in_list, bg='gray')
def mark_player_in_list(self, player_nickname, kicked=False, disconnected=False, turn=False):
'''
Here we mark player with specific color depending on player state.
If kicked - mark red, if disconnected - mark gray.
If it's player_nickname turn, then mark his nickname in list with green color.
'''
# Player list should exist before updating
if self.players_l is None:
return
try:
all_players = self.players_l.get(0, END)
except TclError:
return
pos_in_list = -1
# Find player in list by his nickname
for i, el in enumerate(all_players):
if el.strip() == player_nickname:
pos_in_list = i
break
# If player was found, then mark him
if pos_in_list != -1:
if kicked:
self.players_l.itemconfig(pos_in_list, bg='red')
elif disconnected:
self.players_l.itemconfig(pos_in_list, bg='gray')
# If it's player's turn - mark him with green
elif turn:
self.players_l.itemconfig(pos_in_list, bg='green')
# If it's player's turn - mark him with default color (white color)
elif turn == False:
self.players_l.itemconfig(pos_in_list, bg='white')
def remove_player_from_players_list(self, player_nickname):
'''
Here we iterate over the list of current of players on the map,
to find and remove requested player
'''
all_players = self.players_l.get(0, END)
pos_in_list = -1
for i, el in enumerate(all_players):
if el.strip() == player_nickname:
pos_in_list = i
break
if pos_in_list != -1:
self.players_l.delete(pos_in_list)
def destroy_previous_root(self):
''' Destroy previous window '''
# Destroy window to enter nickname
if self.nickname_root:
self.nickname_root.destroy()
self.nickname_root = None
# Destroy window to choose server
if self.server_root:
self.server_root.destroy()
self.server_root = None
# Destroy window to choose map
if self.select_map_root:
self.select_map_root.destroy()
self.select_map_root = None
# Destroy window to create new game (with parameters)
if self.create_new_map_root:
self.create_new_map_root.destroy()
self.create_new_map_root = None
# Destroy window with players
if self.players_root:
self.players_root.destroy()
self.players_root = None
####################
# Important function to process responses from servers
####################
def process_task(self, task):
''' Handler to receive response on request reg_me '''
command, resp_code, server_id, data = parse_response(task)
print ">> Received resp(%s) on command: %s, server(%s)" \
% (error_code_to_string(resp_code), command_to_str(command), server_id)
if command == COMMAND.LIST_OF_MAPS:
maps_data = parse_data(data)
self.maps = {}
if len(maps_data) == 1 and maps_data[0] == "":
self.add_notification("No available maps online")
else:
# Decompress maps (map_id, map_name, field size) to dict[map_id] = [params]
for i in range(0, len(maps_data), 4):
map_id = maps_data[i]
map_name, field_size = maps_data[i + 1], maps_data[i + 2]
game_started = maps_data[i + 3]
self.maps[map_id] = {
"name": map_name,
"size": field_size,
"game_started": game_started
}
self.update_maps_list()
self.add_notification("List with maps updated successfully")
elif command == COMMAND.CREATE_NEW_GAME:
map_id, map_name, map_size = parse_data(data)
if resp_code == RESP.OK:
# Start the game and open new field
self.run_game()
self.maps[map_id] = {
"name": map_name,
"size": map_size
}
# Update local vars
self.field_size = int(map_size)
self.selected_map_id = map_id
# Unblock button "Place ships"
self.place_ships_b.config(state=NORMAL)
self.start_game_b.config(state=NORMAL)
else:
# Unblock the buttons
self.go_to_maps_b.config(state=NORMAL)
self.create_map_b.config(state=NORMAL)
# Update notification area
err_msg = error_code_to_string(resp_code)
self.add_notification(err_msg)
elif command == COMMAND.JOIN_EXISTING_GAME:
if resp_code == RESP.MAP_DOES_NOT_EXIST:
self.add_notification("Requested map doesn't exist")
self.unfreeze_connect_to_map_buttons()
elif resp_code == RESP.GAME_ALREADY_FINISHED:
self.add_notification("This game already finished")
self.unfreeze_connect_to_map_buttons()
# Game started, but player didn't join the game earlier
elif resp_code == RESP.GAME_ALREADY_STARTED:
self.add_notification("Game already started")
self.unfreeze_connect_to_map_buttons()
elif resp_code == RESP.MAP_FULL:
map_name = data
self.add_notification("Requested map is full")
self.unfreeze_connect_to_map_buttons()
# Mark requested map with red color