Module:Chess

local p = {};

function p.pagename2pgn( frame ) local pgn = frame.args[1] or '' if pgn == '' then local pagename = mw.title.getCurrentTitle.text if pagename:sub(1, 23) == "Chess Opening Theory/1." then pgn = pagename:sub(22):gsub("/", " "):gsub("[0-9]+%.%.%.", "") else return end end local enc = mw.uri.encode( pgn ) return string.format( '%s', enc, pgn ) end

-- Determines whether it's White's or Black's turn. Returns ' w' if arg contains -- three dots, ' b' if arg contains one dot, or '' otherwise. local function whoseTurn( subpagename ) local _, count = subpagename:gsub( "%.", "" ) if count == 3 then return " w" -- White elseif count == 1 then return " b" -- Black else return "" end end

-- From w:Module:Chessboard. -- Generates "rnbqkbnr/pppp1ppp/8/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R b" if args = -- {'rd','nd','bd','qd','kd','bd','nd','rd', -- 'pd','pd','pd','pd','  ','pd','pd','pd', -- '  ','  ','  ','  ','  ','  ','  ','  ', --  '  ','  ','  ','  ','pd','  ','  ','  ', -- '  ','  ','  ','  ','pl','  ','  ','  ', -- '  ','  ','  ','  ','  ','nl','  ','  ', -- 'pl','pl','pl','pl','  ','pl','pl','pl', -- 'rl','nl','bl','ql','kl','bl','  ','rl',} local function convertArgsToFen( args, offset ) local function nullOrWhitespace( s ) return not s or s:match( '^%s*(.-)%s*$' ) == '' end local function piece( s ) return nullOrWhitespace( s ) and 1 or s:gsub( '%s*(%a)(%a)%s*', function( a, b ) return b == 'l' and a:upper or a end ) end

local res = '' for row = 1, 8 do		for file = 1, 8 do res = res .. piece( args[ 8*(row-1) + file + offset ] ) end if row < 8 then res = res .. '/' end end res = mw.ustring.gsub( res, '1+', function( s ) return #s end ) return res .. whoseTurn( mw.title.getCurrentTitle.subpageText ) end

function p.ascii2fen( frame ) local fen = convertArgsToFen( frame:getParent.args, 2 ) -- args start local enc = mw.uri.encode( fen, 'WIKI' ) return string.format('%s', enc, fen) end

return p