OXT Community Stacks

The scripts of 2048

Version 1.0. These are the scripts exactly as they are in the stack that plays here. Each line has its number, and a link to a line keeps it.

14 scripts in this stack
  1. card id 1002 (card 1) 2048, 518 lines
  2. button "View script" (card 1) 2048, 9 lines
  3. button "OverButton" (card 1) 2048, 5 lines
  4. button "New game" (card 1) 2048, 5 lines
  5. button "Undo" (card 1) 2048, 5 lines
  6. the stack script 2048 Script Viewer, 28 lines
  7. card "Viewer" (card 1) 2048 Script Viewer, 369 lines
  8. field "svObjects" (card 1) 2048 Script Viewer, 5 lines
  9. button "svOnly" (card 1) 2048 Script Viewer, 5 lines
  10. field "svCode" (card 1) 2048 Script Viewer, 5 lines
  11. button "svCopy" (card 1) 2048 Script Viewer, 4 lines
  12. button "svShowMe" (card 1) 2048 Script Viewer, 4 lines
  13. button "svEdit" (card 1) 2048 Script Viewer, 5 lines
  14. button "svClose" (card 1) 2048 Script Viewer, 4 lines

card id 1002 (card 1)

2048.oxtstack, stack "2048", 518 lines

-- 2048: slide the tiles, join equal ones, and reach 2048.
--
-- Each tile is a rounded graphic with a field on it, taken from a pool of
-- twenty on the card. A move works out where every tile ends up, then a
-- timer slides them there a few pixels at a time; tiles that join pop, and
-- a new tile grows in an empty cell. The best score is written to a file:
-- in a browser it is kept in the page's own storage between visits.

constant kSize = 104
constant kGap = 12
constant kLeft = 40
constant kTop = 96
constant kPool = 20
constant kFrames = 7
constant kBestFile = "2048-best.txt"

local sCell, sTileAt, sTileUsed, sScore, sBest, sMoves, sWon
local sUndoCell, sUndoScore, sCanUndo
local sSlides, sMerged, sGone, sFrame, sTimer, sBusy, sPending, sDownAt, sOver

on preOpenCard
   if sScore is empty then
      put tfLoadBest() into sBest
      tfNewGame
   end if
end preOpenCard

on closeCard
   if sTimer is not empty then cancel sTimer
   put empty into sTimer
   put false into sBusy
end closeCard

command tfNewGame
   local c
   repeat with c = 1 to 16
      put 0 into sCell[c]
      put 0 into sTileAt[c]
   end repeat
   repeat with c = 1 to kPool
      put false into sTileUsed[c]
      set the visible of graphic ("tile" & c) to false
      set the visible of field ("num" & c) to false
   end repeat
   put 0 into sScore
   put 0 into sMoves
   put false into sWon
   put false into sCanUndo
   put false into sOver
   put false into sBusy
   put empty into sPending
   set the visible of group "Over" to false
   tfSpawn false
   tfSpawn false
   tfShowScore
end tfNewGame

-- Cells are numbered 1 to 16, row by row.
function tfX pCell
   return kLeft + kGap + ((pCell - 1) mod 4) * (kSize + kGap) + kSize div 2
end tfX

function tfY pCell
   return kTop + kGap + ((pCell - 1) div 4) * (kSize + kGap) + kSize div 2
end tfY

-- The cell at place pPlace (1 is the edge the tiles slide to) of line
-- pLine, for a move in direction pDir.
function tfLineCell pDir, pLine, pPlace
   switch pDir
      case "left"
         return (pLine - 1) * 4 + pPlace
      case "right"
         return (pLine - 1) * 4 + 5 - pPlace
      case "up"
         return (pPlace - 1) * 4 + pLine
      default
         return (4 - pPlace) * 4 + pLine
   end switch
end tfLineCell

-- The keyboard: arrows and WASD. A key pressed while tiles slide waits.
on arrowKey pKey
   tfMove pKey
end arrowKey

on keyDown pKey
   switch toLower(pKey)
      case "w"
         tfMove "up"
         break
      case "a"
         tfMove "left"
         break
      case "s"
         tfMove "down"
         break
      case "d"
         tfMove "right"
         break
      default
         pass keyDown
   end switch
end keyDown

-- A swipe on the board.
on mouseDown
   if the mouseLoc is within the rect of graphic "Board" and word 1 of the name of the target is not "button" then
      put the mouseLoc into sDownAt
   else
      put empty into sDownAt
      pass mouseDown
   end if
