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
| -- Nom du fichier : validateur_003.lua
-- Exercice de programmation en Lua
-- Validation d'une chaîne de caractères au format FEN
-- http://kirill-kryukov.com/chess/doc/fen.html
-- Lua 5.2
local exemples = {
-- chaînes valides
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2",
"rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2",
"4k3/8/8/8/8/8/4P3/4K3 w - - 5 39",
-- chaînes non valides
"rnbqqbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", -- qk --> qq
"rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c5 0 2", -- c6 --> c5
"rnbqkbnr/pp1ppppp/8/3p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2", -- 2p5 --> 3p5
"4k3/8/8/8/8/8/4P3/4K3 W - - 5 39" -- w --> W
}
function IsFEN(str)
t = {}
for s in string.gmatch(str, "%S+") do
t[#t + 1] = s
end
if #t ~= 6 then
return false
end
if (string.match(t[1], "k") == nil) or (string.match(t[1], "K") == nil) then
return false
end
t1 = {}
for s in string.gmatch(t[1], "[^/]+") do
t1[#t1 + 1] = s
end
if #t1 ~= 8 then
return false
end
function f(s)
local n = 0
for i = 1, string.len(s) do
if string.match(string.sub(s, i, i), "[bknpqrBKNPQR]") then
n = n + 1
elseif string.match(string.sub(s, i, i), "[12345678]") then
n = n + tonumber(string.sub(s, i, i))
end
end
return n == 8
end
for i = 1, 8 do
if not f(t1[i]) then
return false
end
end
if not ((string.len(t[2]) == 1) and string.match(t[2], "[wb]")) then
return false
end
if t[3] ~= "-" then
if string.len(t[3]) ~= string.len(string.match(t[3], "[kqKQ]+")) then
return false
end
end
if not (
(t[4] == "-") or
(string.len(t[4]) == 2) and
string.match(string.sub(t[4], 1, 1), "[abcdefgh]") and
string.match(string.sub(t[4], 2, 2), "[36]")
) then
return false
end
if (tonumber(t[5]) == nil) then
return false
end
if ((tonumber(t[6]) == nil) or (tonumber(t[6]) < 1)) then
return false
end
return true
end
for i = 1, #exemples do
print(IsFEN(exemples[i]))
end |
Partager