--[[
    飺ԼCе飬Զʼ
;ûˣͿʼˡڿʼ1һ֡Ʒƽ̨ͨ
vs򲻿ܣ֪ɲ
    磬һDOTAͼԶʼ-RD
    ע⣬űְ汾4.1ܴ
                        
                          ߣщ؈      ҹ
]]
--û޸Ĵ
-- ʼı
gameText = '-rd'
--ʱ
timeNum = 5
--Ƿͼؼ֣0Ϊ⣬1Ϊ
isMap = 1
--ͼؼ֣ȫڿʼ󲻴ı
map = 'DotA Allstars'
--û޸Ĵ
--ű
if getwshscriptversion() < 14 then
    msgbox('ְ汾̫ͣ')
end
if iswshfunctionenable(16) == 0 then
    msgbox('δ򿪣')
end
settimer(1000, 'StartProc')
iplay = 1
function sendMsgfunc(msg)
    hWar3 = getwar3window()
    copytexttoclipboard(msg)
    sendmessage(hWar3, 256, 13, 0)
    sleep(1)
    sendmessage(hWar3, 257, 13, 0)
    sleep(1)
    sendmessage(hWar3, 256, 17, 0)
    sleep(1)
    sendmessage(hWar3, 256, 86, 0)
    sleep(1)
    sendmessage(hWar3, 257, 17, 0)
    sleep(1)
    sendmessage(hWar3, 257, 86, 0)
    sleep(1)
    sendmessage(hWar3, 256, 13, 0)
    sleep(1)
    sendmessage(hWar3, 257, 13, 0)
end
function StartGame(key)
    --Alt + SAlt + A
    if key == 1 then
        code = 83
    else
        code = 65
    end
    hWar3 = getwar3window()
    sendmessage(hWar3, 256, 18, 0)
    sleep(1)
    sendmessage(hWar3, 256, code, 0)
    sleep(1)
    sendmessage(hWar3, 257, 18, 0)
    sleep(1)
    sendmessage(hWar3, 257, code, 0)
end
function StartProc()
    if iplay == -1 then
        iplay = 1
    end
    if 3 == getgamestatus() and iplay ~=0 then
        --ոն
        iplay = 0
        SlotID, team = getmyslotidteam()
        mapname = getmapname()
        if (isMap == 0 or string.find(mapname, map)~=nil) and SlotID == 1 then
            sleep(1000)
            sendMsgfunc(gameText)
        end
        
    elseif 0 == getgamestatus() and isHost() == 1 then
        if gethostfreeslot() > 0 then
            iplay = 1
        elseif isWaitCreat()==0 then
            iplay = iplay + 1
	    if iplay <= timeNum + 1 and isWaitStartReady() == 1 then
		sendMsgfunc(timeNum + 2 - iplay)
	    end
        end
        if gethostfreeslot() == 0 and iplay >= timeNum + 1 and isWaitStartReady() == 1 then
            StartGame(1)
        end
    elseif 1 == getgamestatus() and iplay == -1 then
        if gethostfreeslot() > 0 then
            iplay = -1
            StartGame(0)
            if 0 == iswar3front() then
                msgdlg('ˣ', 'C', 3)
            end
        end
    end
end

function isHost()
    for i = 0, 15, 1 do
        ID, IP, port, name, state = getplayerinfo(i)
        if name == '<Լ>' then
            return 0
        end
    end
    return 1
end

function isWaitCreat()
    for i = 0, 15, 1 do
        ID, IP, port, name, state = getplayerinfo(i)
        if string.len(name)~=0 then
            return 0
        end
    end
    return 1
end

function isWaitStartReady()
    for i = 0, 15, 1 do
        ID, IP, port, name, state = getplayerinfo(i)
        if 0<state and state<100 then
            return 0
        end
    end
    return 1
end