module main
author unknown
version 1 0 
description 'Buffered pixel platform jumper for CoCube. Hold A or B to move in the air.'
variables skyTile cloud star platformNormal platformSpring platformBreak playerUp playerDown digits playerX playerY previousY velocityX velocityY platformsX platformsY platformsWidth platformsType platformCount score best running scrollOffset theme animFrame 

  spec ' ' 'start platform jumper' 'start platform jumper'
  spec ' ' 'initialize jumper graphics' 'initialize jumper graphics'
  spec ' ' 'create jumper scenery' 'create jumper scenery'
  spec ' ' 'create jumper actors' 'create jumper actors'
  spec ' ' 'create jumper digits 1' 'create jumper digits 1'
  spec ' ' 'create jumper digits 2' 'create jumper digits 2'
  spec ' ' 'set jumper theme' 'set jumper theme _' 'num' 0
  spec ' ' 'set jumper day palette' 'set jumper day palette'
  spec ' ' 'set jumper night palette' 'set jumper night palette'
  spec ' ' 'reset jumper round' 'reset jumper round'
  spec ' ' 'make jumper platforms' 'make jumper platforms'
  spec ' ' 'recycle jumper platforms' 'recycle jumper platforms'
  spec ' ' 'move jumper player' 'move jumper player'
  spec ' ' 'scroll jumper world' 'scroll jumper world by _' 'num' 1
  spec ' ' 'check jumper landing' 'check jumper landing'
  spec ' ' 'merge jumper number' 'merge number _ at x _' 'num num' 0 10
  spec ' ' 'draw jumper frame' 'draw jumper frame'
  spec ' ' 'finish jumper game' 'finish jumper game'

to 'check jumper landing' {
  if (velocityY > 0) {
    local 'previousBottom' ((previousY / 10) + 8)
    local 'currentBottom' ((playerY / 10) + 8)
    for i platformCount {
      local 'platformY' (at i platformsY)
      if (and (previousBottom <= platformY) (currentBottom >= platformY)) {
        if (and ((playerX + 7) >= (at i platformsX)) (playerX <= ((at i platformsX) + (at i platformsWidth)))) {
          playerY = ((platformY - 8) * 10)
          velocityY = -38
          if ((at i platformsType) == 2) {
            velocityY = -48
          }
          if ((at i platformsType) == 3) {
            atPut i platformsY 90
          }
          'play tone' 'nt;e' 1 18
          return
        }
      }
    }
  }
}

