-
Notifications
You must be signed in to change notification settings - Fork 0
/
boggle.html
409 lines (368 loc) · 9.42 KB
/
boggle.html
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
<html>
<head><title>Boogle</title>
<style>
body {
display: grid;
grid-template-columns: 250px 340px auto;
}
section {
display: grid;
grid-template-columns: repeat(5, 72px);
grid-template-rows: repeat(5, 72px);
margin: 5px;
user-select: none;
-webkit-user-select: none;
touch-action: none;
}
section div {
width: 58px;
height: 58px;
background: #ddd;
font-size: 46px;
text-align: center;
}
.stopped section div {
background: #bbb;
}
section div[data-idx] {
background: lightblue;
}
body > div {
padding: 30px;
}
#info button { margin-bottom: 10px;}
#your-words {
display: grid;
grid-template-columns: repeat(6, 120px);
}
.overtime {
color: #a22;
}
</style>
</head>
<body>
<div id="info">
<button id="newgame">New game</button>
<button id="startover" disabled="disabled">Start over</button>
<p>Drag to form words</p>
<div>Time remaining:</div> <progress id="time" value=0 min=0 max=90></progress>
<p>Score: <span id="score"></span></p>
<p>Previous score: <span id="previousscore"></span></p>
<p>Max. posible score: <span id="possiblescore"></span></p>
</div>
<section>
<!-- divs will be added here -->
</section>
<div>Your words:
<div id="your-words">
<ul id="score-1">
</ul>
<ul id="score-2">
</ul>
<ul id="score-3">
</ul>
<ul id="score-more">
</ul>
<ul id="score-0">
</ul>
<ul id="score-overtime">
</ul>
</div>
</div>
<script src="https://jrobbins.github.io/computer-science/wordlist.js"></script>
<script>
// We want "Big boggle"
const boardSize = 5;
const wordSet = new Set(wordList);
const wordPrefixes = new Set();
for (let w of wordList) {
for (let i = 1; i < w.length; i++)
wordPrefixes.add(w.slice(0, i));
}
// Create the HTML elmements
let sectionEl = document.querySelector("section");
for (let r=0; r<boardSize; r++) {
for (let c=0; c<boardSize; c++) {
let newDiv = document.createElement('div');
newDiv.dataset['r'] = r;
newDiv.dataset['c'] = c;
sectionEl.appendChild(newDiv);
}
}
const dice = document.querySelectorAll(' section div');
const yourWordsEl = document.querySelector('#yourwords');
const bodyEl = document.querySelector('body');
// Give more common letters and fewer rare letters.
const cubes = [
'AAEEGN'.split(''),
'ABBJOO'.split(''),
'ACHOPS'.split(''),
'AFFKPS'.split(''),
'AOOTTW'.split(''),
'CIMOTU'.split(''),
'DEILRX'.split(''),
'DELRVY'.split(''),
'DISTTY'.split(''),
'EEGHNW'.split(''),
'EEINSU'.split(''),
'EHRTVW'.split(''),
'EIOSST'.split(''),
'ELRTTY'.split(''),
'H I M N U Qu'.split(' '),
'HLNNRZ'.split(''),
// More for big boggle
'MAEEGN'.split(''),
'ABBJOO'.split(''),
'ACHOPS'.split(''),
'AFFKPS'.split(''),
'AOOTTW'.split(''),
'CIMOTU'.split(''),
'DEILRX'.split(''),
'DELRVY'.split(''),
'DISTTY'.split(''),
];
function chooseOne(arr) {
let idx = Math.floor(Math.random() * arr.length);
return arr[idx];
}
function scramble(arr) {
let result = Array.from(arr);
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * i);
const temp = result[i];
result[i] = result[j];
result[j] = temp;
}
return result;
}
let timeRemaining = 0;
let score = 0;
let previousScore = null;
let running = false;
let possibleScore = 0;
// This is the list of letters that the user has selected. Each is [r, c].
let snake = [];
// This is a list of strings for the good and bad words that the user has made.
let yourWords = [];
let wordScores = [];
// Board is 4x4 matrix of random letters
let board = [];
function initializeBoard() {
board = [];
for (let r=0; r<boardSize; r++) {
board[r] = [];
for (let c=0; c<boardSize; c++) {
board[r][c] = '';
}
}
}
function fillBoard() {
let letters = [];
for (let cube of cubes) {
letters.push(chooseOne(cube));
}
const scrambledLetters = scramble(letters);
board = [];
for (let r=0; r<boardSize; r++) {
board[r] = [];
for (let c=0; c<boardSize; c++) {
board[r][c] = scrambledLetters.shift();
}
}
}
function initializeSnake() {
snake = [];
dice.forEach((die) => {
delete die.dataset.idx;})
}
function renderAtStart() {
let i = 0;
for (die of dice) {
die.innerText = board[die.dataset.r][die.dataset.c];
i++;
}
if (previousScore) {
let psEl = document.getElementById('previousscore');
psEl.innerText = previousScore;
}
}
function render() {
document.getElementById('time').value = timeRemaining;
document.getElementById('score').innerText = score;
document.getElementById('possiblescore').innerText = possibleScore;
bodyEl.className = running ? 'running' : 'stopped';
document.querySelectorAll('#your-words ul').forEach(scoreColumnEl => {
while (scoreColumnEl.firstChild) {
scoreColumnEl.removeChild(scoreColumnEl.firstChild);
}
});
for (let ws of wordScores) {
let wordItem = document.createElement('li');
let word = ws[0]; let wordScore = ws[1]; let overtime = ws[2];
wordItem.innerText = word + ': ' + wordScore;
if (wordScore == 'dup') wordScore = 0;
let scoreColumnID = '#score-' + (wordScore >= 4 ? 'more' : wordScore);
let scoreColumnEl = document.querySelector(scoreColumnID);
scoreColumnEl.appendChild(wordItem);
if (overtime) wordItem.className = 'overtime';
}
}
// Note: wordList is loaded from a separate .js file.
function computeScore(word) {
if (yourWords.includes(word)) return 'dup';
if (word.length < 3) return 0;
let valid = false;
if (wordSet.has(word)) valid = true;
if (!valid) return 0;
if (word.length == 3) return 1;
if (word.length >= 8) return 11;
return word.length - 3;
}
function visit(r, c, wordSoFar, visitedRC, foundWords) {
if (!board[r] || !board[r][c]) return 0;
let rc = r + ',' + c;
if (visitedRC.has(rc)) return 0;
wordSoFar += board[r][c].toLowerCase();
let wordScore = computeScore(wordSoFar);
if (wordScore) {
foundWords.add(wordSoFar);
}
if (wordPrefixes.has(wordSoFar)) {
visitedRC.add(rc);
visit(r-1, c-1, wordSoFar, visitedRC, foundWords);
visit(r-1, c, wordSoFar, visitedRC, foundWords);
visit(r-1, c+1, wordSoFar, visitedRC, foundWords);
visit(r, c-1, wordSoFar, visitedRC, foundWords);
visit(r, c+1, wordSoFar, visitedRC, foundWords);
visit(r+1, c-1, wordSoFar, visitedRC, foundWords);
visit(r+1, c, wordSoFar, visitedRC, foundWords);
visit(r+1, c+1, wordSoFar, visitedRC, foundWords);
visitedRC.delete(rc);
}
return foundWords;
}
function findAllWords() {
yourWords = [];
wordScores = [];
let foundWords = new Set();
for (let r=0; r<boardSize; r++) {
for (let c=0; c<boardSize; c++) {
visit(r, c, '', new Set(), foundWords);
}
}
possibleScore = 0;
for (let w of foundWords) possibleScore += computeScore(w);
console.log(foundWords);
return foundWords;
}
initializeBoard()
renderAtStart();
function startOver() {
timeRemaining = 90;
initializeSnake();
yourWords = [];
wordScores = [];
previousScore = score;
score = 0;
bestWordScore = 0;
running = true;
renderAtStart();
document.getElementById('startover').disabled = '';
}
function newGame() {
fillBoard();
findAllWords();
startOver();
}
document.getElementById('newgame').addEventListener('click', newGame);
document.getElementById('startover').addEventListener('click', startOver);
function gameLoop() {
if (!running) return;
if (running) {
timeRemaining--;
}
if (timeRemaining <= 0) {
running = false;
}
render();
}
setInterval(gameLoop, 1000);
function pushSnake(die) {
die.dataset.idx = snake.length;
let r = Number(die.dataset.r);
let c = Number(die.dataset.c);
snake.push([r, c]);
}
function startLetter(e) {
e.target.releasePointerCapture(e.pointerId);
if (snake.length > 0) {
initializeSnake();
}
let die = e.target;
pushSnake(die);
}
function dragLetter(e) {
if (e.pointerType == 'mouse' && !e.buttons) return;
let die = e.target;
let idx = die.dataset.idx;
if (idx === undefined) {
// The user is adding a letter
let tail = snake[snake.length - 1];
// Can only add a neighbor
let r = Number(die.dataset.r);
let c = Number(die.dataset.c);
if (tail === undefined ||
r >= tail[0] - 1 &&
r <= tail[0] + 1 &&
c >= tail[1] - 1 &&
c <= tail[1] + 1) {
pushSnake(die);
}
}
else {
// The user is backing up
while (idx < snake.length - 1) {
let tail = snake.pop();
let tailDie = document.querySelector('[data-idx="' + snake.length + '"]');
delete tailDie.dataset.idx;
}
}
}
function recordWord(word) {
let wordScore = computeScore(word);
if (wordScore != 'dup' && timeRemaining > 0)
score += wordScore;
yourWords.push(word);
wordScores.push([word, wordScore, timeRemaining <= 0]);
render();
}
function considerWord(word) {
let wordScore = computeScore(word);
if (wordScore > 0) {
recordWord(word);
}
return wordScore;
}
function finishWord(e) {
let word = '';
let wordScore = 0;
let diceArray = Array.from(dice);
for (let rc of snake) {
let index = rc[0] * boardSize + rc[1];
let die = diceArray[index];
word += die.innerText.toLowerCase();
wordScore = considerWord(word, false);
}
if ((wordScore == 0 || wordScore == 'dup') && word.length > 2) {
recordWord(word);
}
initializeSnake();
}
dice.forEach((die) => {
die.addEventListener('pointerdown', startLetter);
die.addEventListener('pointerenter', dragLetter);
die.addEventListener('pointerup', finishWord);
});
</script>
</body>
</html>