-
Notifications
You must be signed in to change notification settings - Fork 0
/
record.lua
98 lines (93 loc) · 2.21 KB
/
record.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
87
88
89
90
91
92
93
94
95
96
97
98
function generate_record()
record_meta = {}
record_meta.__index = {
add = function(self)
self[#self + 1] = { color = TO_PLAY, x = CURRENT.x, y = CURRENT.y, state = stones_to_str(STONES) }
end,
pass = function(self)
if #self > 0 then
self[#self + 1] = { scolor = TO_PLAY, state = self[#self].state }
end
end,
undo = function(self)
if #self == 0 then
return
elseif #self == 1 then
STONES = generate_stones()
JUST_PLAYED = { x = nil, y = nil }
self[#self] = nil
return
end
STONES = str_to_stones(self[#self - 1].state)
JUST_PLAYED = self[#self - 1]
self[#self] = nil
TO_PLAY = -TO_PLAY
end,
}
record = {}
setmetatable(record, record_meta)
return record
end
-- STONES --> n**2 str
function stones_to_str(stones)
if stones == nil then
return
end
local string = ""
for i = 1, SIZE do
for j = 1, SIZE do
if stones[i][j] ~= nil then
if stones[i][j].color == BLACK then
string = string .. "B"
elseif stones[i][j].color == WHITE then
string = string .. "W"
end
else
string = string .. "."
end
end
end
return string
end
-- --> n**2 str --> STONES
function str_to_stones(str)
if not str then
return generate_stones() -- root of game
end
local stones = {}
local index = 1
for i = 1, SIZE do
stones[i] = {}
for j = 1, SIZE do
local char = str:sub(index, index)
if char ~= "." then
if char == "W" then
stones[i][j] = { color = WHITE, x = i, y = j }
elseif char == "B" then
stones[i][j] = { color = BLACK, x = i, y = j }
end
end
index = index + 1
end
end
setmetatable(stones, stones_meta)
return stones
end
function str_pretty_print(str)
print(" -- Turn " .. #RECORD .. " --")
local transpose = {}
for i = 1, SIZE do
for j = 1, SIZE do
local k = (j - 1) * SIZE + i
if not transpose[i] then
transpose[i] = ""
end
transpose[i] = transpose[i] .. str:sub(k, k)
end
end
for i = 1, SIZE do
local pretty_row = transpose[i]:gsub(".", "%0 ")
print(pretty_row)
end
print("\n")
end