-
Notifications
You must be signed in to change notification settings - Fork 1
/
ai.lua
86 lines (75 loc) · 1.85 KB
/
ai.lua
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
require("wordlookup")
function take(table, n)
result = {}
for i=0, n do
result[#result + 1] = table[i]
end
return result
end
function concat(t1,t2)
for i=1,#t2 do
t1[#t1+1] = t2[i]
end
return t1
end
local function getAdjacentTiles(x, y, board)
local result = {}
for newX=(x - 1),(x + 1) do
for newY=(y - 1),(y + 1) do
local sameTile = newX == x and newY == y
local inBounds = (newX >= 1 and newX <= #board) and (newY >= 1 and newY <= #(board[1]))
if not sameTile and inBounds then
result[#result + 1] = {x=newX, y=newY}
end
end
end
return result
end
function inBoard(word, board, x, y)
if word == "" then
return true
end
if string.lower(board[x][y]) == string.sub(word, 1, 1) then
local adjacentTiles = getAdjacentTiles(x, y, board)
for i=1, #adjacentTiles do
local tile = adjacentTiles[i]
if inBoard(string.sub(word, 2), board, tile['x'], tile['y']) then
return true
end
end
end
return false
end
local function allWords(board, words)
local result = {}
for x=1, #board do
for y=1, #(board[1]) do
for i=1,#words do
if inBoard(words[i], board, x, y) then
result[#result + 1] = words[i]
end
end
end
end
local longest = 0
local longestWord = nil
for k, v in pairs(result) do
if string.len(v) > longest then
longest = string.len(v)
longestWord = v
end
end
if not longestWord then
return ""
end
return longestWord
end
function makeMove(board, words, difficulty)
if difficulty == 1 then
words = take(words, 1000)
end
if difficulty == 2 then
words = take(words, 10000)
end
return allWords(board, words)
end