129 lines
2.9 KiB
Text
129 lines
2.9 KiB
Text
-- Lesson 28: Online. The finished script, exactly as the lesson ends.
|
|
|
|
dofile("Singe/Framework.singe")
|
|
|
|
local WAIT_MIN = 1000
|
|
local WAIT_MAX = 3000
|
|
local PERFECT = 1000
|
|
|
|
local state = "attract"
|
|
local goAt = 0
|
|
local score = 0
|
|
local best = saveGet("best", 0)
|
|
local saying = "Button 1 to play."
|
|
local top = nil
|
|
local standing = nil
|
|
|
|
|
|
local function whyNotPosted()
|
|
if not singeGetGameId() then
|
|
return "this game has no GAME_ID."
|
|
end
|
|
return "this machine is not signed in."
|
|
end
|
|
|
|
|
|
local function fetchBoard()
|
|
top = nil
|
|
standing = nil
|
|
saying = "Asking the service..."
|
|
scoreBoard(function(ok, result)
|
|
if not ok then
|
|
saying = "No board: " .. tostring(result)
|
|
return
|
|
end
|
|
top = result.top
|
|
standing = result.standing
|
|
if #top == 0 then
|
|
saying = "The board is empty. You could be first."
|
|
else
|
|
saying = ""
|
|
end
|
|
end)
|
|
end
|
|
|
|
|
|
local function finish(reaction)
|
|
score = PERFECT - reaction
|
|
if score < 0 then
|
|
score = 0
|
|
end
|
|
if score > best then
|
|
best = score
|
|
saveSet("best", best)
|
|
end
|
|
state = "result"
|
|
if scoreSubmit(score) then
|
|
fetchBoard()
|
|
else
|
|
saying = "Kept here only: " .. whyNotPosted()
|
|
end
|
|
end
|
|
|
|
|
|
local function play()
|
|
state = "waiting"
|
|
goAt = singeGetTicks() + math.random(WAIT_MIN, WAIT_MAX)
|
|
score = 0
|
|
top = nil
|
|
standing = nil
|
|
saying = ""
|
|
scoreBegin()
|
|
end
|
|
|
|
|
|
function onInputPressed(what)
|
|
if what ~= SWITCH_BUTTON1 then
|
|
return
|
|
end
|
|
if state == "waiting" then
|
|
state = "result"
|
|
score = 0
|
|
saying = "Too soon. Nothing posted."
|
|
elseif state == "go" then
|
|
finish(singeGetTicks() - goAt)
|
|
else
|
|
play()
|
|
end
|
|
end
|
|
|
|
|
|
function onOverlayUpdate()
|
|
scoreUpdate()
|
|
|
|
if state == "waiting" and singeGetTicks() >= goAt then
|
|
state = "go"
|
|
end
|
|
|
|
overlayClear()
|
|
overlayPrint(2, 0, "REACTION TEST")
|
|
|
|
if state == "attract" then
|
|
overlayPrint(2, 2, "Button 1 to play.")
|
|
elseif state == "waiting" then
|
|
overlayPrint(2, 2, "Wait for it...")
|
|
elseif state == "go" then
|
|
overlayPrint(2, 2, "NOW!")
|
|
else
|
|
overlayPrint(2, 2, "You scored " .. score .. ". Button 1 plays again.")
|
|
end
|
|
|
|
overlayPrint(2, 4, "Best on this machine: " .. best)
|
|
overlayPrint(2, 5, "Posting as: " .. (scorePlayerName() or "nobody yet"))
|
|
overlayPrint(2, 6, "Waiting to send: " .. scoreWaiting())
|
|
overlayPrint(2, 8, saying)
|
|
|
|
if top then
|
|
for place, row in ipairs(top) do
|
|
if place > 5 then
|
|
break
|
|
end
|
|
overlayPrint(2, 9 + place, place .. ". " .. row.name .. " " .. row.value)
|
|
end
|
|
end
|
|
if standing then
|
|
overlayPrint(2, 16, "You are " .. standing.rank .. " of " .. standing.players .. ".")
|
|
end
|
|
|
|
return OVERLAY_UPDATED
|
|
end
|