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