· 4 years ago · May 08, 2021, 12:02 PM
1import sqlite3
2
3global player
4player = 1
5gridbounds = []
6returning = False
7shipcoordsp1 = []
8shipcoordsp2 = []
9hitcountp1 = 0
10hitcountp2 = 0
11coordlogp1 = []
12coordlogp2 = []
13valid = False
14p1turns = []
15p2turns = []
16returningp1 = False
17returningp2 = False
18grisp1ship = []
19gridp2ship = []
20global player1id
21global player2id
22sqlresult = ''
23
24
25def createDB():
26 # create PLAYER table
27 sql = 'CREATE TABLE IF NOT EXISTS PLAYER ([playerID] INTEGER PRIMARY KEY, [playername] text, [winlose] text)'
28 outputSQL(sql)
29
30 # create GAME table
31 sql = 'CREATE TABLE IF NOT EXISTS GAME ([gameID] INTEGER PRIMARY KEY, [date] date, [winner] text, [lengthofgame] integer)'
32 outputSQL(sql)
33
34 # create SHIPS table
35 sql = 'CREATE TABLE IF NOT EXISTS SHIPS ([shipsID] INTEGER PRIMARY KEY, [playerID] integer, [ship1] text, [ship2] text, [ship3] text, [ship4] text, [ship5] text)'
36 outputSQL(sql)
37
38 # create GAMESTATS table
39 sql = 'CREATE TABLE IF NOT EXISTS GAMESTATS ([gamestatsID] INTEGER PRIMARY KEY, [gameID] integer, [playerID] integer, [hitmiss] text, [noofshots] integer)'
40 outputSQL(sql)
41
42
43def outputSQL(sql):
44 with sqlite3.connect("battleships.db")as conn:
45 cursor = conn.cursor()
46 cursor.execute(sql)
47 conn.commit
48 result = cursor.fetchall()
49 for each in result:
50 print(each)
51
52
53def outputSQLtable(table):
54 sql = "select * from " + table
55
56 with sqlite3.connect("battleships.db")as conn:
57 cursor = conn.cursor()
58 cursor.execute(sql)
59 conn.commit
60 result = cursor.fetchall()
61 for each in result:
62 print(each)
63
64
65def returnSQL(sql):
66 with sqlite3.connect("battleships.db")as conn:
67 cursor = conn.cursor()
68 cursor.execute(sql)
69 conn.commit
70 result = cursor.fetchall()
71 return result
72
73
74def ifshipssaved(playerid):
75 results = getshipssaved(playerid)
76 if results == []:
77 return False
78 else:
79 return True
80
81
82def ifpreviousplayers():
83 sql = "SELECT * FROM PLAYER"
84 results = returnSQL(sql)
85 if results == []: # if empty, return empty list
86 return False
87 return True # if not empty, returns first row
88
89
90def returningplayer(player, user_text, player1id):
91 playerid = user_text
92 if player == 1:
93 sql = "SELECT playername FROM PLAYER WHERE playerID = {}".format(playerid)
94 results = returnSQL(sql)
95 player1name = str(results[0])
96 player1name = player1name.replace("(", "")
97 player1name = player1name.replace("'", "")
98 player1name = player1name.replace(")", "")
99 player1name = player1name.replace(",", "")
100 player1id = playerid
101 returningp1 = True
102 return player1id, player1name, returningp1
103
104 else: # if player == 2
105 while playerid == player1id:
106 playerid = user_text
107 sql = "SELECT playername FROM PLAYER WHERE playerID = {}".format(playerid)
108 results = returnSQL(sql)
109 player2name = str(results[0])
110 player2name = player2name.replace("(", "")
111 player2name = player2name.replace("'", "")
112 player2name = player2name.replace(")", "")
113 player2name = player2name.replace(",", "")
114 player2id = playerid
115 returningp2 = True
116 return player2id, player2name, returningp2
117
118
119def newplayername(player, user_text, returning):
120 if player == 1:
121 sql = "INSERT INTO PLAYER (playername) VALUES('{}') ".format(user_text)
122 outputSQL(sql)
123 sql = "SELECT playerID from PLAYER WHERE playername = '{}'".format(user_text)
124 player1name = user_text
125 result = returnSQL(sql)
126 player1id = result[0][0]
127
128 returningp1 = returning
129 return player1id, player1name, returningp1
130
131 elif player == 2:
132 sql = "INSERT INTO PLAYER (playername) VALUES('{}') ".format(user_text)
133 outputSQL(sql)
134 sql = "SELECT playerID from PLAYER WHERE playername = '{}'".format(user_text)
135 player2name = user_text
136 result = returnSQL(sql)
137 player2id = result[0][0]
138
139 returningp2 = returning
140 return player2id, player2name, returningp2
141
142
143def getshipssaved(playerid):
144 sql = "SELECT ship1, ship2, ship3, ship4, ship5 FROM SHIPS WHERE playerID = {}".format(playerid)
145 results = returnSQL(sql)
146 if results == []: # if empty, return empty list
147 return []
148 return results[0] # if not empty, returns first row
149
150
151def placeships(grid, shipcoord, player):
152 ships = [5, 4, 3, 3, 2]
153 shipsplaced = 0
154
155 while shipsplaced != 5: # while not all ships are placed
156 shipcoord.append([]) # adding new sublist for the new ship
157 y = 3
158 for count in range(ships[shipsplaced]): # grid[rows][columns], [y, x]
159 shipcoord[shipsplaced].append([y, 4])
160 y += 1
161 vertical = True # orientation of ship
162 key = ""
163 while key != 'f':
164 # print grid start
165 for i in range(len(grid)):
166 for j in range(len(grid[i])):
167 found = False
168 coordinate = [i, j]
169 for ship in range(shipsplaced + 1):
170 if coordinate in shipcoord[ship]:
171 print("[x] ", end='')
172 found = True
173 if not found:
174 print(grid[i][j], end=' ')
175 print()
176 print()
177 # print grid end
178
179
180def printgrid(grid, shipsplaced, shipcoord):
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 grid = [[[''], [''], [''], [''], [''], [''], [''], {''}, ['']],
195 [[''], [''], [''], [''], [''], [''], [''], [''], [''],
196 [[''], [''], [''], [''], [''], [''], [''], [''], [''],
197 [[''], [''], [''], [''], [''], [''], [''], [''], [''],
198 [[''], [''], [''], [''], [''], [''], [''], [''], [''],
199 [[''], [''], [''], [''], [''], [''], [''], [''], [''],
200 [[''], [''], [''], [''], [''], [''], [''], [''], [''],
201 [[''], [''], [''], [''], [''], [''], [''], [''], [''],
202 [[''], [''], [''], [''], [''], [''], [''], [''], ['']]]
203 '''
204
205 for i in range(len(grid)):
206 for j in range(len(grid[i])):
207 found = False
208 coordinate = [i, j]
209 for ship in range(shipsplaced + 1):
210 if coordinate in shipcoord[ship]:
211 shipcoord[ship] = 'x'
212 found = True
213
214
215def validcoord(shipcoord, shipsplaced, grid):
216 valid = True
217 for coordinate in shipcoord[shipsplaced]:
218 if coordinate[0] > 8 or coordinate[1] > 8 or coordinate[0] < 0 or coordinate[1] < 0:
219 valid = False # if coordinate is outside the grid, it is invalid
220 if valid == True:
221 for ship in range(shipsplaced):
222 for coordinate in shipcoord[shipsplaced]:
223 if coordinate in shipcoord[ship]:
224 valid = False # if a ship has already been placed on that coordinate, it is invalid
225 return valid
226
227
228def hitormiss(shipcoords, hitcount, coordlog, shot):
229 global hit
230 hit = False
231 if valid == True: # hit or miss
232 hit = False
233 for ship in range(len(shipcoords)):
234 for coordinate in range(len(shipcoords[ship])):
235 if shot[0] == shipcoords[ship][coordinate][0] and shot[1] == shipcoords[ship][coordinate][1]:
236 hit = True
237 if hit:
238 hitcount += 1
239 return hitcount, coordlog, hit
240
241
242def winlosecalc(playerid, playername, winnername):
243 sql = "SELECT winlose FROM PLAYER WHERE playerid = {} ".format(playerid)
244 results = returnSQL(sql)
245 if results[0] == (None,): # if empty
246 win = 0
247 lose = 0
248 else: # if not empty, gives first row
249 results = str(results[0])
250 results = results.replace("(", "")
251 results = results.replace("'", "")
252 results = results.replace(")", "")
253 results = results.replace(",", "")
254 results = results.replace("[", "")
255 results = results.replace("]", "")
256 winlose = results.split(':')
257 win = str(winlose[0])
258 lose = str(winlose[1])
259
260 if winnername == playername: # if current player won
261 win = int(win) + 1
262 else:
263 lose = int(lose) + 1
264 newwinlose = (str(win), ':', str(lose))
265 newwinlose = ''.join(newwinlose)
266 sql = "UPDATE PLAYER SET winlose = '{}' where playerid = {}".format(newwinlose, playerid)
267 returnSQL(sql)
268
269
270def hitmisscalc(playerid, turns):
271 hits = turns.count(True)
272 misses = turns.count(False)
273 hitmiss = (str(hits), ':', str(misses))
274 hitmiss = ''.join(hitmiss)
275 return hitmiss