to 'create jumper actors' {
  playerUp = ('8bit_bitmap' 8 '000DD000
00D88D00
0D88C8D0
0D8888D0
00D88D00
0D8888D0
D0D88D0D
00D00D00')
  playerDown = ('8bit_bitmap' 8 '000DD000
00D88D00
0D88C8D0
0D8888D0
00D88D00
0D8888D0
00D00D00
0D0000D0')
}

to 'create jumper digits 1' {
  atPut 1 digits ('8bit_bitmap' 3 'FFF
F0F
F0F
F0F
FFF')
  atPut 2 digits ('8bit_bitmap' 3 '0F0
FF0
0F0
0F0
FFF')
  atPut 3 digits ('8bit_bitmap' 3 'FFF
00F
FFF
F00
FFF')
  atPut 4 digits ('8bit_bitmap' 3 'FFF
00F
FFF
00F
FFF')
  atPut 5 digits ('8bit_bitmap' 3 'F0F
F0F
FFF
00F
00F')
}

to 'create jumper digits 2' {
  atPut 6 digits ('8bit_bitmap' 3 'FFF
F00
FFF
00F
FFF')
  atPut 7 digits ('8bit_bitmap' 3 'FFF
F00
FFF
F0F
FFF')
  atPut 8 digits ('8bit_bitmap' 3 'FFF
00F
00F
00F
00F')
  atPut 9 digits ('8bit_bitmap' 3 'FFF
F0F
FFF
F0F
FFF')
  atPut 10 digits ('8bit_bitmap' 3 'FFF
F0F
FFF
00F
FFF')
}

to 'create jumper scenery' {
  skyTile = ('8bit_bitmap' 8 '11111111
11111111
11111111
11111111
11111111
11111111
11111111
11111111')
  cloud = ('8bit_bitmap' 12 '000033000000
000333300000
033333333000
333333333330')
  star = ('8bit_bitmap' 3 '040
444
040')
  platformNormal = ('8bit_bitmap' 12 '555555555555
566666666665
577777777775')
  platformSpring = ('8bit_bitmap' 12 '888888888888
855555555558
080808080808
008080808080')
  platformBreak = ('8bit_bitmap' 12 '999999999999
99D999D99999
999D99D99999')
}

to 'draw jumper frame' {
  '8bit_merge3 tile' skyTile 0 0 80 80
  if (theme == 1) {
    for i 8 {
      '8bit_merge' star (((i * 17) + 5) % 76) (((i * 11) + 7) % 58)
    }
  }
  '8bit_merge' cloud (65 - ((scrollOffset / 3) % 90)) 13
  '8bit_merge' cloud (20 - ((scrollOffset / 5) % 90)) 38
  for i platformCount {
    if ((at i platformsType) == 1) {'8bit_merge' platformNormal (at i platformsX) (at i platformsY)}
    if ((at i platformsType) == 2) {'8bit_merge' platformSpring (at i platformsX) (at i platformsY)}
    if ((at i platformsType) == 3) {'8bit_merge' platformBreak (at i platformsX) (at i platformsY)}
  }
  if (velocityY < 0) {
    '8bit_merge' playerUp playerX (playerY / 10)
  } else {
    '8bit_merge' playerDown playerX (playerY / 10)
  }
  'merge jumper number' score 66
  '8bit_draw buffer'
}

to 'finish jumper game' {
  '[tft:rect]' 30 79 180 82 (colorSwatch 15 23 42 255) true
  '[tft:text]' 'GAME OVER' 39 91 (colorSwatch 248 113 113 255) 3 false
  '[tft:text]' ('[data:join]' 'HEIGHT ' score) 60 126 (colorSwatch 241 245 249 255) 2 false
  '[tft:text]' ('[data:join]' 'BEST ' best) 72 148 (colorSwatch 148 163 184 255) 2 false
  'play tone' 'nt;g' 0 120
  'play tone' 'nt;c' 0 260
  waitMillis 1400
  waitUntil (and (not (buttonA)) (not (buttonB)))
}

to 'initialize jumper graphics' {
  'clear display'
  '8bit_set scale _' 3
  '8bit_set transparent color index _' 0
  'create jumper scenery'
  'create jumper actors'
  digits = (newList 10)
  'create jumper digits 1'
  'create jumper digits 2'
}

to 'make jumper platforms' {
  platformCount = 7
  platformsX = (newList platformCount)
  platformsY = (newList platformCount)
  platformsWidth = (newList platformCount)
  platformsType = (newList platformCount)
  local 'previousX' 33
  local 'previousY' 73
  for i platformCount {
    if (i > 1) {
      previousX = (maximum 3 (minimum 65 (previousX + (random -18 18))))
      previousY += (0 - (random 8 10))
    }
    atPut i platformsX previousX
    atPut i platformsY previousY
    atPut i platformsWidth 12
    atPut i platformsType 1
  }
  atPut 2 platformsType 2
  atPut 5 platformsType 3
}

to 'merge jumper number' value x {
  value = (value % 1000)
  '8bit_merge' (at (((value / 100) % 10) + 1) digits) x 2
  '8bit_merge' (at (((value / 10) % 10) + 1) digits) (x + 4) 2
  '8bit_merge' (at ((value % 10) + 1) digits) (x + 8) 2
}

to 'move jumper player' {
  previousY = playerY
  playerX += velocityX
  playerX = (maximum 0 (minimum playerX 72))
  velocityY += 4
  playerY += velocityY
  if (and (playerY < 300) (velocityY < 0)) {
    local 'worldShift' ((300 - playerY) / 10)
    playerY = 300
    'scroll jumper world' worldShift
  }
  if (playerY > 820) {
    running = (booleanConstant false)
  }
  animFrame += 1
}

to 'recycle jumper platforms' {
  for i platformCount {
    if ((at i platformsY) > 82) {
      local 'topY' 80
      local 'topX' 33
      for j platformCount {
        if ((at j platformsY) < topY) {
          topY = (at j platformsY)
          topX = (at j platformsX)
        }
      }
      atPut i platformsY (topY - (random 8 10))
      atPut i platformsX (maximum 3 (minimum 65 (topX + (random -18 18))))
      atPut i platformsType (random 1 3)
    }
  }
}

to 'reset jumper round' {
  playerX = 35
  playerY = 620
  previousY = playerY
  velocityX = 0
  velocityY = -38
  score = 0
  scrollOffset = 0
  animFrame = 0
  'set jumper theme' 0
  'make jumper platforms'
  running = (booleanConstant true)
  'play tone' 'nt;c' 1 45
  'play tone' 'nt;g' 1 70
}

to 'scroll jumper world' amount {
  for i platformCount {
    atPut i platformsY ((at i platformsY) + amount)
  }
  scrollOffset += amount
  score += amount
  if (score > best) {
    best = score
  }
  if (((score / 200) % 2) == 0) {
    'set jumper theme' 0
  } else {
    'set jumper theme' 1
  }
}

to 'set jumper day palette' {
  '8bit_set palette' ('[data:makeList]' (makeColor 0 0 0) (makeColor 106 196 235) (makeColor 176 225 247) (makeColor 244 251 255) (makeColor 255 239 153) (makeColor 65 149 82) (makeColor 43 113 67) (makeColor 116 83 49) (makeColor 250 204 21) (makeColor 248 113 113) (makeColor 56 189 248) (makeColor 30 41 59) (makeColor 255 255 255) (makeColor 93 56 37) (makeColor 15 23 42) (makeColor 255 255 255))
}

to 'set jumper night palette' {
  '8bit_set palette' ('[data:makeList]' (makeColor 0 0 0) (makeColor 12 25 58) (makeColor 35 54 91) (makeColor 75 92 130) (makeColor 255 234 139) (makeColor 41 116 67) (makeColor 29 91 54) (makeColor 78 61 49) (makeColor 250 204 21) (makeColor 248 113 113) (makeColor 56 189 248) (makeColor 30 41 59) (makeColor 255 255 255) (makeColor 93 56 37) (makeColor 15 23 42) (makeColor 255 255 255))
}

to 'set jumper theme' newTheme {
  theme = newTheme
  if (theme == 0) {
    'set jumper day palette'
  }
  if (theme == 1) {
    'set jumper night palette'
  }
}

to 'start platform jumper' {
  best = 0
  'initialize jumper graphics'
  forever {
    '[tft:clear]'
    '[tft:text]' 'SKY' 83 58 (colorSwatch 56 189 248 255) 4 false
    '[tft:text]' 'JUMPER' 47 105 (colorSwatch 250 204 21 255) 4 false
    '[tft:text]' 'A:LEFT  B:RIGHT' 29 181 (colorSwatch 241 245 249 255) 2 false
    waitUntil (or (buttonA) (buttonB))
    waitUntil (and (not (buttonA)) (not (buttonB)))
    'reset jumper round'
    repeatUntil (not running) {
      'move jumper player'
      'check jumper landing'
      'recycle jumper platforms'
      'draw jumper frame'
      waitMillis 22
    }
    'finish jumper game'
  }
}

script 49 49 {
whenStarted
'start platform jumper'
}

script 510 52 {
whenButtonPressed 'B'
if running {
  repeatUntil (or (not running) (not (buttonB))) {
    velocityX = 2
    waitMillis 10
  }
  if (not (buttonA)) {
    velocityX = 0
  }
}
}

script 47 154 {
whenButtonPressed 'A'
if running {
  repeatUntil (or (not running) (not (buttonA))) {
    velocityX = -2
    waitMillis 10
  }
  if (not (buttonB)) {
    velocityX = 0
  }
}
}


module '8 Bit Graphics' Output
author MicroBlocks
version 1 6 
depends _TFT _Files 
tags graphics 
choices eightBitPalettes MicroBlocks 'red hues' 'green hues' 'blue hues' grayscale 
choices mirrorAxis horizontal vertical 'ascending diagonal' 'descending diagonal' 
choices fourBitPalettes CGA 'Machintosh II' 'Win & OS/2' MSX Pico8 'RISC 2' grayscale 
choices orthoRotations '0' '90' '180' '270' 
description 'Provides a full 8-bit (and lower depth) framework to create retro-looking games and applications.

By combining different scales and bit depths you can adapt your project to work on virtually any board.

It allows reading 8-bit indexed BMP files, color palettes and raw image data exported from GIMP, or creating your own bitmaps by hand as byte arrays.  It also includes a bunch of default 4-bit and 8-bit color palettes.

By using a buffer and bitmap merge operations, you can work with sprites and backgrounds at a reasonably high abstraction level, while achieving a decent framerate.
'
variables _8bit_scale _8bit_alpha_index _8bit_buffer _8bit_palette _bmpIsRGB565 _bmpHeight _bmpCompression _bmpWidth _bmpPalette _bmpPixelsOffset _bmpBPP _bmpLine 

  spec ' ' '8bit_set scale _' 'set scale _' 'num' 4
  space
  spec ' ' 'clear display' 'clear display'
  spec ' ' '8bit_draw buffer' 'draw buffer : starting at x _ y _ width _ height _' 'num num num num' 10 20 7 7
  space
  spec 'r' '8bit_bitmap from BMP file' 'bitmap from BMP file _' 'auto' '8bit.bmp'
  spec 'r' '8bit_bitmap from file' 'bitmap of width _ from raw indexed file _' 'num str' 32 'filename.data'
  spec 'r' '8bit_bitmap' 'bitmap of width _ from string _' 'num str' 7 '0003000003B30003BFB30003B3000003000'
  space
  spec 'r' '8bit_rotated sprite' 'bitmap _ rotated _ º' 'auto menu.orthoRotations' 'aBitmap' 270
  spec 'r' '8bit_mirrored bitmap' 'bitmap _ mirrored across _ axis' 'auto menu.mirrorAxis' 'aBitmap' 'vertical'
  space
  spec ' ' '8bit_merge' 'merge bitmap _ at _ , _' 'auto num num' '' 10 20
  spec ' ' '8bit_merge3 tile' 'merge tile _ from _ , _ to _ , _' 'auto auto auto auto auto' 'aBitmap' 10 20 15 30
  spec ' ' '8bit_merge2 tile' 'merge tile _ at tile position _ , _' 'auto auto auto' 'aBitmap' 1 2
  space
  spec ' ' '8bit_set palette' 'set palette _' 'auto' ''
  spec ' ' '8bit_set transparent color index _' 'set transparent color index _' 'num' 0
  spec 'r' '8bit_palette from pal format' 'palette from pal file _' 'auto' 'filename.data.pal'
  spec 'r' '8bit_palette from BMP file' 'palette from BMP file _' 'auto' '8bit.bmp'
  spec 'r' '8bit_4 bit palette' '4 bit _ palette' 'menu.fourBitPalettes' 'CGA'
  spec 'r' '8bit_8 bit palette' '8 bit _ palette' 'menu.eightBitPalettes' 'MicroBlocks'
  spec 'r' 'rgb_to_color' 'color number for r _ g _ b _ (0-255)' 'num num num' 128 0 0
  spec ' ' '8bit_draw palette table' 'draw palette table _' 'auto' ''
  spec 'r' '8bit_current palette' 'current palette'
  space
  spec 'r' '8bit_screen width' 'screen width'
  spec 'r' '8bit_screen height' 'screen height'
  space
  spec 'r' '_8bit_4bit_CGA palette' '_8bit_4bit_CGA palette'
  spec 'r' '_8bit_4bit_Machintosh II palette' '_8bit_4bit_Machintosh II palette'
  spec 'r' '_8bit_4bit_Win & OS/2 palette' '_8bit_4bit_Win & OS/2 palette'
  spec 'r' '_8bit_4bit_grayscale palette' '_8bit_4bit_grayscale palette'
  spec 'r' '_8bit_4bit_MSX palette' '_8bit_4bit_MSX palette'
  spec 'r' '_8bit_4bit_Pico8 palette' '_8bit_4bit_Pico8 palette'
  spec 'r' '_8bit_4bit_RISC 2 palette' '_8bit_4bit_RISC 2 palette'
  spec 'r' '_8bit_8bit_grayscale palette' '_8bit_8bit_grayscale palette'
  spec 'r' '_8bit_8bit_green hues palette' '_8bit_8bit_green hues palette'
  spec 'r' '_8bit_8bit_red hues palette' '_8bit_8bit_red hues palette'
  spec 'r' '_8bit_8bit_blue hues palette' '_8bit_8bit_blue hues palette'
  spec 'r' '_8bit_8bit_MicroBlocks palette' '_8bit_8bit_MicroBlocks palette'
  spec 'r' '_sqrt _' '_sqrt _' 'num' 10
  spec 'r' '_bmp_readHeader' '_bmp_readHeader file _' 'str' ''
  spec ' ' '_bmp_readPalette' '_bmp_readPalette file _' 'auto' ''
  spec ' ' '_bmp_readLine' '_bmp_readLine file _' 'auto' ''
  spec 'r' '_bmp_line2indexes' '_bmp_line2indexes'
  spec 'r' '_bmp_RLEline' '_bmp_readRLELine file _' 'auto' ''
  spec 'r' '_bmp_readInt16' '_bmp read int16 file _' 'str' ''
  spec 'r' '_bmp_readInt32' '_bmp read int32 file _' 'str' ''
  spec ' ' '_bmp_alignLineData' '_bmp_alignLineData file _' 'auto' ''

to '8bit_4 bit palette' selector {
  return (callCustomReporter ('[data:join]' '_8bit_4bit_' selector ' palette'))
}

to '8bit_8 bit palette' selector {
  return (callCustomReporter ('[data:join]' '_8bit_8bit_' selector ' palette'))
}

to '8bit_bitmap' width 'bitmap string' {
  local 'list' ('[data:makeList]')
  for line ('[data:split]' (v 'bitmap string') ('[data:unicodeString]' 10)) {
    for bit line {
      '[data:addLast]' (hexToInt bit) list
    }
  }
  return ('[data:makeList]' width ('[data:asByteArray]' list))
}

to '8bit_bitmap from BMP file' filename {
  if (not ('_bmp_readHeader' filename)) {return 0}
  if (_bmpBPP > 8) {return 1}
  '[file:setReadPosition]' _bmpPixelsOffset filename
  local 'buf' ('[data:newByteArray]' 0)
  repeat (absoluteValue _bmpHeight) {
    '_bmp_readLine' filename
    if (_bmpHeight >= 0) {
      buf = ('[data:join]' _bmpLine buf)
    } else {
      buf = ('[data:join]' buf _bmpLine)
    }
    '_bmp_alignLineData' filename
  }
  return ('[data:makeList]' _bmpWidth buf)
}

to '8bit_bitmap from file' width 'file name' {
  '[file:open]' (v 'file name')
  local 'bitmap' ('[data:newByteArray]' ('[file:fileSize]' (v 'file name')))
  for i ('[file:fileSize]' (v 'file name')) {
    atPut i bitmap (at 1 ('[file:readBytes]' 1 (v 'file name')))
  }
  '[file:close]' (v 'file name')
  return ('[data:makeList]' width bitmap)
}

to '8bit_current palette' {
  return _8bit_palette
}

to '8bit_draw buffer' 'region x' 'region y' width height {
  if (not (isType _8bit_palette 'list')) {_8bit_palette = ('[data:makeList]' '0' 'AA' 'AA00' 'AAAA' 'AA0000' 'AA00AA' 'AA5500' 'AAAAAA' '555555' '5555FF' '55FF55' '55FFFF' 'FF5555' 'FF55FF' 'FFFF55' 'FFFFFF')}
  if ((pushArgCount) < 1) {
    '[tft:drawBuffer]' _8bit_buffer _8bit_palette _8bit_scale
  } else {
    '[tft:drawBuffer]' _8bit_buffer _8bit_palette _8bit_scale (v 'region x') (v 'region y') width height
  }
  waitMicros 500
}

to '8bit_draw palette table' palette {
  if (not (isType palette 'list')) {if (isType _8bit_palette 'list') {
    palette = _8bit_palette
  } else {
    return 0
  }}
  local 'side' ('_sqrt _' (size palette))
  local 'width' (minimum (('[tft:getHeight]') / side) (('[tft:getWidth]') / side))
  for y side {
    for x side {
      local 'index' (((y - 1) * side) + x)
      if (index <= (size palette)) {
        '[tft:rect]' ((x - 1) * width) ((y - 1) * width) width width (at index palette)
      }
    }
  }
}

to '8bit_merge' bitmap 'origin x' 'origin y' {
  if (_8bit_scale == 0) {'8bit_set scale _' 2}
  '[tft:mergeBitmap]' (at 2 bitmap) (at 1 bitmap) _8bit_buffer _8bit_scale _8bit_alpha_index (v 'origin x') (v 'origin y')
}

to '8bit_merge2 tile' bitmap x y {
  local 'tile width' (at 1 bitmap)
  local 'tile height' ((size (at 2 bitmap)) / (v 'tile width'))
  '8bit_merge' bitmap ((x - 1) * (v 'tile width')) ((y - 1) * (v 'tile height'))
}

to '8bit_merge3 tile' bitmap x1 y1 x2 y2 {
  local 'tile width' (at 1 bitmap)
  local 'tile height' ((size (at 2 bitmap)) / (v 'tile width'))
  local 'first x' (((x1 - 1) / (v 'tile width')) + 1)
  local 'first y' (((y1 - 1) / (v 'tile height')) + 1)
  local 'last x' (((x2 - 1) / (v 'tile width')) + 1)
  local 'last y' (((y2 - 1) / (v 'tile height')) + 1)
  for x ('[data:range]' (v 'first x') (v 'last x')) {
    for y ('[data:range]' (v 'first y') (v 'last y')) {
      '8bit_merge2 tile' bitmap x y
    }
  }
}

to '8bit_mirrored bitmap' bitmap axis {
  local 'bitmap width' (at 1 bitmap)
  local 'index list' (at 2 bitmap)
  local 'index length' (size (v 'index list'))
  local 'new array' ('[data:newByteArray]' (v 'index length'))
  if (axis == 'vertical') {
    for i (v 'index length') {
      atPut i (v 'new array') (at (((v 'index length') - (((((i - 1) / (v 'bitmap width')) + 1) * (v 'bitmap width')) - ((i - 1) % (v 'bitmap width')))) + 1) (v 'index list'))
    }
  } (axis == 'horizontal') {
    for i (v 'index length') {
      atPut i (v 'new array') (at (((((i - 1) / (v 'bitmap width')) + 1) * (v 'bitmap width')) - ((i - 1) % (v 'bitmap width'))) (v 'index list'))
    }
  } (axis == 'descending diagonal') {
    for i (v 'index length') {
      atPut i (v 'new array') (at (((((i - 1) * (v 'bitmap width')) + ((i - 1) / (v 'bitmap width'))) % (v 'index length')) + 1) (v 'index list'))
    }
  } (axis == 'ascending diagonal') {
    for i (v 'index length') {
      atPut i (v 'new array') (at ((v 'index length') - ((((i - 1) * (v 'bitmap width')) + ((i - 1) / (v 'bitmap width'))) % (v 'index length'))) (v 'index list'))
    }
  }
  return ('[data:makeList]' (v 'bitmap width') (v 'new array'))
}

to '8bit_palette from BMP file' filename {
  if ('_bmp_readHeader' filename) {return _bmpPalette}
}

to '8bit_palette from pal format' 'file name' {
  '[file:open]' (v 'file name')
  local 'palette' (newList (('[file:fileSize]' (v 'file name')) / 3))
  for i (('[file:fileSize]' (v 'file name')) / 3) {
    atPut i palette ((((at 1 ('[file:readBytes]' 1 (v 'file name'))) << 16) | ((at 1 ('[file:readBytes]' 1 (v 'file name'))) << 8)) | (at 1 ('[file:readBytes]' 1 (v 'file name'))))
  }
  '[file:close]' (v 'file name')
  return palette
}

to '8bit_rotated sprite' bitmap degs {
  local 'bitmap width' (at 1 bitmap)
  local 'index list' (at 2 bitmap)
  local 'index length' (size (v 'index list'))
  if ((degs % 360) == 0) {
    return bitmap
  } else {
    local 'new array' ('[data:newByteArray]' (v 'index length'))
    if ((absoluteValue (degs % 360)) == 180) {
      for i (v 'index length') {
        atPut ((v 'index length') - (i - 1)) (v 'new array') (at i (v 'index list'))
      }
    } ((degs % 360) == 90) {
      for i (v 'index length') {
        atPut i (v 'new array') (at (((v 'index length') - (((((i - 1) % (v 'bitmap width')) + 1) * (v 'bitmap width')) - ((i - 1) / (v 'bitmap width')))) + 1) (v 'index list'))
      }
    } ((degs % 360) == 270) {
      for i (v 'index length') {
        atPut i (v 'new array') (at (((((i - 1) % (v 'bitmap width')) + 1) * (v 'bitmap width')) - ((i - 1) / (v 'bitmap width'))) (v 'index list'))
      }
    }
  }
  return ('[data:makeList]' (v 'bitmap width') (v 'new array'))
}

to '8bit_screen height' {
  if (_8bit_scale == 0) {'8bit_set scale _' 2}
  return (('[tft:getHeight]') / _8bit_scale)
}

to '8bit_screen width' {
  if (_8bit_scale == 0) {'8bit_set scale _' 2}
  return (('[tft:getWidth]') / _8bit_scale)
}

to '8bit_set palette' 'color list' {
  _8bit_palette = (v 'color list')
}

to '8bit_set scale _' scale {
  _8bit_scale = scale
  _8bit_buffer = ('[data:newByteArray]' (('8bit_screen width') * ('8bit_screen height')) 0)
}

to '8bit_set transparent color index _' 'alpha index' {
  _8bit_alpha_index = (v 'alpha index')
}

to '_8bit_4bit_CGA palette' {
  return ('[data:makeList]' 0 170 43520 43690 11141120 11141290 11162880 11184810 5592405 5592575 5635925 5636095 16733525 16733695 16777045 16777215)
}

to '_8bit_4bit_MSX palette' {
  return ('[data:makeList]' (hexToInt '0') (hexToInt '010101') (hexToInt '3eb849') (hexToInt '74d07d') (hexToInt '5955e0') (hexToInt '8076f1') (hexToInt 'b95e51') (hexToInt '65dbef') (hexToInt 'db6559') (hexToInt 'ff897d') (hexToInt 'ccc35e') (hexToInt 'ded087') (hexToInt '3aa241') (hexToInt 'b766b5') (hexToInt 'cccccc') (hexToInt 'ffffff'))
}

to '_8bit_4bit_Machintosh II palette' {
  return ('[data:makeList]' (hexToInt 'ffffff') (hexToInt 'fcf400') (hexToInt 'ff6400') (hexToInt 'dd0202') (hexToInt 'f10285') (hexToInt '4600a6') (hexToInt 'd5') (hexToInt 'aee9') (hexToInt '1ab90c') (hexToInt '6408') (hexToInt '582800') (hexToInt '917135') (hexToInt 'c1c1c1') (hexToInt '818181') (hexToInt '3e3e3e') (hexToInt '0'))
}

to '_8bit_4bit_Pico8 palette' {
  return ('[data:makeList]' (hexToInt '0') (hexToInt '1d2b53') (hexToInt '7e2553') (hexToInt '008751') (hexToInt 'ab5236') (hexToInt '5f574f') (hexToInt 'c2c3c7') (hexToInt 'fff1e8') (hexToInt 'ff004d') (hexToInt 'ffa300') (hexToInt 'fff024') (hexToInt '00e756') (hexToInt '29adff') (hexToInt '83769c') (hexToInt 'ff77a8') (hexToInt 'ffccaa'))
}

to '_8bit_4bit_RISC 2 palette' {
  return ('[data:makeList]' (hexToInt 'ffffff') (hexToInt 'dddddd') (hexToInt 'bdbdbd') (hexToInt '999999') (hexToInt '797979') (hexToInt '535353') (hexToInt '313131') (hexToInt '0') (hexToInt '4299') (hexToInt 'f0f000') (hexToInt 'cd00') (hexToInt 'dd0000') (hexToInt 'f0f0bd') (hexToInt '538900') (hexToInt 'ffbd00') (hexToInt 'bdff'))
}

to '_8bit_4bit_Win & OS/2 palette' {
  return ('[data:makeList]' (hexToInt '0') (hexToInt '800000') (hexToInt '8000') (hexToInt '808000') (hexToInt '80') (hexToInt '800080') (hexToInt '8080') (hexToInt 'c0c0c0') (hexToInt '808080') (hexToInt 'ff0000') (hexToInt 'ff00') (hexToInt 'ffff00') (hexToInt 'ff') (hexToInt 'ff00ff') (hexToInt 'ffff') (hexToInt 'ffffff'))
}

to '_8bit_4bit_grayscale palette' {
  return ('[data:makeList]' 0 1315860 2105376 2894892 3684408 4539717 5329233 6381921 7434609 8553090 9605778 10658466 11974326 13355979 14935011 16777215)
}

to '_8bit_8bit_MicroBlocks palette' {
  return ('[data:join]' ('[data:range]' 0 (hexToInt 'FFFFFF') ((hexToInt 'FFFFFF') / 239)) ('[data:range]' 0 (hexToInt 'FFFFFF') ((hexToInt 'FFFFFF') / 15)))
}

to '_8bit_8bit_blue hues palette' {
  return ('[data:range]' 0 255)
}

to '_8bit_8bit_grayscale palette' {
  return ('[data:range]' 0 (hexToInt 'FFFFFF') ((hexToInt 'FFFFFF') / 255))
}

to '_8bit_8bit_green hues palette' {
  return ('[data:range]' (hexToInt 'FF00') (hexToInt 'FFFF'))
}

to '_8bit_8bit_red hues palette' {
  return ('[data:range]' (hexToInt 'FF0000') (hexToInt 'FF00FF'))
}

to '_bmp_RLEline' filename {
  local 'result' ('[data:newByteArray]' 0)
  forever {
    if ((('[file:readPosition]' filename) & 1) == 1) {file_SkipBytes 1 filename}
    local 'rle' ('[file:readBytes]' 2 filename)
    if ((at 1 rle) == 0) {
      if ((at 2 rle) > 2) {
        comment 'odd numbers for RL4?'
        result = ('[data:join]' result ('[file:readBytes]' ((((at 2 rle) * _bmpBPP) + 7) / 8) filename))
      } else {
        return result
      }
    } else {
      result = ('[data:join]' result ('[data:newByteArray]' ((((at 1 rle) * _bmpBPP) + 7) / 8) (at 2 rle)))
    }
  }
}

to '_bmp_alignLineData' filename {
  if (and (_bmpCompression != 1) (_bmpCompression != 2)) {
    local 'padding' (((32 - ((_bmpWidth * _bmpBPP) % 32)) / 8) % 4)
    if (padding > 0) {
      file_SkipBytes padding filename
    }
  }
}

to '_bmp_line2indexes' {
  local 'mask' ((1 << _bmpBPP) - 1)
  local 'result' ('[data:newByteArray]' 0)
  local 'i' 1
  repeatUntil ((size result) == _bmpWidth) {
    local 'byte' (at i _bmpLine)
    local 'b' (8 / _bmpBPP)
    repeatUntil (or (b < 1) ((size result) == _bmpWidth)) {
      b += -1
      result = ('[data:join]' result ('[data:asByteArray]' ((byte >> (_bmpBPP * b)) & mask)))
    }
    i += 1
  }
  return result
}

to '_bmp_readHeader' filename {
  if (('[file:fileSize]' filename) < 0) {
    sayIt 'File not found: ' filename
    return (booleanConstant false)
  }
  '[file:open]' filename
  if (or (('[file:fileSize]' filename) < 54) ('BM' != ('[data:join]' '' ('[file:readBytes]' 2 filename)))) {
    sayIt 'Not a BMP file: ' filename
    return (booleanConstant false)
  }
  file_SkipBytes 8 filename
  _bmpPixelsOffset = ('_bmp_readInt32' filename)
  local 'headerSize' ('_bmp_readInt32' filename)
  _bmpWidth = ('_bmp_readInt32' filename)
  _bmpHeight = ('_bmp_readInt32' filename)
  file_SkipBytes 2 filename
  _bmpBPP = ('_bmp_readInt16' filename)
  _bmpCompression = ('_bmp_readInt32' filename)
  if (_bmpCompression > 3) {
    sayIt ('[data:join]' 'Unsupported compression method: ' _bmpCompression)
    return (booleanConstant false)
  }
  _bmpPalette = 0
  if (_bmpBPP <= 8) {
    file_SkipBytes 12 filename
    local 'palSize' ('_bmp_readInt16' filename)
    if (palSize == 0) {
      palSize = (1 << _bmpBPP)
    }
    _bmpPalette = (newList palSize)
    file_SkipBytes (headerSize - 34) filename
    '_bmp_readPalette' filename
  } else {
    _bmpIsRGB565 = (booleanConstant false)
    if (_bmpCompression == 3) {
      file_SkipBytes 20 filename
      comment 'BITFIELD  Red'
      _bmpIsRGB565 = (('_bmp_readInt32' filename) == (hexToInt 'F800'))
    }
  }
  return (booleanConstant true)
}

to '_bmp_readInt16' filename {
  local 'data' ('[file:readBytes]' 2 filename)
  return (((at 2 data) << 8) | (at 1 data))
}

to '_bmp_readInt32' filename {
  local 'data' ('[file:readBytes]' 4 filename)
  return ((((at 4 data) << 24) | ((at 3 data) << 16)) | (((at 2 data) << 8) | (at 1 data)))
}

to '_bmp_readLine' filename {
  if (or (_bmpCompression == 1) (_bmpCompression == 2)) {
    _bmpLine = ('_bmp_RLEline' filename)
  } else {
    _bmpLine = ('[file:readBytes]' (((_bmpWidth * _bmpBPP) + 7) / 8) filename)
  }
  if (_bmpBPP < 8) {
    local 'indexes' ('_bmp_line2indexes')
    _bmpLine = indexes
  }
}

to '_bmp_readPalette' filename {
  for i (size _bmpPalette) {
    local 'data' ('[file:readBytes]' 4 filename)
    local 'color' (((at 3 data) << 16) | (((at 2 data) << 8) | (at 1 data)))
    atPut i _bmpPalette color
  }
}

to '_sqrt _' n {
  for i n {
    if ((i * i) >= n) {return i}
  }
}

to 'clear display' {
  '[display:mbDisplayOff]'
}

to rgb_to_color r g b {
  r = (maximum 0 (minimum r 255))
  g = (maximum 0 (minimum g 255))
  b = (maximum 0 (minimum b 255))
  return (((r << 16) | (g << 8)) | b)
}


module TFT Output
author MicroBlocks
version 1 19 
description 'Draw graphics and write text on boards with a TFT display, such as the M5Stack, M5Stick, Citilab ED1 or (discontinued) IoT-Bus.'

  spec ' ' '[tft:clear]' 'clear TFT display'
  space
  spec ' ' '[tft:rect]' 'draw rectangle on TFT at x _ y _ width _ height _ color _ : filled _' 'num num num num color bool' 10 10 40 30 nil true
  spec ' ' '[tft:roundedRect]' 'draw rounded rectangle on TFT at x _ y _ width _ height _ radius _ color _ : filled _' 'num num num num num color bool' 10 10 40 30 8 nil true
  spec ' ' '[tft:circle]' 'draw circle on TFT at x _ y _ radius _ color _ : filled _' 'num num num color bool' 40 40 30 nil true
  spec ' ' '[tft:triangle]' 'draw triangle on TFT at x _ y _ , x _ y _ , x _ y _ color _ : filled _' 'num num num num num num color bool' 20 20 30 80 60 5 nil true
  spec ' ' '[tft:line]' 'draw line on TFT from x _ y _ to x _ y _ color _' 'num num num num color' 12 8 25 15
  spec ' ' 'tft_drawVector' 'draw vector x _ y _ angle _ length _ color _' 'num num num num color' 40 40 45 40
  space
  spec ' ' '[tft:text]' 'write _ on TFT at x _ y _ color _ : scale _ wrap _ : bg color _' 'str num num color num bool color' 'Hello World!' 5 5 nil 2 true
  spec ' ' 'tft_drawText' 'draw text _ on TFT at x _ y _ color _ : scale _ : bg color _' 'str num num color num color' 'Line 1
Line 2' 50 20 nil 2
  space
  spec ' ' '[tft:setPixel]' 'set TFT pixel x _ y _ to _' 'num num color' 10 10
  spec ' ' '[tft:pixelRow]' 'draw pixel row _ x _ y _ : bytes per pixel _ : palette _' 'auto num num num str' 'aList' 0 0 4
  spec ' ' '[tft:drawBitmap]' 'draw bitmap _ palette _ on TFT at x _ y _' 'str str num num' 'aBitmap' 'a list of colors' 10 10
  space
  spec 'r' 'tft_colorSwatch' '_' 'color'
  spec 'r' 'makeColor' 'color r _ g _ b _ (0-255)' 'num num num' 0 100 100
  spec 'r' 'makeGray' 'gray _ %' 'num' 50
  spec 'r' 'randomColor' 'random color'
  space
  spec ' ' 'tft_drawImage' 'draw image _ on TFT at x _ y _ color _ : #BR# scale _' 'str num num color num' '' 0 0 nil 1
  spec 'r' 'tft_image' 'image _' 'str' '00000
01010
00000
10001
01110'
  space
  spec 'r' '[tft:getWidth]' 'TFT width'
  spec 'r' '[tft:getHeight]' 'TFT height'
  space
  spec ' ' '[tft:setBacklight]' 'set TFT backlight _ (0-10)' 'num' 10
  spec ' ' '[tft:invertDisplay]' 'invert TFT display _' 'bool' false
  advanced
  spec ' ' 'tft_deferOLEDDisplayUpdates' 'defer OLED display updates'
  spec ' ' 'tft_resumeOLEDDisplayUpdates' 'resume OLED display updates'
  space
  spec ' ' '_deferMonochromeDisplayUpdates' '_defer monochrome display updates'
  spec ' ' '_resumeMonochromeDisplayUpdates' '_resume monochrome display updates'
  spec ' ' '[tft:unicode]' 'obsolete unicode _ on TFT at x _ y _ color _ : scale _ wrap _ : bg color _' 'str num num color num bool color' 'Hello World!' 5 5 nil 1 true

to '_deferMonochromeDisplayUpdates' {
  '[tft:deferUpdates]'
}

to '_resumeMonochromeDisplayUpdates' {
  '[tft:resumeUpdates]'
}

to makeColor r g b {
  r = (maximum 0 (minimum r 255))
  g = (maximum 0 (minimum g 255))
  b = (maximum 0 (minimum b 255))
  return ((r << 16) | ((g << 8) | b))
}

to makeGray percent {
  gray = ((percent * 255) / 100)
  gray = (maximum 0 (minimum gray 255))
  return ((gray << 16) | ((gray << 8) | gray))
}

to randomColor {
  local 'n1' (random 100 200)
  local 'n2' (random 0 100)
  if (1 == (random 1 3)) {
    return ((n1 << 16) | (n2 << 8))
  } (1 == (random 1 2)) {
    return ((n2 << 16) | n1)
  } else {
    return ((n1 << 8) | n2)
  }
}

to tft_colorSwatch color {
  return color
}

to tft_deferOLEDDisplayUpdates {
  '[tft:deferUpdates]'
}

to tft_drawImage imageString x y c optionalScale {
  comment 'Draw an image at the given position. An image is represented by a multi-line string
of 0 and 1 characters where each line is one row of the image. 1 means that pixel on (lit).'
  local 'scale' (argOrDefault 5 1)
  local 'left' x
  for ch ('[data:convertType]' imageString 'byte array') {
    if (ch == 10) {
      y += scale
      x = left
    } else {
      if (ch == 49) {'[tft:rect]' x y scale scale c}
      x += scale
    }
  }
}

to tft_drawText s x y color optionalScale optionalBGColor {
  s = ('[data:convertType]' s 'string')
  local 'scale' (argOrDefault 5 2)
  local 'bgColor' (argOrDefault 6 '')
  local 'lines' ('[data:split]' s ('[data:unicodeString]' 10))
  for line ('[data:split]' s ('[data:unicodeString]' 10)) {
    if (isType bgColor 'number') {
      '[tft:text]' line x y color scale false bgColor
    } else {
      '[tft:text]' line x y color scale false
    }
    y += (8 * scale)
  }
}

to tft_drawVector x y angle length color {
  local 'endX' (x + ((length * ('[misc:sin]' (100 * (angle + 90)))) >> 14))
  local 'endY' (y + ((length * ('[misc:sin]' (100 * angle))) >> 14))
  '[tft:line]' x y endX endY color
}

to tft_image s {
  return ('[data:convertType]' s 'string')
}

to tft_resumeOLEDDisplayUpdates {
  '[tft:resumeUpdates]'
}


module Tone Output
author MicroBlocks
version 1 11 
tags tone sound music audio note speaker 
choices tone_NoteName 'nt;c' 'nt;c#' 'nt;d' 'nt;d#' 'nt;e' 'nt;f' 'nt;f#' 'nt;g' 'nt;g#' 'nt;a' 'nt;a#' 'nt;b' 
description 'Audio tone generation. Make music with MicroBlocks!
'
variables _tonePin _toneInitalized _toneLoopOverhead _toneNoteNames _toneArezzoNotes _toneFrequencies 

  spec ' ' 'play tone' 'play note _ octave _ for _ ms' 'str.tone_NoteName num num' 'nt;c' 0 500
  spec ' ' 'playMIDIKey' 'play midi key _ for _ ms' 'num num' 60 500
  spec ' ' 'play frequency' 'play frequency _ for _ ms' 'num num' 261 500
  space
  spec ' ' 'startTone' 'start tone _ Hz' 'num' 440
  spec ' ' 'tone_startNote' 'start note _ octave _' 'str.tone_NoteName num' 'nt;c' 0
  spec ' ' 'tone_startMIDIKey' 'start midi key _' 'num' 60
  spec ' ' 'stopTone' 'stop tone'
  space
  spec ' ' 'attach buzzer to pin' 'attach buzzer to pin _' 'auto' ''
  space
  spec 'r' '_measureLoopOverhead' '_measureLoopOverhead'
  spec 'r' '_baseFreqForNote' '_baseFreqForNote _' 'auto' 'c'
  spec 'r' '_baseFreqForSemitone' '_baseFreqForSemitone _' 'num' 0
  spec ' ' '_toneLoop' '_toneLoop _ for _ ms' 'num num' 440000 100
  spec 'r' '_trimmedLowercase' '_trimmedLowercase _' 'str' 'A. b C...'
  spec ' ' '_tone init note names' '_tone init note names'

to '_baseFreqForNote' note {
  comment 'Return the frequency for the given note in the middle-C octave
scaled by 1000. For example, return 440000 (440Hz) for A.
Note names may be upper or lower case. Note names
may be followed by # for a sharp or b for a flat.'
  local 'normalized note' ('_trimmedLowercase' note)
  'normalized note' = (ifExpression ((at 1 (v 'normalized note')) == 'n') (v 'normalized note') ('[data:join]' 'nt;' (v 'normalized note')))
  '_tone init note names'
  if (('[data:find]' (v 'normalized note') _toneArezzoNotes) > 0) {
    return ('_baseFreqForSemitone' ('[data:find]' (v 'normalized note') _toneArezzoNotes))
  } else {
    return ('_baseFreqForSemitone' ('[data:find]' (v 'normalized note') _toneNoteNames))
  }
}

to '_baseFreqForSemitone' semitone {
  if (_toneFrequencies == 0) {_toneFrequencies = ('[data:makeList]' 261626 277183 293665 311127 329628 349228 369994 391995 415305 440000 466164 493883 246942 277183 277183 311127 311127 349228 329628 369994 369994 415305 415305 466164 466164 523252)}
  if (and (1 <= semitone) (semitone <= (size _toneFrequencies))) {
    return (at semitone _toneFrequencies)
  } else {
    comment 'Bad note name; return 10 Hz'
    return 10000
  }
}

to '_measureLoopOverhead' {
  comment 'Measure the loop overhead on this device'
  local 'halfCycle' 100
  local 'startT' (microsOp)
  repeat 100 {
    digitalWriteOp _tonePin false
    waitMicros halfCycle
    digitalWriteOp _tonePin false
    waitMicros halfCycle
  }
  local 'usecs' ((microsOp) - startT)
  return ((usecs - 20000) / 200)
}

to '_tone init note names' {
  if (_toneNoteNames == 0) {
    _toneNoteNames = ('[data:makeList]' 'nt;c' 'nt;c#' 'nt;d' 'nt;d#' 'nt;e' 'nt;f' 'nt;f#' 'nt;g' 'nt;g#' 'nt;a' 'nt;a#' 'nt;b' 'nt;c_' 'nt;db' 'nt;d_' 'nt;eb' 'nt;e_' 'nt;e#' 'nt;f_' 'nt;gb' 'nt;g_' 'nt;ab' 'nt;a_' 'nt;bb' 'nt;b_' 'nt;b#')
    _toneArezzoNotes = ('[data:makeList]' 'nt;do' 'nt;do#' 'nt;re' 'nt;re#' 'nt;mi' 'nt;fa' 'nt;fa#' 'nt;sol' 'nt;sol#' 'nt;la' 'nt;la#' 'nt;si' 'nt;do_' 'nt;dob' 'nt;re_' 'nt;reb' 'nt;mi_' 'nt;mi#' 'nt;fa_' 'nt;solb' 'nt;sol_' 'nt;lab' 'nt;la_' 'nt;sib' 'nt;si_' 'nt;si#')
  }
}

to '_toneLoop' scaledFreq ms {
  if (_toneInitalized == 0) {'attach buzzer to pin' ''}
  if ('[io:hasTone]') {
    '[io:playTone]' _tonePin (scaledFreq / 1000)
    waitMillis ms
    '[io:playTone]' _tonePin 0
  } else {
    local 'halfCycle' ((500000000 / scaledFreq) - _toneLoopOverhead)
    local 'cycles' ((ms * 500) / halfCycle)
    repeat cycles {
      digitalWriteOp _tonePin true
      waitMicros halfCycle
      digitalWriteOp _tonePin false
      waitMicros halfCycle
    }
  }
}

to '_trimmedLowercase' s {
  comment 'Return a copy of the given string without whitespace
or periods and all lowercase.'
  local 'result' (newList (size s))
  '[data:delete]' 'all' result
  for i (size s) {
    local 'ch' ('[data:unicodeAt]' i s)
    if (and (ch > 32) (ch != 46)) {
      if (and (65 <= ch) (ch <= 90)) {ch = (ch + 32)}
      '[data:addLast]' ch result
    }
  }
  return ('[data:unicodeString]' result)
}

to 'attach buzzer to pin' pinNumber {
  if (pinNumber == '') {
    comment 'Pin number not specified; use default pin for this device'
    if ((boardType) == 'Citilab ED1') {
      _tonePin = 26
    } ((boardType) == 'M5Stack-Core') {
      _tonePin = 25
    } ((boardType) == 'M5StickC') {
      _tonePin = 26
    } ((boardType) == 'Calliope') {
      digitalWriteOp 23 true
      digitalWriteOp 24 true
      _tonePin = 25
    } ((boardType) == 'D1-Mini') {
      _tonePin = 12
    } ((boardType) == 'CodingBox') {
      _tonePin = 32
    } else {
      _tonePin = -1
    }
  } else {
    _tonePin = pinNumber
  }
  _toneLoopOverhead = ('_measureLoopOverhead')
  _toneInitalized = (booleanConstant true)
}

to 'play frequency' freq ms {
  '_toneLoop' (freq * 1000) ms
}

to 'play tone' note octave ms {
  local 'freq' ('_baseFreqForNote' note)
  if (freq <= 10000) {
    waitMillis ms
    return 0
  }
  if (octave < 0) {
    repeat (absoluteValue octave) {
      freq = (freq / 2)
    }
  }
  repeat octave {
    freq = (freq * 2)
  }
  '_toneLoop' freq ms
}

to playMIDIKey key ms {
  local 'freq' ('_baseFreqForSemitone' ((key % 12) + 1))
  local 'octave' ((key / 12) - 5)
  if (octave < 0) {
    repeat (absoluteValue octave) {
      freq = (freq / 2)
    }
  }
  repeat octave {
    freq = (freq * 2)
  }
  '_toneLoop' freq ms
}

to startTone freq {
  if (_toneInitalized == 0) {'attach buzzer to pin' ''}
  if ('[io:hasTone]') {'[io:playTone]' _tonePin freq}
}

to stopTone {
  startTone 0
}

to tone_startMIDIKey key {
  local 'freq' ('_baseFreqForSemitone' ((key % 12) + 1))
  local 'octave' ((key / 12) - 5)
  if (octave < 0) {
    repeat (absoluteValue octave) {
      freq = (freq / 2)
    }
  }
  repeat octave {
    freq = (freq * 2)
  }
  startTone ((freq + 500) / 1000)
}

to tone_startNote note octave {
  local 'freq' ('_baseFreqForNote' note)
  if (freq <= 10000) {
    return 0
  }
  if (octave < 0) {
    repeat (absoluteValue octave) {
      freq = (freq / 2)
    }
  }
  repeat octave {
    freq = (freq * 2)
  }
  startTone ((freq + 500) / 1000)
}