end mouseDown

on mouseUp
   local tDX, tDY
   if sDownAt is empty then pass mouseUp
   put item 1 of the mouseLoc - item 1 of sDownAt into tDX
   put item 2 of the mouseLoc - item 2 of sDownAt into tDY
   put empty into sDownAt
   if max(abs(tDX), abs(tDY)) < 24 then exit mouseUp
   if abs(tDX) > abs(tDY) then
      if tDX > 0 then
         tfMove "right"
      else
         tfMove "left"
      end if
   else
      if tDY > 0 then
         tfMove "down"
      else
         tfMove "up"
      end if
   end if
end mouseUp

on mouseRelease
   put empty into sDownAt
end mouseRelease

-- One move: work out where every tile goes, then slide them.
command tfMove pDir
   local tLine, tPlace, tTiles, tValues, tCount, i, tFrom, tTo, tNewCell, tNewTile, tMoved, tGain
   if pDir is not among the items of "left,right,up,down" then exit tfMove
   if sOver then exit tfMove
   if sBusy then
      put pDir into sPending
      exit tfMove
   end if
   put empty into sSlides
   put empty into sMerged
   put empty into sGone
   put false into tMoved
   put 0 into tGain
   repeat with i = 1 to 16
      put 0 into tNewCell[i]
      put 0 into tNewTile[i]
   end repeat
   repeat with tLine = 1 to 4
      -- the tiles of this line, nearest the edge first
      put 0 into tCount
      repeat with tPlace = 1 to 4
         put tfLineCell(pDir, tLine, tPlace) into tFrom
         if sCell[tFrom] > 0 then
            add 1 to tCount
            put tFrom into tTiles[tCount]
            put sCell[tFrom] into tValues[tCount]
         end if
      end repeat
      put 1 into tPlace
      put 1 into i
      repeat while i <= tCount
         put tfLineCell(pDir, tLine, tPlace) into tTo
         if i < tCount and tValues[i] = tValues[i + 1] then
            -- two equal tiles join: the first stays, the second goes
            put tValues[i] * 2 into tNewCell[tTo]
            put sTileAt[tTiles[i]] into tNewTile[tTo]
            put sTileAt[tTiles[i]] & comma & tTiles[i] & comma & tTo & return after sSlides
            put sTileAt[tTiles[i + 1]] & comma & tTiles[i + 1] & comma & tTo & return after sSlides
            put sTileAt[tTiles[i]] & comma & tValues[i] * 2 & return after sMerged
            put sTileAt[tTiles[i + 1]] & return after sGone
            add tValues[i] * 2 to tGain
            put true into tMoved
            add 2 to i
         else
            put tValues[i] into tNewCell[tTo]
            put sTileAt[tTiles[i]] into tNewTile[tTo]
            if tTiles[i] is not tTo then
               put sTileAt[tTiles[i]] & comma & tTiles[i] & comma & tTo & return after sSlides
               put true into tMoved
            end if
            add 1 to i
         end if
         add 1 to tPlace
      end repeat
   end repeat
   if not tMoved then exit tfMove
   -- keep the board as it was, for Undo
   put sCell into sUndoCell
   put sScore into sUndoScore
   put true into sCanUndo
   put tNewCell into sCell
   put tNewTile into sTileAt
   add tGain to sScore
   add 1 to sMoves
   if tGain > 0 then tfFloat "+" & tGain
   put true into sBusy
   put 0 into sFrame
   tfSlide
end tfMove

-- One frame of the slide, eased so the tiles slow down as they land.
on tfSlide
   local tLine, tTile, tT, tX, tY
   set the defaultStack to the short name of the owner of me
   put empty into sTimer
   add 1 to sFrame
   put 1 - (1 - sFrame / kFrames) ^ 3 into tT
   lock screen
   repeat for each line tLine in sSlides
      put item 1 of tLine into tTile
      put round(tfX(item 2 of tLine) + (tfX(item 3 of tLine) - tfX(item 2 of tLine)) * tT) into tX
      put round(tfY(item 2 of tLine) + (tfY(item 3 of tLine) - tfY(item 2 of tLine)) * tT) into tY
      set the loc of graphic ("tile" & tTile) to tX, tY
      set the loc of field ("num" & tTile) to tX, tY
   end repeat
   unlock screen
   if sFrame < kFrames then
      send "tfSlide" to me in 16 milliseconds
      put the result into sTimer
   else
      tfLand
   end if
end tfSlide

