-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboggle_old.py
706 lines (606 loc) · 23.1 KB
/
boggle_old.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
from flask import render_template
import sys, cgi, json, datetime, re, os, time, decimal, subprocess, random
from nav import nav #file in same dir
LOGIN = 0
LOBBY = 1
JOIN_GAME = 2
VIEW_GAME = 3
PLAY_GAME = 4
GAME_OVER = 5
ROOT_DIR = "/srv/boggle_old"
GAMES_FILE = os.path.join(ROOT_DIR, "games.json")
GAME_DURATION = 3 * 60 * 1000 #3 minutes in milliseconds
formMethod = "get"
def header():
return render_template("header.html", nav=nav, active="boggle")
def footer():
return render_template("footer.html")
#replace quotes
def rq(s):
return s.replace("'", "'").replace('"', '"')
#return cgi.escape(s).replace("'", "'").replace('"', '"')
def create(size=5):
#all the dice found in boggle deluxe
dice = [
['O','O','O','T','T','U'],
['D','H','H','N','O','T'],
['N','O','U','T','O','W'],
['A','A','A','S','F','R'],
['A','E','E','M','U','G'],
['A','E','N','N','M','G'],
['A','D','E','N','N','N'],
['D','D','N','R','L','O'],
['C','C','T','S','N','W'],
['F','S','I','P','R','Y'],
['A','E','E','E','E','M'],
['I','R','R','P','H','Y'],
['E','O','T','T','T','M'],
['A','A','F','I','S','R'],
['D','O','L','H','N','R'],
['C','E','S','P','T','I'],
['A','A','E','E','E','E'],
['E','I','I','I','T','T'],
['A','F','I','S','R','Y'],
['C','E','P','I','T','L'],
['E','N','S','S','S','U'],
['C','E','I','I','L','T'],
['D','H','H','O','L','R'],
['G','O','V','R','R','W'],
['K','Z','X','B','J','Qu']
]
if size > 5:
size = 5
#the empty board
board = []
numbers = [] #the order of the dice
for i in range(len(dice)): #randomize the dice order
numbers.insert(random.randint(0, i),i)
for i in range(size):
row = []
for j in range(size): #for each board spot
letter = dice[numbers[i*size+j]][random.randint(0,5)] #roll the dice
row.append(letter) #set the letter on the board
board.append(row)
return [board]
#x, y: the current position on the board
#word: the current word
#used: the spots the word has letters from
def solve_aux(x, y, word, used, board, words, found, size):
myused = []
for item in used: #copy used to myused
myused.append(item)
myused.append([x,y]); #use the current spot
myword = word + board[x][y].lower() #add on to the word
if myword in words: #if the word is in the list of possible words
found.append(myword)
words.remove(myword)
if not any(re.search("^" + myword, word) for word in words):
return
for newx in range(x-1,x+2):
for newy in range(y-1,y+2):
if (newx>=0 and newy>=0 and newx<size and newy<size and not [newx,newy] in myused):
solve_aux(newx, newy, myword, myused, board, words, found, size)
def solve(game, minWordLength):
board = game[0]
size = len(board)
#the boggle alphabet
alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','P','Qu','R','S','T','U','V','W','X','Y','Z']
quantities = [] #the quantities of each letter
excluded = [] #which letters are not on the board
for letter in alphabet:
excluded.append(letter) #copy the alphabet to excluded
quantities.append(0) #fill quantities with 0's
for letter2 in alphabet:
excluded.append(letter + letter2)
for x in range(size):
for y in range(size):
letter = board[x][y]
quantities[alphabet.index(letter)] += 1 #increase the quantity of the letter
if letter in excluded: #if the letter is in excluded
excluded.remove(letter) #remove the letter from excluded
if letter == 'Qu' and 'U' in excluded: #if the letter is in excluded
excluded.remove('U') #remove the letter from excluded
for newx in range(x-1,x+2):
for newy in range(y-1,y+2):
if (newx>=0 and newy>=0 and newx<size and newy<size
and not (newx == x and newy == y)):
newletter = board[newx][newy]
seq = letter + newletter
if seq in excluded: #if the sequence is in excluded
excluded.remove(seq) #remove the sequence from excluded
if letter == 'Qu':
seq = 'U' + newletter
if seq in excluded: #if the sequence is in excluded
excluded.remove(seq) #remove the sequence from excluded
#increase the number of U's by the number of Qu's
quantities[alphabet.index('U')] += quantities[alphabet.index('Qu')]
words = [] #the list of possible words
for line in open(ROOT_DIR + "/lists/list.txt", 'r'): #sort through each word
line = line.strip() #remove the newline
if len(line) >= minWordLength: #if the word is long enough
#if the word does not have too many of any letter
if not any(line.count(alphabet[i].lower()) > quantities[i] for i in range(len(alphabet))):
#if there are no letters not on the board in this word
if not any(letter.lower() in line for letter in excluded):
words.append(line); #add the word to the list of possible words
score = 0
numwords = 0
found = []
for x in range(size):
for y in range(size):
used = []
word = ""
solve_aux(x, y, word, used, board, words, found, size)
return [board, found]
def tableRow(row, tableItem='td'):
text = ''
for item in row:
text += '<'+tableItem+'>' + item + '</'+tableItem+'>'
return '<tr>' + text + '</tr>'
def table(rows, properties, head=True):
text = '<table '+properties+'>\n'
if head:
text += '<thead>'
text += tableRow(rows[0], 'th') + '\n'
text += '</thead>'
rows = rows[1:]
text += '<tbody>'
for row in rows:
text += tableRow(row) + '\n'
text += '</tbody>'
return text + '</table>'
def page(form):
text = ""
games = json.load(open(GAMES_FILE, 'r'))
#form = cgi.FieldStorage()
if "action" in form:
action = int(form["action"])
else:
action = LOBBY
if not "username" in form:
text += header()
text += '<h1>Boggle</h1>'
text += '<p>Boggle is a word game with a grid of random letters. The goal is to find letters next to each other that form words. The game lasts 3 minutes and the person with the highest score (longer words are worth more) at the end wins.</p>'
text += '<h3>Enter your nickname</h3>'
text += '<form method="' + formMethod + '">'
text += '<input type="text" name="username" required>'
text += '<input type="submit" value="Enter" required>'
text += '<input type="hidden" name="action" value="'+str(LOBBY)+'">'
text += '</form>'
text += footer()
return text
username = form["username"]
if action == VIEW_GAME:
text += header()
text += '<h1>Boggle</h1>'
text += '<h3>Past Game</h3>'
myGameID = 0
username = ""
if len(sys.argv) == 3:
myGameID = sys.argv[1]
username = sys.argv[2]
else:
myGameID = int(form["gameID"])
username = form["username"]
myGame = []
for game in games:
gameID = game[0]
if myGameID == gameID:
break
myGame = game
board = myGame[5]
size = myGame[2]
size2 = int(size[0])
players = myGame[7]
playerWords = myGame[8]
host = myGame[1][0]
text += '<a href="?username=' + rq(username) + '">Back to Lobby</a>'
text += "<h4>Game hosted by " + rq(host) + ".</h4>"
text += "<table cellpadding=10><tr><td>"
text += display(board, 0)
text += "</td><td>"
text += """<table border=1 cellpadding=7>
<tr><td>Players:</td>"""
for player in players:
text += '<td>' + rq(player) + '</td>'
text += '</tr><tr><td valign="top" style="vertical-align:top">Words:</td>'
allPlayerWords = []
for words in playerWords:
text += '<td valign="top" style="vertical-align:top">'
words.sort()
score = 0
numwords = 0
for word in words:
allPlayerWords.append(word)
points = calculatePoints(word)
text += ("%2d" %(points)) + " " + word + "<br>"
score += points
numwords += 1
text += "Word Count: " + str(numwords) + "<br>"
text += "Total Score: " + str(score) + "<br>"
text += '</td>'
text += "</tr></table></td></tr></table>"
text += "<br>All possible words for this board:<br><br>"
if(len(myGame) > 6):
words = myGame[6]
words.sort()
found = 0
total = len(words)
score = 0
numwords = 0
for word in words:
if word in allPlayerWords:
text += '<span style="color:green; font-weight:bold">'
found += 1
points = calculatePoints(word)
text += ("%2d" %(points)) + " " + word + "<br>"
score += points
numwords += 1
if word in allPlayerWords:
text += "</span>"
text += "Word Count: " + str(numwords) + "<br>"
text += "Total Score: " + str(score) + "<br>"
percent = int(found*100.0/total+0.5)
text += str(percent) + "% of all these words were found."
text += footer()
if action == JOIN_GAME:
myGame = []
myGameID = 0
size = ""
if "gameID" in form:
myGameID = int(form["gameID"])
for game in games:
gameID = game[0]
if myGameID == gameID:
myGame = game
size = myGame[2]
break
else:
size = form["size"]
myGameID = 0;
while any(myGameID == game[0] for game in games):
myGameID += 1
myGame = [myGameID, [username], size, 0]
games.append(myGame)
size2 = int(size[0])
if len(myGame) < 6:
minWordLength = 4
if size == "4x4":
minWordLength = 3
game = create(size2)
game = solve(game, minWordLength)
myGame.append(-1)
myGame.extend(game)
myGame.append([])
myGame.append([])
json.dump(games, open(GAMES_FILE, 'w'))
if myGame == []:
action = LOBBY
players = myGame[1]
host = players[0]
if not myGame[3] == 0:
if username in players:
text += play(username, size, myGameID)
else:
action = LOBBY
if not username in players:
players.append(username)
json.dump(games, open(GAMES_FILE, 'w'))
minWordLength = "Four"
if size == "4x4":
minWordLength = "Three"
text += header()
text += """<h1>Boggle</h1><h4>New Game hosted by """ + rq(host) + ".<br><br>" + rq(size) + " Board, " + rq(minWordLength) + """ letter
words or more.</h4>
<p>Waiting for players...</p>
<form action="">
<input type="hidden" name="username" value='""" + username + """'>
<input type="hidden" name="size" value='""" + size + """'>
<input type="hidden" name="gameID" value='""" + str(myGameID) + """'>
<input type="hidden" name="action" value='""" + str(JOIN_GAME) + """'>
<input type="submit" value="Refresh">
</form>
<br>
<table border=1 cellpadding=7>
<tr><td>Players:</td></tr>"""
for player in players:
text += '<tr><td>' + player + '</td></tr>'
text += "</table><br>"
if username == host:
text += """<form action="">
<input type="hidden" name="username" value='""" + username + """'>
<input type="hidden" name="action" value='""" + str(PLAY_GAME) + """'>
<input type="hidden" name="size" value='""" + size + """'>
<input type="hidden" name="gameID" value='""" + str(myGameID) + """'>
<input value="Start Game" type="submit">
</form>"""
else:
text += """<script>
setTimeout(function(){
window.location.reload(1);
}, 3000);
</script>"""
text += footer()
if action == PLAY_GAME:
size = form["size"]
myGameID = int(form["gameID"])
myGame = []
for game in games:
gameID = game[0]
if myGameID == gameID:
break
myGame = game
if myGame[3] == 2:
text += header()
text += """Content-type: text/html
<!DOCTYPE html>
<html>
<head>
<script>
window.location = '?username=""" + username + """';
</script>
<link rel="stylesheet" type="text/css" href="../stylesheet.css" media="all"/>
</head>
</html>"""
return text
myGame[3] = 1
players = myGame[1]
host = players[0]
if username == host and myGame[4] == -1:
myGame[4] = time.time() * 1000
json.dump(games, open(GAMES_FILE, 'w'))
minWordLength = "Four"
if size == "4x4":
minWordLength = "Three"
text += header()
text += """<h1>Boggle</h1><h4>Game hosted by """ + rq(host) + ".<br><br>" + size + " Board, " + minWordLength + """ letter
words or more.</h4>
<p>The game has started! Good luck, """ + rq(username) + '!</p><h4><p id="time"></p></h4>'
#"""
board = myGame[5]
text += display(board, 1)
text += """<form action="" id="words" name="words">
<input type="hidden" name="action" value='""" + str(GAME_OVER) + """'>
<input type="hidden" name="username" value='""" + username + """'>
<input type="hidden" name="size" value='""" + size + """'>
<input type="hidden" name="gameID" value='""" + str(myGameID) + """'>
<h1><table cellpadding=13 cellspacing=3>
<tr><td background="/static/boggle_old/space.bmp">
<a style="text-decoration:none;color:#000000" href="javascript:type(' ')">
Space</a></td>
<td background="/static/boggle_old/backspace.bmp">
<a style="text-decoration:none;color:#000000" href="javascript:backspace()">
Backspace</a></td></tr></table></h1>
<textarea rows="20" cols="75" name="words" id="wordBox">
</textarea>
</form>
<script>
var startTime = """ + str(myGame[4]) + """;
var endTime = startTime + """ + str(GAME_DURATION) + """;
countDown();
function type(letter){
document.getElementById("wordBox").value += letter;
}
function backspace(){
var box = document.getElementById("wordBox").value.slice(0, -1);
document.getElementById("wordBox").value = box;
}
function countDown(){
time = new Date().getTime();
timeLeft = Math.ceil((endTime - time) / 1000);
millis = timeLeft;
minutes = Math.floor(millis / 60);
seconds = millis % 60;
if(minutes < 10){
minutes = "0" + minutes;
}
if(seconds < 10){
seconds = "0" + seconds;
}
document.getElementById("time").innerHTML = minutes + ":" + seconds;
if(millis <= 0){
clearTimeout(timer);
document.getElementById("time").innerHTML = "Time's up!";
document.forms.words.submit();
}
var timer = setTimeout("countDown()", 1000);
}
</script>"""
text += footer()
if action == GAME_OVER:
size = form["size"]
myGameID = int(form["gameID"])
if "words" in form:
wordBox = form["words"].lower()
words = re.split("\s|\n|,", wordBox)
else:
words = []
myGame = []
for game in games:
gameID = game[0]
if myGameID == gameID:
break
myGame = game
myGame[3] = 2
size2 = int(size[0])
players = myGame[1]
host = players[0]
if not username in myGame[7]:
allWords = myGame[6]
validWords = []
for word in words:
if word in allWords and not word in validWords:
validWords.append(word)
myGame[7].append(username)
myGame[8].append(validWords)
json.dump(games, open(GAMES_FILE, 'w'))
text += header()
text += """<script>
function redirect() {
window.location = '?action=""" + str(VIEW_GAME) + "&gameID=" + str(gameID) + "&username=" + username + """';
}
setTimeout(redirect, 5000);
</script>
<h2>
Redirect in 5 seconds...
</h2>"""
text += footer()
if action == LOBBY:
lobbyStartTime = time.time()
text += header()
text += '<script type="text/javascript" src="/static/sorttable.js"></script>'
text += '<h1>Boggle Lobby</h1>'
text += '<p>Welcome, ' + username + '!'
text += '<form method="' + formMethod + '">'
text += '<input type="hidden" name="username" value="'+username+'">'
text += '<input type="hidden" name="action" value="'+str(LOBBY)+'">'
text += '<input type="hidden" name="skip" value="'+str(True)+'">'
text += '<input type="submit" value="Refresh" required>'
text += '</form><br/>'
text += '<p>You can join one of these games:</p>'
text += '<form method="' + formMethod + '">'
text += '<input type="hidden" name="action" value="'+str(JOIN_GAME)+'">'
text += '<input type="hidden" name="username" value="'+username+'">'
rows = []
disabled = "disabled "
checked = "checked "
for game in games:
state = game[3]
if state == 0:
gameID = game[0]
host = game[1][0]
size = game[2]
players = len(game[1])
if checked == "checked ":
rows.append(["Select", "Host", "Size", "Players"])
rows.append(['<input type="radio" ' + checked + 'name="gameID" value="' + str(gameID) + '">',
host, size, str(players)])
checked = ""
disabled = ""
if disabled == "disabled ":
text += '<p><b>No games are waiting for players.</b></p>'
else:
text += table(rows, 'border=1 cellpadding=7 id="waiting" class="sortable"')
text += '<br/>'
text += '<input value="Join Game" type="submit" ' + disabled + '>'
text += '</form><br/><br/>'
text += '<p>Or you can create a new game:</p>'
text += '<form method="' + formMethod + '">'
text += '<input type="hidden" name="action" value="'+str(JOIN_GAME)+'">'
text += '<input type="hidden" name="username" value="'+username+'">'
text += """<select name="size">
<option>5x5</option>
<option>4x4</option>
</select>"""
text += '<input value="Create Game" type="submit" id="create">'
text += '</form><br/>'
text += '<p>Games in progress:</p>'
any1 = 0
for game in games:
state = game[3]
startTime = game[4]
if state == 1 and time.time() * 1000 > startTime + GAME_DURATION:
game[3] = 2
any1 = 1
if any1 == 1:
json.dump(games, open(GAMES_FILE, 'w'))
rows = []
any1 = 0
for game in games:
state = game[3]
if state == 1:
gameID = game[0]
host = game[1][0]
size = game[2]
players = len(game[1])
if any1 == 0:
rows.append(["Host", "Size", "Players"])
rows.append([host, size, str(players)])
any1 = 1
if any1 == 0:
text += '<p><b>No games are in progress.</b></p>'
else:
text += table(rows, 'border=1 cellpadding=7 id="playing" class="sortable"')
text += '<br/><br/>'
text += '<p>Games that are over:</p>'
text += '<p>Click on a column to sort by that column</p>'
rows = []
rows.append(["Game #", "Host", "Size", "Players", "Total # of Words", "# of Words Found", "% of Words Found"])
length = len(games)
for i in range(length-1, -1, -1):
game = games[i]
state = game[3]
if state == 2:
gameID = game[0]
host = game[1][0]
size = game[2]
players = len(game[1])
allWords = game[6]
allPlayerWords = []
allPlayerWordLists = game[8]
found = 0
for playerWords in allPlayerWordLists:
for word in playerWords:
if not word in allPlayerWords:
allPlayerWords.append(word)
found += 1
percent = int(found*10000.0/len(allWords)+0.5)/100.0
percentStr = str(decimal.Decimal(percent).quantize(decimal.Decimal('0.01')))+"%"
rows.append(['<a href="?gameID=' + str(gameID) + '&username=' + username + '&action=' + str(VIEW_GAME) + '">' + str(gameID) + '</a>', host,
size, str(players), str(len(allWords)), str(found), percentStr])
text += table(rows, 'border=1 cellpadding=7 id="over" class="sortable"')
text += '<p>It took ' + str(time.time() - lobbyStartTime) + ' seconds to load the lobby.</p>'
text += footer()
return text
def display(board, buttons):
text = ""
size = len(board)
text += '<h1><font color="black"><table style="background-color:black" bgcolor="black">'
for i in range(size):
text += "<tr>"
for j in range(size):
letter = board[i][j]
if letter == "Qu":
space = ""
else:
space = " "
if buttons == 1:
letter = '<a style="text-decoration:none;color:#000000" href="javascript:type(\'' + letter.lower() + '\')">' + letter + '</a>'
text += '<td width="62" height="62" background="/static/boggle_old/letter.bmp"> ' + space + letter + "</td>"
text += "</tr>"
text += "</table></font></h1>"
return text
def calculatePoints(word):
length = len(word)
if length < 7:
points = length - 3
elif length == 7:
points = 5
else:
points = 11
if points < 1:
points = 1;
return points
def lobby(username):
return """Content-type: text/html
<!DOCTYPE html>
<html>
<head>
<script>
window.location = '?username=""" + username + """';
</script>
<link rel="stylesheet" type="text/css" href="../stylesheet.css" media="all"/>
</head>
</html>"""
def play(username, size, myGameID):
return """Content-type: text/html
<!DOCTYPE html>
<html>
<head>
<script>
window.location = '?username=""" + str(username) + "&action=" + str(PLAY_GAME) + "&size=" + str(size) + "&gameID=" + str(myGameID) + """';
</script>
<link rel="stylesheet" type="text/css" href="../stylesheet.css" media="all"/>
</head>
</html>"""