· 4 years ago · Feb 12, 2021, 01:56 PM
1from replit import clear
2import sqlite3
3import json
4import time
5import datetime
6
7def createDB():
8 #create PLAYER table
9 sql = 'CREATE TABLE IF NOT EXISTS PLAYER ([playerID] INTEGER PRIMARY KEY, [playername] text, [winlose] text)'
10 outputSQL(sql)
11
12 #create GAME table
13 sql = 'CREATE TABLE IF NOT EXISTS GAME ([gameID] INTEGER PRIMARY KEY, [date] date, [winner] text, [lengthofgame] integer)'
14 outputSQL(sql)
15
16 #create SHIPS table
17 sql = 'CREATE TABLE IF NOT EXISTS SHIPS ([shipsID] INTEGER PRIMARY KEY, [playerID] integer, [ship1] text, [ship2] text, [ship3] text, [ship4] text, [ship5] text)'
18 outputSQL(sql)
19
20 #create GAMESTATS table
21 sql = 'CREATE TABLE IF NOT EXISTS GAMESTATS ([gamestatsID] INTEGER PRIMARY KEY, [gameID] integer, [playerID] integer, [hitmiss] text, [noofshots] integer)'
22 outputSQL(sql)
23
24def outputSQL(sql):
25 with sqlite3.connect("battleships.db")as conn:
26 cursor = conn.cursor()
27 cursor.execute(sql)
28 conn.commit
29 result = cursor.fetchall()
30 for each in result:
31 print(each)
32sqlresult = ''
33
34def outputSQLtable(table):
35 sql = "select * from "+ table
36
37 with sqlite3.connect("battleships.db")as conn:
38 cursor = conn.cursor()
39 cursor.execute(sql)
40 conn.commit
41 result = cursor.fetchall()
42 for each in result:
43 print(each)
44
45
46def returnSQL(sql):
47 with sqlite3.connect("battleships.db")as conn:
48 cursor = conn.cursor()
49 cursor.execute(sql)
50 conn.commit
51 result = cursor.fetchall()
52 return result
53
54## select player ##
55def selectplayer(player):
56 global player1id
57 global player2id
58 returninginp = ''
59 validinp = False
60
61 sql = "SELECT * FROM PLAYER"
62 results = returnSQL(sql)
63 if results == []:
64 validinp = True
65 returning = False
66 #else
67
68 while validinp == False:
69 returning = False
70 returninginp = input('\nAre you a New or Returning player? (n/r):\n\t ')
71 returninginp.lower()
72 if returninginp == 'n':
73 returning = False
74 validinp = True
75 elif returninginp == 'r':
76 returning = True
77 validinp = True
78 else:
79 print('\nInvalid input')
80 validinp = False
81
82 if returning == True:
83 sql = 'SELECT playerID, playername FROM PLAYER'
84 results = returnSQL(sql)
85
86 i = 0
87 i = int(i)
88 print('\nID\tName')
89 count = 0
90 for row in range (len(results)):
91 print(str(results[row][0]) + "\t" + str(results[row][1]))
92
93 playerid = input('\nEnter the ID next to your name:\n\t ')
94 if player == 1:
95 sql = "SELECT playername FROM PLAYER WHERE playerID = {}".format(playerid)
96 results = returnSQL(sql)
97 player1name = str(results[0])
98 player1name = player1name.replace("(", "")
99 player1name = player1name.replace("'", "")
100 player1name = player1name.replace(")", "")
101 player1name = player1name.replace(",", "")
102 player1id = playerid
103
104 print('\nWelcome back',player1name)
105
106 returningp1 = returning
107 return player1id, player1name, returningp1
108
109 else: #if player == 2
110 while playerid == player1id:
111 playerid = input('\nPlayer already chosen, pick another player:\n\t ')
112
113 sql = "SELECT playername FROM PLAYER WHERE playerID = {}".format(playerid)
114 results = returnSQL(sql)
115 player2name = str(results[0])
116 player2name = player2name.replace("(", "")
117 player2name = player2name.replace("'", "")
118 player2name = player2name.replace(")", "")
119 player2name = player2name.replace(",", "")
120 player2id = playerid
121
122 print('\nWelcome back',player2name)
123
124 returningp2 = returning
125 return player2id, player2name, returningp2
126
127 else: #new player
128 if player == 1:
129 player1name = input('Enter the name you would like to be known as:\n\t ')
130 sql = "INSERT INTO PLAYER (playername) VALUES('{}') ".format(player1name)
131 outputSQL(sql)
132 sql = "SELECT playerID from PLAYER WHERE playername = '{}'".format(player1name)
133 result = returnSQL(sql)
134 player1id = result[0][0]
135
136 returningp1 = returning
137 return player1id, player1name, returningp1
138
139 elif player == 2:
140 player2name = input('Enter the name you would like to be known as:\n\t ')
141 sql = "INSERT INTO PLAYER (playername) VALUES('{}') ".format(player2name)
142 outputSQL(sql)
143 sql = "SELECT playerID from PLAYER WHERE playername = '{}'".format(player2name)
144 result = returnSQL(sql)
145 player2id = result[0][0]
146
147 returningp2 = returning
148 return player2id, player2name, returningp2
149
150
151## print grid ##
152def printgrid(shipcoord):
153 for i in range(9):
154 for j in range(9):
155 found = False
156 coordinate = [i,j]
157 for ship in shipcoord:
158 if coordinate in ship:
159 print("[x] ",end='')
160 found = True
161 if not found:
162 print("[ ]", end=' ')
163 print()
164 print()
165
166## place ships function ##
167def placeships(grid, shipcoord, player):
168 ships = [5, 4, 3, 3, 2]
169 shipsplaced = 0
170 print('\nPlayer',player,', place your ships')
171
172 while shipsplaced != 5: #while not all ships are placed
173 shipcoord.append([]) #adding new sublist for the new ship
174 y = 3
175 for count in range(ships[shipsplaced]): #grid[rows][columns], [y, x]
176 shipcoord[shipsplaced].append([y,4])
177 y += 1
178 vertical = True #orientation of ship
179 key = ""
180 while key != 'f':
181 for i in range(len(grid)):
182 for j in range(len(grid[i])):
183 found = False
184 coordinate = [i,j]
185 for ship in range(shipsplaced+1):
186 if coordinate in shipcoord[ship]:
187 print("[x] ",end='')
188 found = True
189 if not found:
190 print(grid[i][j], end=' ')
191 print()
192 print()
193
194 ## moving the ships ##
195 key = input('\nWhich direction would you like to move? \n(use wasd, r to rotate and f to finish:\n\t ').lower()
196 print()
197 if key == 'w':
198 for i in range(ships[shipsplaced]):
199 shipcoord[shipsplaced][i][0] -= 1
200 elif key == 'a':
201 for i in range(ships[shipsplaced]):
202 shipcoord[shipsplaced][i][1] -= 1
203 elif key == 's':
204 for i in range(ships[shipsplaced]):
205 shipcoord[shipsplaced][i][0] += 1
206 elif key == 'd':
207 for i in range(ships[shipsplaced]):
208 shipcoord[shipsplaced][i][1] += 1
209 elif key == 'r':
210 if vertical == True:
211 for i in range(ships[shipsplaced]):
212 if i != 0:
213 shipcoord[shipsplaced][i][0] = shipcoord[shipsplaced][0][0]
214 shipcoord[shipsplaced][i][1] = shipcoord[shipsplaced][0][1] - i
215 vertical = False
216 else:
217 for i in range(ships[shipsplaced]):
218 if i != 0:
219 shipcoord[shipsplaced][i][0] = shipcoord[shipsplaced][0][0] + i
220 shipcoord[shipsplaced][i][1] = shipcoord[shipsplaced][0][1]
221 vertical = True
222
223 elif key == 'f':
224 valid = validcoord(shipcoord,shipsplaced,grid)
225 #shows coordinates in shipcoords before adding new ship
226 if valid == False:
227 key = ' '
228 y = 3
229 for count in range(len(shipcoord[shipsplaced])):
230 #grid[rows][columns], [y, x]
231 shipcoord[shipsplaced][count] = [y,4]
232 y += 1
233 #shows coordinates in shipcoords after adding new ship
234 else:
235 print('\nInvalid input, enter either wasd, f or r')
236
237 shipsplaced += 1 #add 1 to ships placed once ship is placed
238
239 return grid, shipcoord
240
241def ifshipssaved(playerid):
242 results = getshipssaved(playerid)
243 if results == []:
244 return False
245 else:
246 return True
247
248def getshipssaved(playerid):
249 sql = "SELECT ship1, ship2, ship3, ship4, ship5 FROM SHIPS WHERE playerID = {}".format(playerid)
250 results = returnSQL(sql)
251 if results == []: #if empty, return empty list
252 return []
253 return results[0] #if not empty, returns first row
254
255## placeshipsDB ##
256
257## place the ships for a particular player
258def placeshipsDB(player, playerid, gridship, shipcoords, returning):
259 if returning == True :
260 sql = "SELECT ship1, ship2, ship3, ship4, ship5 FROM SHIPS WHERE playerID = {}".format(playerid)
261 results = returnSQL(sql)
262 validinp = False
263 usearrange = False
264 if ifshipssaved(playerid): #ships exist in database
265 while validinp == False:
266 usearrangeinp = input('\nWould you like to use your ship arrangement from your previous game? (y/n):\n\t ')
267 usearrangeinp.lower()
268 if usearrangeinp == 'n':
269 usearrange = False
270 validinp = True
271 elif usearrangeinp == 'y':
272 usearrange = True
273 validinp = True
274 else:
275 print('\nInvalid input')
276 validinp = False
277
278 if usearrange == False: #if user wants to place ships
279 gridship, shipcoords = placeships(gridship, shipcoords, player)
280 elif usearrange == True : #if user wants to reuse saved ships
281 ships = getshipssaved(playerid)
282 shipcoords = []
283 for item in ships:
284 ship = json.loads(item)
285 shipcoords.append(ship)
286
287 else: # not a returning player
288 gridship, shipcoords = placeships(gridship, shipcoords, player)
289
290 if ifshipssaved(playerid) == True: #ships saved
291 sql = "UPDATE SHIPS SET ship1 = '{}', ship2 = '{}', ship3 ='{}', ship4 = '{}', ship5 = '{}' WHERE playerid = {}".format(shipcoords[0], shipcoords[1], shipcoords[2], shipcoords[3], shipcoords[4], playerid)
292 returnSQL(sql)
293 else: #ships not previouslt saved
294 sql = "INSERT INTO SHIPS (playerID,ship1, ship2, ship3, ship4, ship5) VALUES ('{}','{}','{}','{}','{}','{}')".format(playerid, shipcoords[0],shipcoords[1],shipcoords[2],shipcoords[3],shipcoords[4])
295 returnSQL(sql)
296
297 return shipcoords
298
299## validcoord function ##
300def validcoord(shipcoord,shipsplaced,grid):
301 valid = True
302 for coordinate in shipcoord[shipsplaced]:
303 if coordinate[0] > 8 or coordinate[1] > 8 or coordinate[0] < 0 or coordinate[1] < 0:
304 valid = False #if coordinate is outside the grid, it is invalid
305 if valid == True:
306 for ship in range(shipsplaced):
307 for coordinate in shipcoord[shipsplaced]:
308 if coordinate in shipcoord[ship]:
309 valid = False #if a ship has already been placed on that coordinate, it is invalid
310 return valid
311
312
313def drawHitorMiss(grid, shipcoords, coordlog, turns):
314 for i in range(len(grid)):
315 for j in range(len(grid[i])):
316 found = False
317 coordinate = [i,j]
318 if coordinate in coordlog:
319 if turns[coordlog.index(coordinate)] == True:
320 if coordlog.index(coordinate) == len(turns)-1:
321 print("[X] ",end='')
322 else:
323 print("[x] ",end='')
324 elif turns[coordlog.index(coordinate)] == False:
325 if coordlog.index(coordinate) == len(turns)-1:
326 print("[O] ",end='')
327 else:
328 print("[o] ",end='')
329 found = True
330 if not found:
331 print(grid[i][j], end=' ')
332 print()
333
334## gameplay function ##
335
336def gameplay(player,coordlogp1,coordlogp2,gridp1ship, p1turns,gridp2ship, p2turns):
337 valid = False
338 while valid == False:
339 if player == 1:
340 drawHitorMiss(gridp1ship, shipcoordsp2, coordlogp1, p1turns)
341 else:
342 drawHitorMiss(gridp2ship, shipcoordsp2, coordlogp2, p2turns)
343 shot = input('\nPlayer '+str(player)+', enter x and y values separated by a space:\n\t')
344 shot = shot.split(" ")
345 try:
346 shot[0] = int(shot[0])
347 shot[1] = int(shot[1])
348 temp = shot[0]
349 shot[0] = shot[1]
350 shot[1] = temp
351 valid = True
352 except ValueError:
353 print("\nNot a valid coordinate")
354 valid = False
355 except IndexError:
356 print('\nNot a valid coordinate')
357 valid = False
358 if valid == True:
359 if shot[0] >= 0 and shot[0] < 9 and shot[1] >= 0 and shot[1] < 9: #checks its on the grid
360 valid = True
361 else:
362 valid = False
363 print('\nNot a valid coordinate - not on the grid')
364 if valid == True:
365 if player == 1:
366 if shot in coordlogp1:
367 valid = False
368 print('\nNot a valid coordinate - already tried')
369 elif player == 2:
370 if shot in coordlogp2:
371 valid = False
372 print('\nNot a valid coordinate - already tried')
373 return shot, valid
374
375def hitormiss(shipcoords, hitcount, coordlog):
376 global hit
377 hit = False
378 if valid == True: #hit or miss
379 hit = False
380 for ship in range(len(shipcoords)):
381 for coordinate in range(len(shipcoords[ship])):
382 if shot[0] == shipcoords[ship][coordinate][0] and shot[1] == shipcoords[ship][coordinate][1]:
383 hit = True
384 if hit:
385 hitcount += 1
386 return hitcount, coordlog, hit
387
388## win:lose calculator ##
389def winlosecalc (playerid, playername, winnername):
390 sql = "SELECT winlose FROM PLAYER WHERE playerid = {} ".format(playerid)
391 results = returnSQL(sql)
392 if results[0] == (None,): #if empty
393 win = 0
394 lose = 0
395 else: #if not empty, gives first row
396 results = str(results[0])
397 results = results.replace("(", "")
398 results = results.replace("'", "")
399 results = results.replace(")", "")
400 results = results.replace(",", "")
401 results = results.replace("[", "")
402 results = results.replace("]", "")
403 winlose = results.split(':')
404 win = str(winlose[0])
405 lose = str(winlose[1])
406
407 if winnername == playername: #if current player won
408 win = int(win) + 1
409 else:
410 lose = int(lose) + 1
411 newwinlose = (str(win) ,':', str(lose))
412 newwinlose = ''.join(newwinlose)
413 sql = "UPDATE PLAYER SET winlose = '{}' where playerid = {}".format(newwinlose, playerid)
414 returnSQL(sql)
415
416def hitmisscalc(playerid, turns):
417 hits = turns.count(True)
418 misses = turns.count(False)
419 hitmiss = (str(hits) ,':', str(misses))
420 hitmiss = ''.join(hitmiss)
421 return hitmiss
422
423## code starts ##
424player = 1
425gridbounds = []
426
427shipcoordsp1 = []
428shipcoordsp2 = []
429hitcountp1 = 0
430hitcountp2 = 0
431coordlogp1 = []
432coordlogp2 = []
433valid = False
434p1turns = []
435p2turns = []
436returningp1 = False
437returningp2 = False
438grisp1ship = []
439gridp2ship = []
440
441#create database
442createDB()
443
444#player 1 ship grid
445gridp1ship = []
446for i in range(9):
447 gridp1ship.append([])
448 for j in range(9):
449 gridp1ship[i].append('[ ]')
450 print(gridp1ship[i][j], end=' ')
451 print()
452print()
453
454#player 2 ship grid
455gridp2ship = []
456for i in range(9):
457 gridp2ship.append([])
458 for j in range(9):
459 gridp2ship[i].append('[ ]')
460 print(gridp2ship[i][j], end=' ')
461 print()
462print()
463
464clear()
465shipsplaced = 0
466
467#call placeships
468player = 1
469
470player1id, player1name, returningp1 = selectplayer(player)
471
472shipcoordsp1 = placeshipsDB(1, player1id, gridp1ship, shipcoordsp1, returningp1)
473print('\nAll ships placed')
474printgrid(shipcoordsp1)
475clear()
476print('\nPass to player 2')
477
478player = 2
479
480player2id, player2name, returningp2 = selectplayer(player)
481
482shipcoordsp2 = placeshipsDB(2, player2id, gridp2ship, shipcoordsp2, returningp2)
483print('\nAll ships placed')
484printgrid(shipcoordsp2)
485clear()
486print('\nThe game can now start')
487
488player = 1
489
490## GAMEPLAY ##
491start = time.time()
492while hitcountp1 < 17 and hitcountp2 < 17:
493 shot, valid = gameplay(player,coordlogp1,coordlogp2, gridp1ship, p1turns,gridp2ship, p2turns)
494 if valid == True and player == 1:
495 coordlogp1.append(shot)
496 hitcountp1, coordlogp1, hit = hitormiss(shipcoordsp2, hitcountp1, coordlogp1)
497 if hit == True:
498 print('\nIts a hit!')
499 print('')
500 p1turns.append(hit)
501 else:
502 print("\nIt's a miss")
503 print('')
504 player = 2
505 p1turns.append(hit)
506
507 if player == 1:
508 drawHitorMiss(gridp1ship, shipcoordsp2, coordlogp1, p1turns)
509 else:
510 drawHitorMiss(gridp2ship, shipcoordsp2, coordlogp2, p2turns)
511 clear()
512 print()
513
514 elif valid == True and player == 2:
515 coordlogp2.append(shot)
516 hitcountp2, coordlogp2, hit = hitormiss(shipcoordsp1, hitcountp2, coordlogp2)
517 if hit == True:
518 print('Its a hit!')
519 p2turns.append(hit)
520 else:
521 player = 1
522 p2turns.append(hit)
523 clear()
524end = time.time()
525lengthofgameseconds = round(end - start)
526minutes = lengthofgameseconds // 60
527seconds = lengthofgameseconds % 60
528
529print('\nGame over!')
530if player == 1:
531 winnername = player1name
532else:
533 winnername = player2name
534print('\n' + winnername,'won the game!')
535
536#GAME
537tdate = datetime.datetime.now()
538tdate = (tdate.strftime("%d %m %Y"))
539sql = "INSERT INTO GAME(date, winner, lengthofgame) VALUES('{}','{}',{})".format(tdate, winnername, lengthofgameseconds)
540returnSQL(sql)
541
542#PLAYER
543winlose1 = winlosecalc(player1id, player1name, winnername)
544winlose2 = winlosecalc(player2id, player2name, winnername)
545
546#GAMESTATS
547hitmiss1 = hitmisscalc(player1id, p1turns)
548hitmiss2 = hitmisscalc(player2id, p2turns)
549#get gameid from GAME for GAMESTATS
550sql = "SELECT gameID FROM GAME ORDER BY GameID DESC LIMIT 1"
551results = returnSQL(sql)
552results = results[0]
553results = str(results)
554results = results.replace("(", "")
555results = results.replace(")", "")
556results = results.replace(",", "")
557gameid = int(results)
558
559noofshots1 = len(p1turns)
560noofshots2 = len(p2turns)
561sql = "INSERT INTO GAMESTATS (gameid, playerid, hitmiss, noofshots) VALUES ({}, {},'{}', '{}')".format(gameid, player1id, hitmiss1,noofshots1)
562returnSQL(sql)
563
564sql = "INSERT INTO GAMESTATS (gameid, playerid, hitmiss, noofshots) VALUES ({}, {}, '{}', '{}')".format(gameid, player2id, hitmiss2,noofshots2)
565returnSQL(sql)