-- The tiles have landed: joined tiles pop, a new one grows.
command tfLand
   local tLine
   lock screen
   repeat for each line tLine in sGone
      put false into sTileUsed[tLine]
      set the visible of graphic ("tile" & tLine) to false
      set the visible of field ("num" & tLine) to false
   end repeat
   repeat for each line tLine in sMerged
      tfPaint item 1 of tLine, item 2 of tLine
      tfScale item 1 of tLine, 1.12
   end repeat
   tfSpawn true
   unlock screen
   send "tfSettle" to me in 70 milliseconds
   put the result into sTimer
   tfShowScore
end tfLand

on tfSettle
   local tLine, c
   set the defaultStack to the short name of the owner of me
   put empty into sTimer
   lock screen
   repeat for each line tLine in sMerged
      tfScale item 1 of tLine, 1
   end repeat
   repeat with c = 1 to 16
      if sTileAt[c] > 0 then tfScale sTileAt[c], 1
   end repeat
   unlock screen
   put false into sBusy
   tfCheckEnd
   if sPending is not empty and not sOver then
      get sPending
      put empty into sPending
      tfMove it
   end if
end tfSettle

-- A new tile in a random empty cell: a 2, or now and then a 4.
command tfSpawn pGrow
   local tEmpty, c, tCell, tTile
   repeat with c = 1 to 16
      if sCell[c] = 0 then put c & comma after tEmpty
   end repeat
   if tEmpty is empty then exit tfSpawn
   delete the last char of tEmpty
   put any item of tEmpty into tCell
   repeat with tTile = 1 to kPool
      if not sTileUsed[tTile] then exit repeat
   end repeat
   put true into sTileUsed[tTile]
   put tTile into sTileAt[tCell]
   if random(10) = 1 then
      put 4 into sCell[tCell]
   else
      put 2 into sCell[tCell]
   end if
   tfPaint tTile, sCell[tCell]
   set the loc of graphic ("tile" & tTile) to tfX(tCell), tfY(tCell)
   set the loc of field ("num" & tTile) to tfX(tCell), tfY(tCell)
   if pGrow then
      tfScale tTile, 0.45
   else
      tfScale tTile, 1
   end if
   set the visible of graphic ("tile" & tTile) to true
   set the visible of field ("num" & tTile) to true
end tfSpawn

-- A tile's size about its centre: 1 is the size of a cell.
command tfScale pTile, pScale
   local tLoc, tHalf
   put the loc of graphic ("tile" & pTile) into tLoc
   put round(kSize * pScale / 2) into tHalf
   set the rect of graphic ("tile" & pTile) to item 1 of tLoc - tHalf, item 2 of tLoc - tHalf, item 1 of tLoc + tHalf, item 2 of tLoc + tHalf
   set the loc of field ("num" & pTile) to tLoc
end tfScale

-- The colours and size of a tile's number.
command tfPaint pTile, pValue
   local tBack, tInk, tSize
   switch pValue
      case 2
         put "226,232,240" into tBack
         break
      case 4
         put "199,210,254" into tBack
         break
      case 8
         put "253,186,116" into tBack
         break
      case 16
         put "251,146,60" into tBack
         break
      case 32
         put "248,113,113" into tBack
         break
      case 64
         put "225,29,72" into tBack
         break
      case 128
         put "250,204,21" into tBack
         break
      case 256
         put "234,179,8" into tBack
         break
      case 512
         put "132,204,22" into tBack
         break
      case 1024
         put "16,185,129" into tBack
         break
      case 2048
         put "168,85,247" into tBack
         break
      default
         put "236,72,153" into tBack
   end switch
   if pValue <= 4 or pValue = 128 or pValue = 256 then
      put "30,41,59" into tInk
   else
      put "255,255,255" into tInk
   end if
   if pValue < 100 then
      put 46 into tSize
   else if pValue < 1000 then
      put 40 into tSize
   else if pValue < 10000 then
      put 32 into tSize
   else
      put 26 into tSize
   end if
   set the backgroundColor of graphic ("tile" & pTile) to tBack
   set the foregroundColor of field ("num" & pTile) to tInk
   set the textSize of field ("num" & pTile) to tSize
   set the text of field ("num" & pTile) to pValue
   set the height of field ("num" & pTile) to the formattedHeight of field ("num" & pTile)
end tfPaint

