-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathWarships2.py
1539 lines (1372 loc) · 64.9 KB
/
Warships2.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#==============================================================================
# Title: Warships 2
# Author: Ryan J. Slater
# Date: 5/31/2018
#==============================================================================
import platform
import os
os.chdir(os.path.dirname(os.path.realpath(__file__)))
operatingSystem = platform.system()
import Warships2Account as Account
import pygame
import numpy as np
import pygame.locals as pl
import time
class colors():
'''
Saves constant tuple (RED, GREEN, BLUE) values for colors
'''
BLACK = (0,0,0)
LIGHTGRAY = (100, 100, 100)
DARKGRAY = (50, 50, 50)
WHITE = (255,255,255)
RED = (200,0,0)
GREEN = (0,200,0)
BLUE = (0, 0, 200)
ORANGE = (255, 100, 0)
PURPLE = (102, 0, 51)
PINK = (255, 0, 102)
BROWN = (139, 69, 19)
BRIGHTRED = (255,0,0)
BRIGHTGREEN = (0,255,0)
BRIGHTBLUE = (0, 0, 255)
SKY = (135, 206, 250)
def text_objects(text, font, color=colors.BLACK):
'''
Takes text, font, and optional color and returns textSurface and textSurface.get_rect(), required for displaying text in pygame
Usage: textSurf, textRect = text_objects(text, font)
Parameters
----------
text : String
The text to be displayed
font : pygame.font.SysFont
text = pygame.font.SysFont('FONTNAME', FONTSIZE), FONTNAME : String, FONTSIZE : int
color : colors.COLOR (OPTIONAL)
Get a color from the colors class. Default = colors.BLACK (0, 0, 0)
Returns
----------
textSurface : pygame-rendered text
font.render(text, True, color)
rect : textSurface.get_rect()
Usage
----------
textSurf, textRect = text_objects(text, font)
textRect.center = (x, y)
gameDisplay.blit(textSurf, textRect)
'''
textSurface = font.render(text, True, color)
return textSurface, textSurface.get_rect()
def button(msg, x, y, w, h, ic, ac, display, action=None, textSize = 30, textColor=colors.BLACK):
'''
Displays a colored button with text
Parameters
----------
msg : String
The text to be displayed
x : int
x-coordinate in pixels of the top left corner of the button
y : int
y-coordinate in pixels of the top left corner of the button
w : int
Width of the button in pixels
h : int
Height of the button in pixels
ic : colors.COLOR
Inactive color of the button
ac : colors.COLOR
Active color of the button
display : pygame.Surface
Pygame display for the button to be displayed on
action : function
Action to be performed by pressing the button
Default = None
textSize : int
Font size
Default = 30
'''
pygame.font.init()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(display, ac, (x, y, w, h))
text = pygame.font.SysFont('couriernew', textSize)
textSurf, textRect = text_objects(msg, text, textColor)
textRect.center = ((x+(w/2)), (y+(h/2)))
display.blit(textSurf, textRect)
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(display, ic, (x, y, w, h))
text = pygame.font.SysFont('couriernew', textSize)
textSurf, textRect = text_objects(msg, text, textColor)
textRect.center = ((x+(w/2)), (y+(h/2)))
display.blit(textSurf, textRect)
def buttonImage(x, y, w, h, ic, ac, display, action=None):
'''
Displays a colored button with text
Parameters
----------
x : int
x-coordinate in pixels of the top left corner of the button
y : int
y-coordinate in pixels of the top left corner of the button
w : int
Width of the button in pixels
h : int
Height of the button in pixels
ic : pygame.image.load(FILEPATH)
Inactive image of the button
ac : pygame.image.load(FILEPATH)
Active image of the button
display : pygame.Surface
Pygame display for the button to be displayed on
action : function
Action to be performed by pressing the button
Default = None
'''
pygame.font.init()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
display.blit(ac, (x, y))
if click[0] == 1 and action != None:
action()
else:
display.blit(ic, (x, y))
class TextInput:
"""
This class lets the user input a piece of text, e.g. a name or a message.
This class let's the user input a short, one-lines piece of text at a blinking cursor
that can be moved using the arrow-keys. Delete, home and end work as well.
"""
def __init__(self, font_family = "",
font_size = 35,
antialias=True,
text_color=(0, 0, 0),
cursor_color=(0, 0, 1),
repeat_keys_initial_ms=400,
repeat_keys_interval_ms=35):
"""
Args:
font_family: Name or path of the font that should be used. Default is pygame-font
font_size: Size of the font in pixels
antialias: (bool) Determines if antialias is used on fonts or not
text_color: Color of the text
repeat_keys_initial_ms: ms until the keydowns get repeated when a key is not released
repeat_keys_interval_ms: ms between to keydown-repeats if key is not released
"""
# Text related vars:
self.antialias = antialias
self.text_color = text_color
self.font_size = font_size
self.input_string = "" # Inputted text
if not os.path.isfile(font_family): font_family = pygame.font.match_font(font_family)
self.font_object = pygame.font.SysFont('couriernew', font_size)
# Text-surface will be created during the first update call:
self.surface = pygame.Surface((1, 1))
self.surface.set_alpha(0)
# Vars to make keydowns repeat after user pressed a key for some time:
self.keyrepeat_counters = {} # {event.key: (counter_int, event.unicode)} (look for "***")
self.keyrepeat_intial_interval_ms = repeat_keys_initial_ms
self.keyrepeat_interval_ms = repeat_keys_interval_ms
# Things cursor:
self.cursor_surface = pygame.Surface((int(self.font_size/20+1), self.font_size))
self.cursor_surface.fill(cursor_color)
self.cursor_position = 0 # Inside text
self.cursor_visible = True # Switches every self.cursor_switch_ms ms
self.cursor_switch_ms = 500 # /|\
self.cursor_ms_counter = 0
self.clock = pygame.time.Clock()
def update(self, events):
for event in events:
if event.type == pygame.KEYDOWN:
self.cursor_visible = True # So the user sees where he writes
# If none exist, create counter for that key:
if not event.key in self.keyrepeat_counters:
self.keyrepeat_counters[event.key] = [0, event.unicode]
if event.key == pl.K_BACKSPACE:
self.input_string = self.input_string[:max(self.cursor_position - 1, 0)] + \
self.input_string[self.cursor_position:]
# Subtract one from cursor_pos, but do not go below zero:
self.cursor_position = max(self.cursor_position - 1, 0)
elif event.key == pl.K_DELETE:
self.input_string = self.input_string[:self.cursor_position] + \
self.input_string[self.cursor_position + 1:]
elif event.key == pl.K_RETURN:
return True
elif event.key == pl.K_RIGHT:
# Add one to cursor_pos, but do not exceed len(input_string)
self.cursor_position = min(self.cursor_position + 1, len(self.input_string))
elif event.key == pl.K_LEFT:
# Subtract one from cursor_pos, but do not go below zero:
self.cursor_position = max(self.cursor_position - 1, 0)
elif event.key == pl.K_END:
self.cursor_position = len(self.input_string)
elif event.key == pl.K_HOME:
self.cursor_position = 0
else:
# If no special key is pressed, add unicode of key to input_string
self.input_string = self.input_string[:self.cursor_position] + \
event.unicode + \
self.input_string[self.cursor_position:]
self.cursor_position += len(event.unicode) # Some are empty, e.g. K_UP
elif event.type == pl.KEYUP:
# *** Because KEYUP doesn't include event.unicode, this dict is stored in such a weird way
if event.key in self.keyrepeat_counters:
del self.keyrepeat_counters[event.key]
# Update key counters:
for key in self.keyrepeat_counters :
self.keyrepeat_counters[key][0] += self.clock.get_time() # Update clock
# Generate new key events if enough time has passed:
if self.keyrepeat_counters[key][0] >= self.keyrepeat_intial_interval_ms:
self.keyrepeat_counters[key][0] = self.keyrepeat_intial_interval_ms - \
self.keyrepeat_interval_ms
event_key, event_unicode = key, self.keyrepeat_counters[key][1]
pygame.event.post(pygame.event.Event(pl.KEYDOWN, key=event_key, unicode=event_unicode))
# Rerender text surface:
self.surface = self.font_object.render(self.input_string, self.antialias, self.text_color)
# Update self.cursor_visible
self.cursor_ms_counter += self.clock.get_time()
if self.cursor_ms_counter >= self.cursor_switch_ms:
self.cursor_ms_counter %= self.cursor_switch_ms
self.cursor_visible = not self.cursor_visible
if self.cursor_visible:
cursor_y_pos = self.font_object.size(self.input_string[:self.cursor_position])[0]
# Without this, the cursor is invisible when self.cursor_position > 0:
if self.cursor_position > 0:
cursor_y_pos -= self.cursor_surface.get_width()
self.surface.blit(self.cursor_surface, (cursor_y_pos, 0))
self.clock.tick()
return False
def get_surface(self):
return self.surface
def get_text(self):
return self.input_string
def get_cursor_position(self):
return self.cursor_position
def set_text_color(self, color):
self.text_color = color
def set_cursor_color(self, color):
self.cursor_surface.fill(color)
def clear_text(self):
self.input_string=""
def firstRunSetup():
'''
If first launch, create .account directory and prompt the user to create an account
Returns
----------
firstTime : boolean
True if initial setup was performed AND first account was created
'''
files = [f for f in os.listdir(os.getcwd())]
if '.accounts' not in files:
os.mkdir('.accounts')
if createNewAccount(True):
return True
return False
def getAllAccountNames():
print('Getting all account names')
accts = []
if operatingSystem == 'Windows':
print('Windows')
for i in os.listdir('.accounts\\'):
accts.append(i)
i = 0
stop = len(accts)
while i < stop:
if accts[i][len(accounts[i])-4:] != '.txt':
accts.pop(i)
i -= 1
stop = len(accts)
else:
accts[i] = accts[i][:len(accts[i])-4]
i += 1
return accts
else:
for i in os.listdir('.accounts/'):
accts.append(i)
i = 0
stop = len(accts)
while i < stop:
if accts[i][len(accts[i])-4:] == '.txt':
accts.pop(i)
i -= 1
stop = len(accts)
i += 1
return accts
def getAllAccounts():
print('Getting all accounts')
accts = []
accountNames = getAllAccountNames()
for i in accountNames:
a = Account.account()
if operatingSystem == 'Windows':
a.updateFromFile(i)
else:
a.updateFromFile(i)
accts.append(a)
return accts
def createNewAccount(isFirstTime=False):
'''
Creates account creation window
'''
global creatingUsername
global displayWidth
global displayHeight
global gameDisplay
global accounts
print('New account creation menu')
pygame.init()
displayWidth = 1000
displayHeight = 600
creatingAccountWindow = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('Create New Account')
textinput = TextInput()
printErrorMessage = False
breakWhileLoop = False
createAccount = False
accountNames = getAllAccountNames()
while True:
creatingAccountWindow.fill(colors.WHITE)
text = pygame.font.SysFont('couriernew', 35)
smallText = pygame.font.SysFont('couriernew', 15)
TextSurf, TextRect = text_objects('Create account username:', text, colors.BLACK)
TextRect.center = (displayWidth/2, displayHeight/2)
creatingAccountWindow.blit(TextSurf, TextRect)
if printErrorMessage:
TextSurf, TextRect = text_objects('Username cannot contain spaces', text, colors.RED)
TextRect.center = (displayWidth/2, displayHeight/2+85)
creatingAccountWindow.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects('or be longer than 20 characters', text, colors.RED)
TextRect.center = (displayWidth/2, displayHeight/2+110)
creatingAccountWindow.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects('or reuse an existing username', text, colors.RED)
TextRect.center = (displayWidth/2, displayHeight/2+135)
creatingAccountWindow.blit(TextSurf, TextRect)
if not isFirstTime:
button('Cancel', 0, 575, 75, 25, colors.RED, colors.BRIGHTRED, gameDisplay, mainMenu, 15)
if len(accounts) > 0:
TextSurf, TextRect = text_objects('ACCOUNTS:', smallText)
TextRect.center = (displayWidth/10, 12)
creatingAccountWindow.blit(TextSurf, TextRect)
for i in range(len(accounts)):
TextSurf, TextRect = text_objects(accounts[i].username, smallText)
TextRect.center = (displayWidth/10, 24+12*i)
creatingAccountWindow.blit(TextSurf, TextRect)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
# In case window is closed
if isFirstTime:
os.rmdir('.accounts')
pygame.quit()
breakWhileLoop = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
creatingUsername = textinput.get_text()
if len(creatingUsername) <= 20 and ' ' not in creatingUsername and creatingUsername not in accountNames:
createAccount = True
pygame.quit()
breakWhileLoop = True
else:
printErrorMessage = True
if breakWhileLoop:
break
textinput.update(events)
creatingAccountWindow.blit(textinput.get_surface(), (displayWidth/3, displayHeight/2+35))
pygame.display.update()
clock.tick(60)
if createAccount:
print('Creating account file: ' + creatingUsername)
if operatingSystem == 'Windows':
file = open('.accounts\\' + creatingUsername + '.txt', 'w+')
else:
file = open('.accounts/' + creatingUsername, 'w+')
file.write(creatingUsername)
for i in range(204):
file.write('\n' + str(0))
file.close()
accounts = getAllAccounts()
for i in accounts:
i.updateFromFile(i.username)
if isFirstTime or loggedIn == None:
if i.username == creatingUsername:
login(i)
pygame.display.set_caption('Warships 2')
displayWidth = 1000
displayHeight = 600
gameDisplay = pygame.display.set_mode((displayWidth, displayHeight))
def login(account=None, playAfterLogin=False):
'''
Logs in an account object by setting loggedIn = account
Parameters
----------
account: Warships2Account.account
Account to be logged in
'''
global loggedIn
print('Login menu')
if account != None and loggedIn == None:
loggedIn = account
print('\nSuccessfully logged in:\n')
print(account.username)
print('\n\n')
return 0
if len(accounts) == 0:
mainMenu()
# ask for name of account and list accounts
pygame.display.set_caption('Login')
displayWidth = 1000
displayHeight = 600
loginWindow = pygame.display.set_mode((displayWidth, displayHeight))
printErrorMessage = False
breakWhileLoop = False
textinput = TextInput()
print('Logged in:', end=' ')
if loggedIn != None:
print(loggedIn.username)
else:
print('None')
while True:
loginWindow.fill(colors.WHITE)
largeText = pygame.font.SysFont('couriernew', 35)
smallText = pygame.font.SysFont('couriernew', 15)
TextSurf, TextRect = text_objects('Enter username to log in:', largeText)
TextRect.center = (displayWidth/2, displayHeight/2)
loginWindow.blit(TextSurf, TextRect)
if loggedIn != None:
TextSurf, TextRect = text_objects('Logged in: ' + loggedIn.username, smallText)
TextRect.center = (displayWidth/2, 12)
loginWindow.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects('ACCOUNTS:', smallText)
TextRect.center = (displayWidth/10, 12)
loginWindow.blit(TextSurf, TextRect)
for i in range(len(accounts)):
TextSurf, TextRect = text_objects(accounts[i].username, smallText)
TextRect.center = (displayWidth/10, 24+12*i)
loginWindow.blit(TextSurf, TextRect)
if printErrorMessage:
TextSurf, TextRect = text_objects('Ensure you are not already logged in', largeText, colors.RED)
TextRect.center = (displayWidth/2, displayHeight/2+85)
loginWindow.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects('and that the spelling is correct', largeText, colors.RED)
TextRect.center = (displayWidth/2, displayHeight/2+115)
loginWindow.blit(TextSurf, TextRect)
button('Cancel', 0, 575, 75, 25, colors.RED, colors.BRIGHTRED, gameDisplay, mainMenu, 15)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
breakWhileLoop = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
if checkValidUsernameLogin(textinput.get_text()):
account = textinput.get_text()
breakWhileLoop = True
else:
printErrorMessage = True
if breakWhileLoop:
break
textinput.update(events)
loginWindow.blit(textinput.get_surface(), (displayWidth/3, displayHeight/2+35))
pygame.display.update()
clock.tick(60)
for i in accounts:
if i.username == account:
account = i
break
loggedIn = account
print('Successfully logged in ' + account.username)
if playAfterLogin:
play()
else:
mainMenu()
def checkValidUsernameLogin(username):
global loggedIn
print('Checking login username validity')
if username in getAllAccountNames():
if loggedIn == None or username != loggedIn.username:
return True
return False
return False
def getSecondPlayer():
global secondPlayer
global loggedIn
global gameDisplay
global accounts
print('Get second player menu')
pygame.font.init()
printErrorMessage = False
breakWhileLoop = False
textinput = TextInput()
account = None
while True:
gameDisplay.fill(colors.WHITE)
largeText = pygame.font.SysFont('couriernew', 35)
smallText = pygame.font.SysFont('couriernew', 15)
TextSurf, TextRect = text_objects('Enter the second player\'s username:', largeText)
TextRect.center = (displayWidth/2, displayHeight/2)
gameDisplay.blit(TextSurf, TextRect)
if loggedIn != None:
TextSurf, TextRect = text_objects('Logged in: ' + loggedIn.username, smallText)
TextRect.center = (displayWidth/2, 12)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects('ACCOUNTS:', smallText)
TextRect.center = (displayWidth/10, 12)
gameDisplay.blit(TextSurf, TextRect)
for i in range(len(accounts)):
TextSurf, TextRect = text_objects(accounts[i].username, smallText)
TextRect.center = (displayWidth/10, 24+12*i)
gameDisplay.blit(TextSurf, TextRect)
if printErrorMessage:
TextSurf, TextRect = text_objects('Ensure you are not already logged in', largeText, colors.RED)
TextRect.center = (displayWidth/2, displayHeight/2+85)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects('and that the spelling is correct', largeText, colors.RED)
TextRect.center = (displayWidth/2, displayHeight/2+115)
gameDisplay.blit(TextSurf, TextRect)
button('Cancel', 0, 575, 75, 25, colors.RED, colors.BRIGHTRED, gameDisplay, mainMenu, 15)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
breakWhileLoop = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
if checkValidUsernameLogin(textinput.get_text()):
account = textinput.get_text()
breakWhileLoop = True
else:
printErrorMessage = True
if breakWhileLoop:
break
textinput.update(events)
gameDisplay.blit(textinput.get_surface(), (displayWidth/3, displayHeight/2+35))
pygame.display.update()
clock.tick(60)
for i in accounts:
if i.username == account:
return i
def editProfile():
global loggedIn
global gameDisplay
print('Edit profile menu')
pygame.font.init()
largeText = pygame.font.SysFont('couriernew', 35)
smallText = pygame.font.SysFont('couriernew', 15)
while True:
gameDisplay.fill(colors.WHITE)
TextSurf, TextRect = text_objects(loggedIn.username, largeText)
TextRect.center = (displayWidth/2, displayHeight/4)
gameDisplay.blit(TextSurf, TextRect)
# Titles
TextSurf, TextRect = text_objects('ONE-PLAYER', smallText)
TextRect.center = (3*displayWidth/7, displayHeight/3)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects('TWO-PLAYER', smallText)
TextRect.center = (4*displayWidth/7, displayHeight/3)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects('TOTAL', smallText)
TextRect.center = (5*displayWidth/7, displayHeight/3)
gameDisplay.blit(TextSurf, TextRect)
# Wins
TextSurf, TextRect = text_objects(' WINS:', smallText)
TextRect.center = (2*displayWidth/7, displayHeight/3+20)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(str(loggedIn.onePlayerWins), smallText)
TextRect.center = (3*displayWidth/7, displayHeight/3+20)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(str(loggedIn.twoPlayerWins), smallText)
TextRect.center = (4*displayWidth/7, displayHeight/3+20)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(str(loggedIn.totalWins), smallText)
TextRect.center = (5*displayWidth/7, displayHeight/3+20)
gameDisplay.blit(TextSurf, TextRect)
# Losses
TextSurf, TextRect = text_objects(' LOSSES:', smallText)
TextRect.center = (2*displayWidth/7, displayHeight/3+40)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(str(loggedIn.onePlayerLosses), smallText)
TextRect.center = (3*displayWidth/7, displayHeight/3+40)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(str(loggedIn.twoPlayerLosses), smallText)
TextRect.center = (4*displayWidth/7, displayHeight/3+40)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(str(loggedIn.totalLosses), smallText)
TextRect.center = (5*displayWidth/7, displayHeight/3+40)
gameDisplay.blit(TextSurf, TextRect)
# Games Played
TextSurf, TextRect = text_objects(' GAMES:', smallText)
TextRect.center = (2*displayWidth/7, displayHeight/3+60)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(str(loggedIn.onePlayerGamesPlayed), smallText)
TextRect.center = (3*displayWidth/7, displayHeight/3+60)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(str(loggedIn.twoPlayerGamesPlayed), smallText)
TextRect.center = (4*displayWidth/7, displayHeight/3+60)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(str(loggedIn.totalGamesPlayed), smallText)
TextRect.center = (5*displayWidth/7, displayHeight/3+60)
gameDisplay.blit(TextSurf, TextRect)
# Win Ratio
TextSurf, TextRect = text_objects('WIN RATIO:', smallText)
TextRect.center = (2*displayWidth/7, displayHeight/3+80)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(str(loggedIn.onePlayerWinRatio) + '%', smallText)
TextRect.center = (3*displayWidth/7, displayHeight/3+80)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(str(loggedIn.twoPlayerWinRatio) + '%', smallText)
TextRect.center = (4*displayWidth/7, displayHeight/3+80)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(str(loggedIn.totalWinRatio) + '%', smallText)
TextRect.center = (5*displayWidth/7, displayHeight/3+80)
gameDisplay.blit(TextSurf, TextRect)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainMenu()
button('Reset Statistics', displayWidth/2-75, displayHeight/3+120, 150, 25, colors.RED, colors.BRIGHTRED, gameDisplay, resetStatistics, 15)
button('Reset AI Development', displayWidth/2-95, displayHeight/3+150, 190, 25, colors.RED, colors.BRIGHTRED, gameDisplay, resetAI, 15)
button('Delete Account', displayWidth/2-75, displayHeight/3+180, 150, 25, colors.RED, colors.BRIGHTRED, gameDisplay, deleteAccount, 15)
button('Back', 0, 575, 50, 25, colors.RED, colors.BRIGHTRED, gameDisplay, mainMenu, 15)
pygame.display.update()
clock.tick(60)
def resetStatistics():
loggedIn.resetStatistics()
def resetAI():
loggedIn.resetAI()
def deleteAccount():
global gameDisplay
global accounts
global loggedIn
print('Deleting account menu')
pygame.init()
displayWidth = 1000
displayHeight = 600
creatingAccountWindow = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('Delete Account Confirmation')
textinput = TextInput()
printErrorMessage = False
breakWhileLoop = False
deleteAccount = False
while True:
creatingAccountWindow.fill(colors.WHITE)
largeText = pygame.font.SysFont('couriernew', 35)
smallText = pygame.font.SysFont('couriernew', 15)
TextSurf, TextRect = text_objects('Enter username to confirm:', largeText, colors.BLACK)
TextRect.center = (displayWidth/2, displayHeight/2)
creatingAccountWindow.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects('Logged in: ' + loggedIn.username, smallText)
TextRect.center = (displayWidth/2, 12)
gameDisplay.blit(TextSurf, TextRect)
if printErrorMessage:
TextSurf, TextRect = text_objects('Usernames do not match!', largeText, colors.RED)
TextRect.center = (displayWidth/2, displayHeight/2+85)
creatingAccountWindow.blit(TextSurf, TextRect)
button('Cancel', 0, 575, 75, 25, colors.RED, colors.BRIGHTRED, gameDisplay, editProfile, 15)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
quitGame()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
if loggedIn.username == textinput.get_text():
deleteAccount = True
breakWhileLoop = True
else:
printErrorMessage = True
if breakWhileLoop:
break
textinput.update(events)
gameDisplay.blit(textinput.get_surface(), (displayWidth/3, displayHeight/2+35))
pygame.display.update()
clock.tick(60)
if deleteAccount:
print('Deleting account file: ' + loggedIn.username)
if operatingSystem == 'Windows':
os.remove('.accounts\\' + loggedIn.username + '.txt')
else:
os.remove('.accounts/' + loggedIn.username)
loggedIn = None
mainMenu()
def quitGame():
print('Closing game')
pygame.quit()
quit()
def settingsMenu():
global loggedIn
global gameDisplay
print('Settings menu')
pygame.font.init()
largeText = pygame.font.SysFont('couriernew', 35)
smallText = pygame.font.SysFont('couriernew', 15)
pygame.display.set_caption('Settings')
while True:
gameDisplay.fill(colors.WHITE)
TextSurf, TextRect = text_objects('SETTINGS', largeText)
TextRect.center = (displayWidth/2, displayHeight/4)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects('Created by', smallText)
TextRect.center = (displayWidth/2, displayHeight/3)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects('Ryan J. Slater', smallText)
TextRect.center = (displayWidth/2, displayHeight/3+25)
gameDisplay.blit(TextSurf, TextRect)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainMenu()
button('Quit Game', displayWidth/2-50, 3*displayHeight/4, 100, 25, colors.RED, colors.BRIGHTRED, gameDisplay, quitGame, 15)
button('Back', 0, 575, 50, 25, colors.RED, colors.BRIGHTRED, gameDisplay, mainMenu, 15)
pygame.display.update()
clock.tick(60)
def play():
global displayWidth
global displayHeight
global gameDisplay
global accounts
global pause
print('Game starting')
if loggedIn == None:
login(None, True)
accounts = getAllAccounts()
pygame.display.set_caption('Warships 2')
pygame.font.init()
textinput = TextInput()
breakWhileLoop = False
twoPlayer = False
while True:
gameDisplay.fill(colors.WHITE)
largeText = pygame.font.SysFont('couriernew', 35)
smallText = pygame.font.SysFont('couriernew', 15)
TextSurf, TextRect = text_objects('Enter number of players:', largeText)
TextRect.center = (displayWidth/2, displayHeight/2)
gameDisplay.blit(TextSurf, TextRect)
button('Main Menu', 0, 575, 100, 25, colors.RED, colors.BRIGHTRED, gameDisplay, mainMenu, 15)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
quitGame()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
if textinput.get_text().lower() in ['1', 'one']:
breakWhileLoop = True
elif textinput.get_text().lower() in ['2', 'two'] and len(accounts) > 1:
twoPlayer = True
breakWhileLoop = True
if breakWhileLoop:
break
textinput.update(events)
gameDisplay.blit(textinput.get_surface(), (displayWidth/3, displayHeight/2+35))
pygame.display.update()
clock.tick(60)
p1 = loggedIn.human
p1acct = loggedIn
p2 = None
p2acct = None
if twoPlayer:
p2acct = getSecondPlayer()
p2 = p2acct.human
else:
p2 = loggedIn.computer
# Place ships
p1.board = placeShips(p1.name, 0)
# -5 = carrier
# -4 = battleship
# -3 = cruiser
# -2 = submarine
# -1 = destroyer
# 0 = empty
# 1 = miss
# 2 = hit
# 3 = sunk ship
p2.board = placeShips(p2.name, 1) if twoPlayer else placeShips(p2.name, 1, True)
p1BoardCopy = np.copy(p1.board)
p2BoardCopy = np.copy(p2.board)
print('\nPlaying:')
print('Player 1: ' + p1.name)
print('Player 2: ' + p2.name)
largeText = pygame.font.SysFont('couriernew', 35)
smallText = pygame.font.SysFont('couriernew', 15)
gameOver = False
turn = -1
reticleImg = pygame.image.load('icons\\reticle.png') if operatingSystem == 'Windows' else pygame.image.load('icons/reticle.png')
reticleLoc = (4, 4)
turnEnded = False
mouseBoardCoords = np.array([[(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0)],
[(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0)],
[(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0)],
[(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0)],
[(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0)],
[(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0)],
[(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0)],
[(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0)],
[(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0)],
[(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0)]], dtype=object)
for row in range(10):
for col in range(10):
mouseBoardCoords[row][col] = (200+60*row, 260+60*row, 60*col, 60+60*col)
turnCount = 0
p1Fleet = []
p2Fleet = []
while True:
pygame.mouse.set_visible(False)
gameDisplay.fill(colors.WHITE)
# Display Player Names
# TODO: make colors based on who's turn it is
p1Col = colors.RED if turn == -1 else colors.BLACK
p2Col = colors.RED if turn == 1 else colors.BLACK
TextSurf, TextRect = text_objects(p1.name, smallText, p1Col)
TextRect.center = (int(10*len(p1.name)/2), 12)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(p2.name, smallText, p2Col)
TextRect.center = (995-int(10*len(p2.name)/2), 12)
gameDisplay.blit(TextSurf, TextRect)
TextSurf, TextRect = text_objects(str(turnCount+1), smallText, colors.BLACK)
TextRect.center = (int(10*len(p1.name))+15, 12)
gameDisplay.blit(TextSurf, TextRect)
# Display Ships
pygame.draw.rect(gameDisplay, colors.BLACK, (0, 100, 200, 250))
pygame.draw.rect(gameDisplay, colors.BLACK, (800, 100, 200, 250))
iconDir = 'icons/'
if operatingSystem == 'Windows':
iconDir = 'icons\\'
if -5 in p1Fleet:
gameDisplay.blit(pygame.image.load(iconDir + 'carrierOutline.png'), (0, 100))
if -4 in p1Fleet:
gameDisplay.blit(pygame.image.load(iconDir + 'battleshipOutline.png'), (0, 150))
if -3 in p1Fleet:
gameDisplay.blit(pygame.image.load(iconDir + 'cruiserOutline.png'), (0, 200))
if -2 in p1Fleet:
gameDisplay.blit(pygame.image.load(iconDir + 'submarineOutline.png'), (0, 250))
if -1 in p1Fleet:
gameDisplay.blit(pygame.image.load(iconDir + 'destroyerOutline.png'), (0, 300))
if -5 in p2Fleet:
gameDisplay.blit(pygame.image.load(iconDir + 'carrierOutline.png'), (800, 100))
if -4 in p2Fleet:
gameDisplay.blit(pygame.image.load(iconDir + 'battleshipOutline.png'), (800, 150))
if -3 in p2Fleet:
gameDisplay.blit(pygame.image.load(iconDir + 'cruiserOutline.png'), (800, 200))
if -2 in p2Fleet:
gameDisplay.blit(pygame.image.load(iconDir + 'submarineOutline.png'), (800, 250))
if -1 in p2Fleet:
gameDisplay.blit(pygame.image.load(iconDir + 'destroyerOutline.png'), (800, 300))
# Display Board
for row in range(10):
for col in range(10):
pygame.draw.rect(gameDisplay, colors.BRIGHTBLUE, (200+60*col, 60*row, 60, 60))
pygame.draw.rect(gameDisplay, colors.BLUE, (201+60*col, 1+60*row, 59, 59))
if turn == -1:
if p2.board[row][col] == 1:
pygame.draw.circle(gameDisplay, colors.WHITE, (230+60*col, 30+60*row), 20)
if p2.board[row][col] == 2:
pygame.draw.rect(gameDisplay, colors.DARKGRAY, (201+60*col, 1+60*row, 59, 59))
pygame.draw.circle(gameDisplay, colors.RED, (230+60*col, 30+60*row), 20)
if p2.board[row][col] == 3:
pygame.draw.rect(gameDisplay, colors.BLACK, (201+60*col, 1+60*row, 59, 59))
pygame.draw.circle(gameDisplay, colors.RED, (230+60*col, 30+60*row), 20)
else:
if p1.board[row][col] == 1:
pygame.draw.circle(gameDisplay, colors.WHITE, (230+60*col, 30+60*row), 20)
if p1.board[row][col] == 2:
pygame.draw.rect(gameDisplay, colors.DARKGRAY, (201+60*col, 1+60*row, 59, 59))
pygame.draw.circle(gameDisplay, colors.RED, (230+60*col, 30+60*row), 20)
if p1.board[row][col] == 3: