forked from himanitawade/Web-Backend-Project3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.py
More file actions
287 lines (242 loc) · 9.83 KB
/
game.py
File metadata and controls
287 lines (242 loc) · 9.83 KB
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
import dataclasses
import sqlite3
import uuid
import databases
import toml
import itertools
import random
from itertools import cycle
from quart import Quart, abort, g, request
from quart_schema import QuartSchema, validate_request
app = Quart(__name__)
QuartSchema(app)
app.config.from_file(f"./etc/{__name__}.toml", toml.load)
@dataclasses.dataclass
class Game:
username: str
@dataclasses.dataclass
class Guess:
gameid: str
word: str
dbList = []
async def _get_write_db():
db = getattr(g, "_sqlite_db", None)
if db is None:
db = g._sqlite_db = databases.Database(app.config["DATABASES"]["PRIMARY"])
await db.connect()
return db
async def _get_read_dbs():
db = getattr(g, "_sqlite_db", None)
if db is None:
db1 = g._sqlite_db = databases.Database(app.config["DATABASES"]["PRIMARY"])
await db1.connect()
db2 = g._sqlite_db = databases.Database(app.config["DATABASES"]["SECONDARY1"])
await db2.connect()
db3 = g._sqlite_db = databases.Database(app.config["DATABASES"]["SECONDARY2"])
await db3.connect()
return db1, db2, db3
@app.teardown_appcontext
async def close_connection(exception):
db = getattr(g, "_sqlite_db", None)
if db is not None:
await db.disconnect()
@app.route("/newgame", methods=["POST"])
async def create_game():
# auth method referenced from https://www.youtube.com/watch?v=VW8qJxy4XcQ
auth = request.authorization
if auth and auth.username and auth.password:
db = await _get_write_db()
# Retrive random ID from the answers table
word = await db.fetch_one(
"SELECT answerid FROM answer ORDER BY RANDOM() LIMIT 1"
)
# Check if the retrived word is a repeat for the user, and if so grab a new word
while await db.fetch_one(
"SELECT answerid FROM games WHERE username = :username AND answerid = :answerid",
values={"username": auth.username, "answerid": word[0]},
):
word = await db.fetch_one(
"SELECT answerid FROM answer ORDER BY RANDOM() LIMIT 1"
)
# Create new game with 0 guesses
gameid = str(uuid.uuid1())
values = {"gameid": gameid, "guesses": 0, "gstate": "In-progress"}
await db.execute(
"INSERT INTO game(gameid, guesses, gstate) VALUES(:gameid, :guesses, :gstate)",
values,
)
# Create new row into Games table which connect with the recently connected game
values = {"username": auth.username, "answerid": word[0], "gameid": gameid}
await db.execute(
"INSERT INTO games(username, answerid, gameid) VALUES(:username, :answerid, :gameid)",
values,
)
return values, 201
else:
return (
{"error": "User not verified"},
401,
{"WWW-Authenticate": 'Basic realm = "Login required"'},
)
# Should validate to check if guess is in valid_word table
# if it is then insert into guess table
# update game table by decrementing guess variable
# if word is not valid throw 404 exception
@app.route("/addguess", methods=["PUT"])
@validate_request(Guess)
async def add_guess(data):
# auth method referenced from https://www.youtube.com/watch?v=VW8qJxy4XcQ
auth = request.authorization
if auth and auth.username and auth.password:
db = await _get_write_db()
currGame = dataclasses.asdict(data)
# checks whether guessed word is the answer for that game
isAnswer = await db.fetch_one(
"SELECT * FROM answer as a where (select count(*) from games where gameid = :gameid and answerid = a.answerid)>=1 and a.answord = :word;",
currGame,
)
# is guessed word the answer
if isAnswer is not None and len(isAnswer) >= 1:
# update game status
try:
await db.execute(
"""
UPDATE game set gstate = :status where gameid = :gameid
""",
values={"status": "Finished", "gameid": currGame["gameid"]},
)
except sqlite3.IntegrityError as e:
abort(404, e)
return {
"guessedWord": currGame["word"],
"Accuracy": "\u2713" * 5,
}, 201 # should return correct answer?
# if 1 then word is valid otherwise it isn't valid and also check if they exceed guess limit
isValidGuess = await db.fetch_one(
"SELECT * from valid_word where valword = :word;",
values={"word": currGame["word"]},
)
if isValidGuess is None:
isValidGuess = await db.fetch_one(
"SELECT * from answer where answord = :word;",
values={"word": currGame["word"]},
)
guessNum = await db.fetch_one(
"SELECT guesses from game where gameid = :gameid",
values={"gameid": currGame["gameid"]},
)
accuracy = ""
if isValidGuess is not None and len(isValidGuess) >= 1 and guessNum[0] < 6:
try:
# make a dict mapping each character and its position from the answer
answord = await db.fetch_one(
"SELECT answord FROM answer as a, games as g where g.gameid = :gameid and g.answerid = a.answerid",
values={"gameid": currGame["gameid"]},
)
ansDict = {}
for i in range(len(answord[0])):
ansDict[answord[0][i]] = i
# compare location of guessed word with answer
guess_word = currGame["word"]
for i in range(len(guess_word)):
if guess_word[i] in ansDict:
# print(ansDict.get(guess_word[i]))
if ansDict.get(guess_word[i]) == i:
accuracy += "\u2713"
else:
accuracy += "O"
else:
accuracy += "X"
# insert guess word into guess table with accruracy
await db.execute(
"INSERT INTO guess(gameid,guessedword, accuracy) VALUES(:gameid, :guessedword, :accuracy)",
values={
"guessedword": currGame["word"],
"gameid": currGame["gameid"],
"accuracy": accuracy,
},
)
# update game table's guess variable by decrementing it
await db.execute(
"""
UPDATE game set guesses = :guessNum where gameid = :gameid
""",
values={
"guessNum": (guessNum[0] + 1),
"gameid": currGame["gameid"],
},
)
# if after updating game number of guesses reaches max guesses then mark game as finished
if guessNum[0] + 1 >= 6:
# update game status as finished
await db.execute(
"""
UPDATE game set gstate = :status where gameid = :gameid
""",
values={"status": "Finished", "gameid": currGame["gameid"]},
)
return "Max attempts.", 202
except sqlite3.IntegrityError as e:
abort(404, e)
else:
# should return msg saying invalid word?
return {"Error": "Invalid Word"}
return {"guessedWord": currGame["word"], "Accuracy": accuracy}, 201
else:
return (
{"error": "User not verified"},
401,
{"WWW-Authenticate": 'Basic realm = "Login required"'},
)
@app.route("/allgames", methods=["GET"])
async def all_games():
# auth method referenced from https://www.youtube.com/watch?v=VW8qJxy4XcQ
auth = request.authorization
if auth and auth.username and auth.password:
dbList = await _get_read_dbs()
print("dbList: " + str(dbList))
db = random.choice(dbList)
print("db: " + str(db))
games_val = await db.fetch_all(
"SELECT * FROM game as a where gameid IN (select gameid from games where username = :username) and a.gstate = :gstate;",
values={"username": auth.username, "gstate": "In-progress"},
)
if games_val is None or len(games_val) == 0:
return {"Message": "No Active Games"}, 406
return list(map(dict, games_val))
else:
return (
{"error": "User not verified"},
401,
{"WWW-Authenticate": 'Basic realm = "Login required"'},
)
@app.route("/onegame", methods=["GET"])
async def my_game():
# auth method referenced from https://www.youtube.com/watch?v=VW8qJxy4XcQ
auth = request.authorization
if auth and auth.username and auth.password:
dbList = await _get_read_dbs()
print("dbList: " + str(dbList))
db = random.choice(dbList)
print("db: " + str(db))
gameid = request.args.get("id")
results = await db.fetch_all(
"select * from game where gameid = :gameid",
values={"gameid": gameid},
)
guess = await db.fetch_all(
"select guessedword, accuracy from guess where gameid = :gameid",
values={"gameid": gameid},
)
if results[0][2] == "Finished":
return {"Message": "Not An Active Game"}, 406
return list(map(dict, (results + guess)))
else:
return (
{"error": "User not verified"},
401,
{"WWW-Authenticate": 'Basic realm = "Login required"'},
)
@app.errorhandler(409)
def conflict(e):
return {"error": str(e)}, 409