-- Is it won, or can nothing move any more?
command tfCheckEnd
   local c, tFull, tBiggest
   put 0 into tBiggest
   put true into tFull
   repeat with c = 1 to 16
      put max(tBiggest, sCell[c]) into tBiggest
      if sCell[c] = 0 then put false into tFull
   end repeat
   if tBiggest >= 2048 and not sWon then
      put true into sWon
      tfMessage "You made 2048!", "Well played, in" && sMoves && "moves.", "Keep going"
      exit tfCheckEnd
   end if
   if not tFull then exit tfCheckEnd
   repeat with c = 1 to 16
      -- a neighbour to the right or below with the same number can join
      if c mod 4 is not 0 and sCell[c] = sCell[c + 1] then exit tfCheckEnd
      if c <= 12 and sCell[c] = sCell[c + 4] then exit tfCheckEnd
   end repeat
   put true into sOver
   tfMessage "No more moves", "You scored" && sScore && "in" && sMoves && "moves.", "Try again"
end tfCheckEnd

command tfMessage pTitle, pText, pButton
   set the text of field "OverTitle" to pTitle
   set the text of field "OverText" to pText
   set the label of button "OverButton" to pButton
   set the visible of group "Over" to true
end tfMessage

-- The button on the message: try again, or carry on past 2048.
command tfOverButton
   set the visible of group "Over" to false
   if sOver then tfNewGame
end tfOverButton

-- One step back: the board before the last move.
command tfUndo
   local c, tTile
   if not sCanUndo or sBusy then exit tfUndo
   put false into sCanUndo
   put false into sOver
   set the visible of group "Over" to false
   put sUndoCell into sCell
   put sUndoScore into sScore
   subtract 1 from sMoves
   lock screen
   repeat with c = 1 to kPool
      put false into sTileUsed[c]
      set the visible of graphic ("tile" & c) to false
      set the visible of field ("num" & c) to false
   end repeat
   put 0 into tTile
   repeat with c = 1 to 16
      put 0 into sTileAt[c]
      if sCell[c] > 0 then
         add 1 to tTile
         put true into sTileUsed[tTile]
         put tTile into sTileAt[c]
         tfPaint tTile, sCell[c]
         set the loc of graphic ("tile" & tTile) to tfX(c), tfY(c)
         tfScale tTile, 1
         set the visible of graphic ("tile" & tTile) to true
         set the visible of field ("num" & tTile) to true
      end if
   end repeat
   unlock screen
   tfShowScore
end tfUndo

command tfShowScore
   local c, tBiggest, tSteps
   if sScore > sBest then
      put sScore into sBest
      tfSaveBest sBest
   end if
   set the text of field "ScoreValue" to sScore
   set the text of field "BestValue" to sBest
   set the text of field "MovesValue" to sMoves && "moves"
   if sCanUndo then
      set the blendLevel of button "Undo" to 0
   else
      set the blendLevel of button "Undo" to 55
   end if
   -- the road to 2048: one step for each doubling, eleven in all
   put 0 into tBiggest
   repeat with c = 1 to 16
      put max(tBiggest, sCell[c]) into tBiggest
   end repeat
   put min(11, round(ln(max(2, tBiggest)) / ln(2))) into tSteps
   set the width of graphic "RoadFill" to max(12, round(tSteps / 11 * the width of graphic "RoadTrack"))
   set the left of graphic "RoadFill" to the left of graphic "RoadTrack"
   set the text of field "RoadText" to "Biggest tile:" && tBiggest
end tfShowScore

-- "+16" rises from the score and fades.
command tfFloat pText
   set the text of field "Gain" to pText
   set the blendLevel of field "Gain" to 0
   set the top of field "Gain" to the top of graphic "ScoreCard" - 4
   set the visible of field "Gain" to true
   send "tfFloatStep 1" to me in 30 milliseconds
end tfFloat

on tfFloatStep pStep
   set the defaultStack to the short name of the owner of me
   set the top of field "Gain" to the top of field "Gain" - 3
   set the blendLevel of field "Gain" to pStep * 8
   if pStep < 12 then
      send "tfFloatStep" && pStep + 1 to me in 30 milliseconds
   else
      set the visible of field "Gain" to false
   end if
end tfFloatStep

-- The best score's file. In a browser, the documents folder is the page's
-- own storage, kept between visits.
function tfBestPath
   local tFolder
   if the platform is "HTML5" then
      put specialFolderPath("documents") into tFolder
   else
      put specialFolderPath("temporary") & "/oxt-2048" into tFolder
   end if
   if there is not a folder tFolder then create folder tFolder
   return tFolder & "/" & kBestFile
end tfBestPath

function tfLoadBest
   local tBest
   put word 1 of url ("file:" & tfBestPath()) into tBest
   if tBest is not an integer then put 0 into tBest
   return tBest
end tfLoadBest

command tfSaveBest pBest
   put pBest into url ("file:" & tfBestPath())
end tfSaveBest

button "View script" (card 1)

2048.oxtstack, stack "2048", 9 lines

-- Opens the Script Viewer: the scripts of this stack, in colour.
on mouseUp
   if the mode of stack "2048 Script Viewer" is not 0 then
      close stack "2048 Script Viewer"
   else
      dispatch "svOpen" to card "Viewer" of stack "2048 Script Viewer" with the short name of this stack
   end if
end mouseUp

button "OverButton" (card 1)

2048.oxtstack, stack "2048", 5 lines

-- Starts again, or carries on past 2048.
on mouseUp
   tfOverButton
end mouseUp

button "New game" (card 1)

2048.oxtstack, stack "2048", 5 lines

-- A fresh board.
on mouseUp
   tfNewGame
end mouseUp

button "Undo" (card 1)

2048.oxtstack, stack "2048", 5 lines

-- Takes the last move back (just the one).
on mouseUp
   tfUndo
end mouseUp

the stack script

2048.oxtstack, stack "2048 Script Viewer", 28 lines

-- The Script Viewer's own messages stop here, so they never reach the
-- stack it belongs to: that stack's openCard, mouseUp and arrowKey
-- handlers are for its own cards.
on preOpenStack
end preOpenStack
on openStack
end openStack
on preOpenCard
end preOpenCard
on openCard
end openCard
on closeCard
end closeCard
on closeStack
end closeStack
on mouseUp
end mouseUp
on mouseDown
end mouseDown
on arrowKey pKey
   -- up and down move through the list
   if pKey is "up" then svMove -1
   if pKey is "down" then svMove 1
end arrowKey
on escapeKey
   close this stack
end escapeKey

card "Viewer" (card 1)

2048.oxtstack, stack "2048 Script Viewer", 369 lines

-- ===== The Script Viewer =====
-- Lists the scripts of the card in front of the stack that opened it,
-- and shows the one chosen in colour: comments, strings, numbers,
-- keywords, commands and the names of handlers each in their own
-- colour, with line numbers. Any stack opens it with svOpen:
--
--    dispatch "svOpen" to card 1 of stack "2048 Script Viewer" with "My Stack"
--
-- Controls are named "of me" (this card), so these handlers work even
-- while another stack is the default stack.

-- The colours of the code, on its dark background.
constant kInk = "#E0DEF4"
constant kComment = "#7F8FA6"
constant kString = "#F6C177"
constant kNumber = "#F8A978"
constant kKeyword = "#C4A7E7"
constant kCommand = "#9CCFD8"
constant kDeclare = "#EB6F92"
constant kName = "#82AAFF"
constant kSoft = "#A6A3C4"

-- Words of each kind. A word may be in only one list.
constant kKeywords = "if,then,else,end,repeat,for,each,while,until,forever,times,switch,case,default,break,exit,next,pass,return,try,catch,finally,throw,do,send,dispatch,call,with,in"
constant kCommands = "put,set,get,go,answer,ask,create,delete,show,hide,lock,unlock,wait,add,subtract,multiply,divide,sort,replace,open,close,palette,move,play,beep,select,copy,paste,start,stop,save,write,read,launch,click,type,focus,choose,cancel,import,export,print,filter,split,combine,load,post"
constant kSoftWords = "the,of,into,after,before,and,or,not,is,a,an,to,me,it,empty,true,false,quote,space,tab,comma,cr,return,line,lines,word,words,char,chars,item,items,field,button,card,stack,graphic,group,this,target,among,contains,there"
constant kDeclares = "on,command,function,private,getprop,setprop,local,global,constant"

local sTarget    -- the name of the stack whose scripts are listed
local sIDs       -- the long id of the object on each line of the list
local sInBlock   -- true inside a /* ... */ comment while colouring

-- Open the viewer for a stack, beside its window, listing the scripts
-- of its card in front. pChoose "stack" chooses the stack script.
command svOpen pStack, pChoose
   local tR, tScreen, tHeight, tLeft, tTop
   put pStack into sTarget
   put the rect of stack pStack into tR
   put the working screenRect into tScreen
   -- As tall as the screen allows, keeping room above for the title bar,
   -- so that the window can always be dragged.
   put min(640, item 4 of tScreen - item 2 of tScreen - 44) into tHeight
   put max(440, tHeight) into tHeight
   if the height of this stack is not tHeight then
      set the height of this stack to tHeight
   end if
   svLayout
   -- To the right of the stack's window, or to its left, or over it.
   put item 3 of tR + 12 into tLeft
   if tLeft + the width of this stack > item 3 of tScreen then
      put item 1 of tR - 12 - the width of this stack into tLeft
   end if
   if tLeft < item 1 of tScreen then
      put item 3 of tR - the width of this stack - 12 into tLeft
   end if
   put max(item 1 of tScreen, tLeft) into tLeft
   -- Level with the stack, but never above the screen or off its bottom.
   put max(item 2 of tR, item 2 of tScreen + 32) into tTop
   if tTop + tHeight > item 4 of tScreen - 8 then
      put item 4 of tScreen - 8 - tHeight into tTop
   end if
   put max(tTop, item 2 of tScreen + 32) into tTop
   set the topLeft of this stack to tLeft, tTop
   -- Open first: a list field keeps its chosen line only while open.
   if the mode of this stack is 0 then
      palette this stack
   end if
   svRefresh pChoose
end svOpen

-- The window can be made shorter or taller: the list and the code share
-- the height, and the buttons stay at the bottom.
on resizeStack
   svLayout
end resizeStack

command svLayout
   local tH, tList, tY, tButton
   put the height of this stack into tH
   put max(70, 140 - max(0, 600 - tH)) into tList
   lock screen
   set the rect of field "svObjects" of me to 16, 78, 524, 78 + tList
   put 78 + tList + 4 into tY
   set the rect of button "svOnly" of me to 16, tY, 330, tY + 22
   add 28 to tY
   set the rect of field "svAbout" of me to 16, tY, 524, tY + 54
   add 62 to tY
   set the rect of field "svGutter" of me to 16, tY, 58, tH - 52
   set the rect of field "svCode" of me to 58, tY, 524, tH - 52
   repeat for each item tButton in "svCopy,svShowMe,svEdit,svClose"
      set the bottom of button tButton of me to tH - 12
   end repeat
   unlock screen
end svLayout

-- Rebuild the list for the target's card in front.
command svRefresh pChoose
   local tCard, tMain, tList, tObj, i, tOnly, tPrevious, tLine
   if sTarget is empty or there is not a stack sTarget then exit svRefresh
   -- Remember which object was chosen, to choose it again.
   put line (the hilitedLine of field "svObjects" of me) of sIDs into tPrevious
   put the long id of stack sTarget into tMain
   put the long id of this card of stack sTarget into tCard
   put sTarget & ": the card" && quote & the short name of tCard & quote into field "svSub" of me
   put the hilite of button "svOnly" of me into tOnly
   -- The stack and the card come first: they are always listed.
   put "Stack script" & tab & svCount(tMain) into tList
   put tMain into sIDs
   put return & "Card script" & tab & svCount(tCard) after tList
   put return & tCard after sIDs
   -- Then each control of the card, from the back to the front.
   repeat with i = 1 to the number of controls of tCard
      put the long id of control i of tCard into tObj
      if tOnly and the script of tObj is empty then next repeat
      put return after tList
      -- Controls in a group are indented under it.
      if word 1 of the owner of tObj is "group" then put "    " after tList
      put the name of tObj & tab & svCount(tObj) after tList
      put return & tObj after sIDs
   end repeat
   put tList into field "svObjects" of me
   -- Choose as asked, or the same object again, or else the card script.
   put 2 into tLine
   if pChoose is "stack" then
      put 1 into tLine
   else if tPrevious is not empty then
      set the wholeMatches to true
      if lineOffset(tPrevious, sIDs) > 0 then put lineOffset(tPrevious, sIDs) into tLine
   end if
   set the hilitedLine of field "svObjects" of me to tLine
   svShow
end svRefresh

-- "12 lines", or "no script".
function svCount pObj
   local tCount
   put the number of lines of the script of pObj into tCount
   if tCount is 0 then return "no script"
   if tCount is 1 then return "1 line"
   return tCount && "lines"
end svCount

-- The long id of the object chosen in the list (empty when none).
function svCurrent
   local tLine
   put the hilitedLine of field "svObjects" of me into tLine
   if tLine is empty then return empty
   return line tLine of sIDs
end svCurrent

-- Show the chosen object's script, and a word on what it is for.
command svShow
   local tObj, tScript, tNumbers, i
   put svCurrent() into tObj
   if tObj is empty then exit svShow
   if not exists(tObj) then
      -- It was deleted since the list was made.
      svRefresh
      exit svShow
   end if
   lock screen
   put svAbout(tObj) into field "svAbout" of me
   put the script of tObj into tScript
   if tScript is empty then put "-- This object has no script." into tScript
   -- htmlText sets the text and its colours in one go.
   set the htmlText of field "svCode" of me to svColoured(tScript)
   repeat with i = 1 to the number of lines of tScript
      put i & return after tNumbers
   end repeat
   put char 1 to -2 of tNumbers into field "svGutter" of me
   set the vScroll of field "svCode" of me to 0
   set the hScroll of field "svCode" of me to 0
   set the vScroll of field "svGutter" of me to 0
   unlock screen
end svShow

-- The script as htmlText, one coloured paragraph per line.
function svColoured pScript
   local tLine, tHtml
   put false into sInBlock
   repeat for each line tLine in pScript
      put "<p>" & svColourLine(tLine) & "</p>" after tHtml
   end repeat
   return tHtml
end svColoured

-- One line, coloured word by word. Walks the line a character at a
-- time: a quote starts a string, -- or # a comment to the end of the
-- line, /* a comment to */, a letter a word.
function svColourLine pLine
   local tOut, tLen, i, tChar, tStart, tWord, tPrev, tEnd
   put the number of chars of pLine into tLen
   put 1 into i
   if sInBlock then
      put offset("*/", pLine) into tEnd
      if tEnd is 0 then return svSpan(pLine, kComment)
      put svSpan(char 1 to tEnd + 1 of pLine, kComment) into tOut
      put false into sInBlock
      put tEnd + 2 into i
   end if
   repeat while i <= tLen
      put char i of pLine into tChar
      if tChar is quote then
         put i into tStart
         add 1 to i
         repeat while i <= tLen and char i of pLine is not quote
            add 1 to i
         end repeat
         put svSpan(char tStart to i of pLine, kString) after tOut
         add 1 to i
      else if char i to i + 1 of pLine is "--" or tChar is "#" then
         put svSpan(char i to tLen of pLine, kComment) after tOut
         exit repeat
      else if char i to i + 1 of pLine is "/*" then
         put offset("*/", char i + 2 to tLen of pLine) into tEnd
         if tEnd is 0 then
            put svSpan(char i to tLen of pLine, kComment) after tOut
            put true into sInBlock
            exit repeat
         end if
         put svSpan(char i to i + tEnd + 2 of pLine, kComment) after tOut
         add tEnd + 3 to i
      else if svIsWordChar(tChar) then
         put i into tStart
         repeat while i <= tLen and svIsWordChar(char i of pLine)
            add 1 to i
         end repeat
         put char tStart to i - 1 of pLine into tWord
         put svSpan(tWord, svWordColour(tWord, tPrev)) after tOut
         put tWord into tPrev
      else
         put svEscape(tChar) after tOut
         add 1 to i
      end if
   end repeat
   return tOut
end svColourLine

-- The colour of a word, which can depend on the word before it: the
-- word after on, command or function is the name of a handler.
function svWordColour pWord, pPrevious
   if pPrevious is among the items of "on,command,function,getProp,setProp" then return kName
   if pWord is a number then return kNumber
   if pWord is among the items of kDeclares then return kDeclare
   if pWord is among the items of kKeywords then return kKeyword
   if pWord is among the items of kCommands then return kCommand
   if pWord is among the items of kSoftWords then return kSoft
   return kInk
end svWordColour

function svIsWordChar pChar
   return pChar is in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
end svIsWordChar

function svSpan pText, pColour
   return "<font color=" & quote & pColour & quote & ">" & svEscape(pText) & "</font>"
end svSpan

-- < > and & mean something in HTML: write them as entities.
function svEscape pText
   replace "&" with "&amp;" in pText
   replace "<" with "&lt;" in pText
   replace ">" with "&gt;" in pText
   return pText
end svEscape

-- A sentence or two on what this kind of script does, and its handlers.
function svAbout pObj
   local tKind, tText, tHandlers
   put word 1 of the name of pObj into tKind
   switch tKind
      case "stack"
         put "The stack script is the last stop on the message path for every card, so its handlers can be called from anywhere in the stack." into tText
         break
      case "card"
         put "A card script gets the card's own messages (openCard, closeCard) and the messages of its controls that they do not handle." into tText
         break
      case "group"
         put "A group script gets the messages of the controls inside the group that they do not handle themselves." into tText
         break
      default
         if the script of pObj is not empty then
            put "This" && tKind & "'s handlers run when it gets the messages they are named after: mouseUp for a click." into tText
         else if the cGoTo of pObj is not empty then
            put "No script: its click goes up the message path to the stack script, which reads its cGoTo property (" & quote & the cGoTo of pObj & quote & ")." into tText
         else if word 1 of the owner of pObj is "group" then
            put "No script: its messages go on to its group," && the short name of the owner of pObj & "." into tText
         else
            put "No script: this" && tKind && "only shows something, and other scripts change it." into tText
         end if
   end switch
   put svHandlers(the script of pObj) into tHandlers
   if tHandlers is not empty then put return & "Handlers: " & tHandlers after tText
   return tText
end svAbout

-- The names of the handlers in a script, joined with commas.
function svHandlers pScript
   local tLine, tDecl, tList
   repeat for each line tLine in pScript
      put tLine into tDecl
      if word 1 of tDecl is "private" then delete word 1 of tDecl
      if word 1 of tDecl is among the items of "on,command,function,getProp,setProp" then
         put word 2 of tDecl & ", " after tList
      end if
   end repeat
   if tList is not empty then delete char -2 to -1 of tList
   return tList
end svHandlers

-- Copy the chosen script, and say so on the button for a moment.
command svCopy
   local tObj
   put svCurrent() into tObj
   if tObj is empty then exit svCopy
   set the clipboardData["text"] to the script of tObj
   set the label of button "svCopy" of me to "Copied!"
   send "svCopyDone" to me in 1200 milliseconds
end svCopy

on svCopyDone
   set the label of button "svCopy" of me to "Copy"
end svCopyDone

-- Open the chosen script in the Script Editor (only in the IDE).
command svEdit
   local tObj
   put svCurrent() into tObj
   if tObj is empty then exit svEdit
   edit the script of tObj
end svEdit

-- Make the chosen control blink, to show where it is.
command svShowMe
   local tObj
   put svCurrent() into tObj
   if tObj is empty then exit svShowMe
   if word 1 of the name of tObj is among the items of "stack,card" then
      put "Show me works on a control: choose one in the list." into field "svAbout" of me
      exit svShowMe
   end if
   if not the visible of tObj then
      put "This control is hidden right now, so it cannot blink." into field "svAbout" of me
      exit svShowMe
   end if
   repeat 3 times
      set the visible of tObj to false
      wait 150 milliseconds with messages
      set the visible of tObj to true
      wait 150 milliseconds with messages
   end repeat
end svShowMe

-- The arrow keys move the choice in the list.
command svMove pStep
   local tLine
   put the hilitedLine of field "svObjects" of me into tLine
   if tLine is empty then put 0 into tLine
   put max(1, min(the number of lines of field "svObjects" of me, tLine + pStep)) into tLine
   set the hilitedLine of field "svObjects" of me to tLine
   svShow
end svMove


-- Edit script is shown only in the IDE, where the Script Editor is.
on preOpenCard
   set the visible of button "svEdit" of me to (the environment is "development")
end preOpenCard

field "svObjects" (card 1)

2048.oxtstack, stack "2048 Script Viewer", 5 lines

-- Show the script of the object clicked. svShow is in the card script.
on mouseUp
   svShow
end mouseUp

button "svOnly" (card 1)

2048.oxtstack, stack "2048 Script Viewer", 5 lines

-- List every control, or only those with a script.
on mouseUp
   svRefresh
end mouseUp

field "svCode" (card 1)

2048.oxtstack, stack "2048 Script Viewer", 5 lines

-- The line numbers scroll with the code.
on scrollbarDrag
   set the vScroll of field "svGutter" of me to the vScroll of me
end scrollbarDrag

button "svCopy" (card 1)

2048.oxtstack, stack "2048 Script Viewer", 4 lines

on mouseUp
   svCopy
end mouseUp

button "svShowMe" (card 1)

2048.oxtstack, stack "2048 Script Viewer", 4 lines

on mouseUp
   svShowMe
end mouseUp

button "svEdit" (card 1)

2048.oxtstack, stack "2048 Script Viewer", 5 lines

-- edit opens the Script Editor, which only the IDE has.
on mouseUp
   svEdit
end mouseUp

button "svClose" (card 1)

2048.oxtstack, stack "2048 Script Viewer", 4 lines

on mouseUp
   close this stack
end mouseUp