SHARE
TWEET

Optimizing Character Count for Tweetcarts

a guest Nov 26th, 2017 1,725 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. OPTIMIZING CHARACTER COUNT FOR TWEETCARTS
  2. (Eli Piilonen - 2DArray.net - @2DArray)
  3. (You may host this on your website if you credit me!)
  4.  
  5. ____________________________
  6.  
  7. INTRO CUTSCENE
  8.  
  9. Pico-8 is lovely, and tweetcarts are super fun, but let's say you want to fit some more shit into one of your 140- or 280-character demos.  You'll need some tricks and shortcuts!
  10.  
  11. Here's the plan: We'll take the most recent tweetcart that I've made and break it down to see what kinds of weird code-compression is happening.
  12.  
  13. Sorry if some of this is super obvious stuff that you already know...I'm just gonna try to be comprehensive.
  14.  
  15. First, here's the final source code - if you have Pico-8, you can paste this into a blank file and run it: it's a (halfway-functional variant of) Tetris.
  16.  
  17. cls(9)p={204,108,46,78,142}r=0m=8192l=memcpy::_::flip()q=band
  18. if(d!=0)x=64y=1s=rnd(5)+1l(0,m*3,m)d=0
  19. y+=1l(m*3,0,m)b=btnp()x+=q(b,2)/2-q(b,1)r-=q(b,4)/16
  20. for i=0,7 do
  21. f=cos(r)g=sin(r)u=x+i%4*f-g*i/4v=y+i%4*g+f*i/4
  22. if(p[s-s%1]/2^i%2>=1 and sget(u,v+1,pset(u,v,s))!=9)d=1
  23. end
  24. goto _
  25. // (280 chars)
  26.  
  27. Here's a recording of the game:
  28.  
  29. https://twitter.com/2DArray/status/934234800319287296
  30.  
  31. Basically, the code looks like a bunch of horseshit, so we're gonna have to separate it out a bit.
  32.  
  33. ____________________________
  34.  
  35. LEVEL ONE: LINE-BREAKS
  36.  
  37. The first trick I'd like to talk about is removing line-breaks.  Linebreaks in LUA are often optional, so you can cut out several characters of most "traditionally-written" code.
  38.  
  39. For example, this:
  40.  
  41. cls()
  42. p=5
  43.  
  44. ...can be shortened into this...
  45.  
  46. cls()p=5
  47.  
  48. ...and you save one character. I find that in an average tweetcart, you can generally do this at the very end of the process to remove about 10 or 20 characters (but your mileage may vary). Lines ending with parentheses or other special-characters are often the easiest to use for line-breaks, so it's good to try to end your lines with them.
  49.  
  50. x=sin(a)+y
  51. // (Tough to chain!)
  52.  
  53. vs
  54.  
  55. x=y+sin(a)
  56. // (Easy to chain!)
  57.  
  58. Now...I said the linebreaks are "often optional." Sometimes, removing a linebreak will combine two tokens into one:
  59.  
  60. end
  61. goto _
  62.  
  63. If we try to combine these, we get "endgoto _" and we get a syntax error, so that's no good. Rearranging stuff can sometimes help here, but other times it might not be possible.
  64.  
  65. Here's a common situation when initializing your cart:  You need to set a few variables to their default values.
  66.  
  67. a=5
  68. z=10
  69. r=0
  70.  
  71. You might try using the "comma notation" in LUA to set them all in one line:
  72.  
  73. a,z,r=5,10,0
  74.  
  75. ...but unfortunately, this doesn't save any characters (still 13 total). Instead, we can just smash our original lines together:
  76.  
  77. a=5z=10r=0
  78.  
  79. LUA can parse this correctly, because it knows that each number is "done" if the next symbol is a letter - and so we've saved three characters worth of line breaks!
  80.  
  81. HOWEVER!  Certain letters will break your code if you do this, because in certain cases, LUA can legally recognize numbers which have letters in them:
  82.  
  83. m=0x2000
  84.  
  85. The "0x" prefix means "this number is represented in hexadecimal." If you've used the recently-added fillp() function, you've likely also seen LUA's similar "0b" binary prefix:
  86.  
  87. p=0b1010010110100101
  88.  
  89. Because of this, you can't stick a variable called "b" right after a different variable's declaration. The "5b" in here will break your code:
  90.  
  91. a=5b=10
  92.  
  93. (I just pasted this into a blank cart - not only did it cause an error...it actually crashed the editor entirely in version 0.1.11d. Save your work often!)
  94.  
  95. There are some other letters that will also break when attached directly to a number, but honestly I don't know the full set. To fix the problem, you can either rename your variables to different letters until you find one that's accepted, or sometimes you can just change the order of your declaration (so the special-case character, like B, happens at the beginning of the line, or after some safe, happy parentheses).
  96.  
  97. So...there are lots of missing line-breaks in the Tetris cart.  Let's see how it looks with all of those expanded out, like you'd see in normal, sane code. I'm also putting in some indentation for extra legibility:
  98.  
  99. cls(9)
  100. p={204,108,46,78,142}
  101. r=0
  102. m=8192
  103. l=memcpy
  104. ::_::
  105.     flip()
  106.     q=band
  107.     if(d!=0) x=64 y=1 s=rnd(5)+1 l(0,m*3,m) d=0
  108.     y+=1
  109.     l(m*3,0,m)
  110.     b=btnp()
  111.     x+=q(b,2)/2-q(b,1)
  112.     r-=q(b,4)/16
  113.     for i=0,7 do
  114.         f=cos(r)
  115.         g=sin(r)
  116.         u=x+i%4*f-g*i/4
  117.         v=y+i%4*g+f*i/4
  118.         if(p[s-s%1]/2^i%2>=1 and sget(u,v+1,pset(u,v,s))!=9)d=1
  119.     end
  120. goto _
  121. // (319 chars)
  122.  
  123. This is looking a bit more sensible now!
  124.  
  125. ____________________________
  126.  
  127. LEVEL TWO: RENAMING FUNCTIONS
  128.  
  129. This one's easy, so we'll get through it quick.  Some built-in functions in pico-8 have long names, and sometimes you use the same one more than once in your cart.  In these cases, you can define a variable and assign the function to it, as a way to "rename" a long function:
  130.  
  131. s=sin
  132. p=print
  133. p(s(0))
  134. p(s(.1))
  135. p(s(.7))
  136. p(s(.8))
  137.  
  138. If the function name is short and you don't use it much, you might not actually save any characters...so be sure to check your changes in a character-counter all the time.
  139.  
  140. ____________________________
  141.  
  142. BONUS ROUND:  BUILT-IN "PRINT" SHORTCUT
  143.  
  144. This one's not used in the Tetris cart, but it's super handy, and I don't think it's in the manual, so let's cover it real quick.
  145.  
  146. print("hello, tailor")
  147.  
  148. We can shorten this with a strange, generally inexplicable built-in shorthand:
  149.  
  150. ?"hello, tailor"
  151.  
  152. When we do this, we have to put it on its own line, and its line can't be indented at all.  Like the standard print() function, the shorthand can take multiple arguments (in the same order as usual: message, x, y, color):
  153.  
  154. ?"hello, tailor",64,64,time()*8
  155.  
  156. ____________________________
  157.  
  158. LEVEL THREE: IF-STATEMENTS
  159.  
  160. Here's the standard pattern for an if statement in LUA:
  161.  
  162. if (t()>5) then
  163.     print("hello, tailor")
  164. end
  165. // (43 chars)
  166.  
  167. There are several ways to shorten this.  One simple option is to remove some spaces:
  168.  
  169. if(t()>5)then
  170. print("hello, tailor")end
  171. // (39 chars)
  172.  
  173. Now...I didn't learn this next bit for a long time, but the parentheses in LUA's if statements are optional (but I still generally use them anyway, out of force of habit). Luckily for us, the letter "T" isn't one of those "legal number characters," so we can do this:
  174.  
  175. if t()>5then
  176. print("hello, tailor")end
  177. // (38 chars)
  178.  
  179. Another option is to use LUA's "single-line if statement" shorthand - this one does require the parentheses around the conditional:
  180.  
  181. if(t()>5)print("hello, tailor")
  182. // (31 chars)
  183.  
  184. This performs the same logic as the original version, but we've cut more than a quarter of our starting characters!
  185.  
  186. But what if we want to do more-than-one-thing when our if statement passes its check? For our if statement's block to contain multiple lines, it needs a "then" and "end" pair.
  187.  
  188. But don't worry! It turns out that we can just jam all of it onto one line by combining our "single-line-if-statement" trick with our "multiple-statements-on-one-line" trick:
  189.  
  190. if(t()>5)print("hello, tailor")print("and goodbye")
  191.  
  192. Any stuff after the if statement's parentheses (but on the same line) is all considered to be "inside the if-block," so either both print statements get called, or both print statements get skipped (never just-one-of-them). If you can combine it all into one line like this, you can still cut out your "then" and "end" statements!
  193.  
  194. Let's expand the first if statement in Tetris:
  195.  
  196. cls(9)
  197. p={204,108,46,78,142}
  198. r=0
  199. m=8192
  200. l=memcpy
  201. ::_::
  202.     flip()
  203.     q=band
  204.     if (d!=0) then
  205.         x=64
  206.         y=1
  207.         s=rnd(5)+1
  208.         l(0,m*3,m)
  209.         d=0
  210.     end
  211.     y+=1
  212.     l(m*3,0,m)
  213.     b=btnp()
  214.     x+=q(b,2)/2-q(b,1)
  215.     r-=q(b,4)/16
  216.     for i=0,7 do
  217.         f=cos(r)
  218.         g=sin(r)
  219.         u=x+i%4*f-g*i/4
  220.         v=y+i%4*g+f*i/4
  221.         if(p[s-s%1]/2^i%2>=1 and sget(u,v+1,pset(u,v,s))!=9)d=1
  222.     end
  223. goto _
  224.  
  225. Even more sensible than before!
  226.  
  227. Now, let's look at that last if statement.  Spoiler: It's a weird one.
  228.  
  229. if(p[s-s%1]/2^i%2>=1 and sget(u,v+1,pset(u,v,s))!=9)d=1
  230.  
  231. We're going to do this one backwards - we'll start with the standard (more legible) version, and then we'll work toward the final version.
  232.  
  233. if(p[s-s%1]/2^i%2>=1) then
  234.     pset(u,v,s)
  235.     if (sget(u,v+1)!=9) then
  236.         d=1
  237.     end
  238. end
  239. // (80 chars)
  240.  
  241. We can ignore that first conditional "somethingSpooky>=1" statement for now (we'll get to it later).  For now, let's just try to shorten out our ifs and thens and ends.  Like before, we can shorten the interior if statement by making it one line:
  242.  
  243. if(p[s-s%1]/2^i%2>=1) then
  244.     pset(u,v,s)
  245.     if(sget(u,v+1)!=9)d=1
  246. end
  247. // (66 chars)
  248.  
  249. Now...you might try to combine all of these lines into one giant one with the previous "shorthand if" trick. Unfortunately, trying it:
  250.  
  251. if(p[s-s%1]/2^i%2>=1)pset(u,v,s)if(sget(u,v+1)!=9)d=1
  252.  
  253. ...gives us a syntax error ("'then' expected near 'd'").  Honestly, I don't know why, other than...uh, we pushed it too far. "If" statements are a bit sensitive when smashed together with other lines, particularly when skipping your then/end, and I don't know all of the rules...but I do know that the previous example doesn't run, so we need to do something else.
  254.  
  255. The thing that saves us here is a common compiler optimization related to AND statements.
  256.  
  257. if (A()==true AND B()==true) then
  258.     // do something
  259. end
  260.  
  261. A quick note from Captain Obvious: An AND statement will only return true if both of its surrounding statements return true.
  262.  
  263. A quick note from Captain Not-Quite-As-Obvious: If the first check in the AND statement fails, the second one will not be executed at all, because no matter what it returns, the AND statement will still fail.  This means we could combine our previous two layers of if statements into a single, unified line of hacky wonkery. Utility functions with no outputs can be included in our logical statement, as long as our logic is expecting those utility functions to return a nil value.
  264.  
  265. if(p[s-s%1]/2^i%2>=1 and(pset(u,v,s)or sget(u,v+1)!=9))d=1
  266. // (58 chars)
  267.  
  268. At this point we've done pretty well! I've only got one more idea for this line, and it's a different way to include that pset() call - this is our utility function which returns nil.
  269.  
  270. Right now, we're trying to fit its nil output somewhere in our logic where it won't cause any problems, but we've got an extra OR statement and some parentheses that I want to remove.
  271.  
  272. (pset(u,v,s)or sget(u,v+1)!=9)
  273.  
  274. Instead of using our nil as a part of the logical statement, we can use it as an ignored function input.
  275.  
  276. sget(u,v+1,pset(u,v,s))!=9
  277.  
  278. This leaves us with the final line, as included in the cart:
  279.  
  280. if(p[s-s%1]/2^i%2>=1 and sget(u,v+1,pset(u,v,s))!=9)d=1
  281. // (55 chars)
  282.  
  283. Woof!
  284.  
  285. Now that we've gotten through the formatting tricks, we can see the Tetris code fully-expanded - I'm also swapping out the function-nicknames for full names:
  286.  
  287. cls(9)
  288. p={204,108,46,78,142}
  289. r=0
  290. m=8192
  291. ::_::
  292.     flip()
  293.     if (d!=0) then
  294.         x=64
  295.         y=1
  296.         s=rnd(5)+1
  297.         memcpy(0,m*3,m)
  298.         d=0
  299.     end
  300.     y+=1
  301.     memcpy(m*3,0,m)
  302.     b=btnp()
  303.     x+=band(b,2)/2-band(b,1)
  304.     r-=band(b,4)/16
  305.     for i=0,7 do
  306.         f=cos(r)
  307.         g=sin(r)
  308.         u=x+i%4*f-g*i/4
  309.         v=y+i%4*g+f*i/4
  310.         if(p[s-s%1]/2^i%2>=1) then
  311.             pset(u,v,s)
  312.             if (sget(u,v+1)!=9) then
  313.                 d=1
  314.             end
  315.         end
  316.     end
  317. goto _
  318. // (377 chars)
  319.  
  320. ____________________________
  321.  
  322. BONUS ROUND: MEMCPY AND YOU
  323.  
  324. There are two places where we call pico8's memcpy() function.
  325.  
  326. // initializing:
  327. m=8192
  328.  
  329. // save screen to sprite sheet:
  330. memcpy(0,m*3,m)
  331.  
  332. // paste sprite sheet to screen:
  333. memcpy(m*3,0,m)
  334.  
  335. 0x0 is the memory address of the sprite sheet in pico8, 0x6000 (or 8192*3 in base 10) is the screen buffer, and both of those fields have a size of 0x2000 (or 8192).  That second memcpy() call is equivalent to this:
  336.  
  337. spr(0,0,0,16,16)
  338.  
  339. ...but it's got less characters.  Woo!
  340.  
  341. ____________________________
  342.  
  343. BONUS-BONUS ROUND: HANDLING INPUT
  344.  
  345. Player input in Tweetjam-Tetris consists of three buttons: Tap to move left, tap to move right, and tap to rotate 90 degrees.  Unlike real Tetris, there's no "drop" button, and instead the pieces just always fall really fast (but they also fall a very large distance to balance it out, or something).
  346.  
  347. Tweetjam-Tetris' trick for handling all of these came from Morgan McGuire (@CasualEffects on twitter):
  348.  
  349. q=band
  350. b=btnp()
  351. x+=q(b,2)/2-q(b,1)
  352. r-=q(b,4)/16
  353.  
  354. More bitmasks and bitshifting!  "b" stores a bitmask of all the buttons pressed, then we use some bitwise AND operations to separate out the bits and alter our position/rotation values. x changes by increments of 1, and r changes by increments of 1/4.  Remember that band(b,4) will return either 0 or 4, so dividing by 16 gives us either 0 or 1/4.
  355.  
  356. I love this trick! The x+= line shows how you could easily extend this to handle 4-direction input for other games with just a few extra characters.
  357.  
  358. ____________________________
  359.  
  360. BONUS-BONUS-BONUS ROUND: GAME LOOP SHORTCUT
  361.  
  362. One more quick trick that you may have already seen in a bunch of other carts:
  363.  
  364. ::_::
  365. // game loop
  366. flip()goto _
  367.  
  368. You can also use a single letter instead of an underscore for your goto label, but for tweetcarts, I like how stupid and illegible it looks when you have ::_:: at the beginning of your code.
  369.  
  370. flip() makes the console wait for the end of the current 30fps frame.  This goto method saves a few characters compared to the usual game loop in pico8, but it does the same thing:
  371.  
  372. function _update()
  373. // game loop
  374. end
  375.  
  376. ____________________________
  377.  
  378. LEVEL FIVE: DEFINING TETRIS BLOCKS
  379.  
  380. Now that all the wacky syntax is out of the way, we can finally dial in on the stuff that's specific to this cartridge. First, let's figure out the way that the different piece shapes are stored.
  381.  
  382. Here's where we define all of the shapes:
  383.  
  384. p={204,108,46,78,142}
  385.  
  386. You might feel that something is wrong because that's just numbers and no shapes, or you might think something is wrong because it should be seven numbers instead of five.
  387.  
  388. If you're in the second camp, then congratulations! You're a step ahead of me, and you just won several internet points. (You can call Comcast to redeem your points for valuable prizes.)
  389.  
  390. The key to this list of numbers is that each item is a bitmask with 8 bits (or, "an integer from 0-255").  These 8 true/false values are interpreted as a 4x2 tilemap:
  391.  
  392. 0010
  393. 1110
  394.  
  395. The "1" tiles in that tilemap form a sideways L shape.  00101110 in binary is the same as 46 in base 10, so we can save a bunch of characters by doing this conversion outside of our code and storing a 46 instead of something more legible.
  396.  
  397. This pre-conversion idea also applies when storing hex values: 0x2000 is a common hex value when dealing with pico8's memory layout, but if you store it as 8192 (the same number in base 10), you save a character.  You'll never want to use the binary "0b" prefix in an optimized tweetcart - when doing a fillp() call, for example - because it's always going to be shorter to represent that number in base 10.
  398.  
  399. Okay, so we've defined five shapes out of the seven standard Tetris pieces, and we're just going to leave the other two out so we can save some characters.  We'll skip the reverse-lightning-bolt, since it's, uh, relatively easy to forget about when the forward-lightning-bolt is present.
  400.  
  401. Then...we'll also skip the Line Piece.
  402.  
  403. I'm sorry.  I'm so sorry.  I know that this is Tetris sacrilege.  The truth is, Tweetcart-Tetris doesn't even do line-clearing, since probably no one will play it for long enough to fill a whole line (I haven't even gotten close, myself).  With this in mind, the line-piece isn't really as great and fun as it usually would be.
  404.  
  405. The second reason...is that if none of the pieces use the two far-right tiles in their 4x2 tilemap, then I can get away with slightly-less-accurate rotation code without breaking the pieces (and in doing so, save some characters).
  406.  
  407. Anyway, now we've defined our set of five pieces. How do we draw them?
  408.  
  409. ____________________________
  410.  
  411. FINAL BOSS: DRAWING SHAPES
  412.  
  413. Here's our expanded version of the loop where we iterate through the bits in our current piece's 4x2 map:
  414.  
  415. for i=0,7 do
  416.     f=cos(r)
  417.     g=sin(r)
  418.     u=x+i%4*f-g*i/4
  419.     v=y+i%4*g+f*i/4
  420.     if (p[s-s%1]/2^i%2>=1) then
  421.         pset(u,v,s)
  422.         if (sget(u,v+1)!=9) then
  423.             d=1
  424.         end
  425.     end
  426. end
  427.  
  428. f, g, u, and v are related to piece rotation - it's applying a standard 2D rotation matrix, where the input x value is i%4, and the input y value is i/4. This gives us our 2D index into our 4x2 tilemap - x is 0-3 and y is 0-1.
  429.  
  430. Really, the input y value should be flr(i/4) so it'd always be exactly 0 or 1, but as I mentioned before, being less accurate (and omitting the Line Piece) saves five characters here.
  431.  
  432. Ultimately, (u,v) is the current screen position where we're testing whether or not the falling piece has a block...which brings us back to this cluttered conditional statement:
  433.  
  434. if (p[s-s%1]/2^i%2>=1) then
  435.  
  436. First of all, let's remember that "p" is our list of shapes, and "i" is our 0-to-7 iterator.  This leaves "s," which represents the index of our current piece.
  437.  
  438. ...But like before, I want to get rid of flr() statements wherever possible, so s ends up being an important integer-piece-index, plus a random-and-meaningless fractional component.  We can do "flr(s)" to drop the fractional part, but if we do "s-s%1" instead, we save one character.  % is pretty common in tweetcarts, and pico8 in general, but just in case, it's the "remainder" (or "modulo") operator. s%1 gives us the fractional component (the remainder when we divide by 1), so subtracting it gives us just the integer component of s (which is a valid array index).
  439.  
  440. So let's look at the line again, swapping that p indexing stuff for a variable called "piece."
  441.  
  442. if (piece/2^i%2>=1) then
  443.  
  444. Now let's add some parenthesis to make the order of operations more clear:
  445.  
  446. if ( (piece/(2^i))%2 >= 1) then
  447.  
  448. Ultimately, this is another strange indexing operation.  We have a bitmask with 8 bits, and we have an index to tell us which bit to check.  We want to know whether or not that bit is 1.
  449.  
  450. This means we'll be doing some bit-shifting:  We want to take a bitfield, move its items around, and ignore most of it.
  451.  
  452. Let's consider our L piece again:
  453.  
  454. 0010
  455. 1110
  456.  
  457. Or:
  458.  
  459. 00101110
  460.  
  461. Let's our bits are indexed from 0 to 7, bit 0 is on the far right, and our current index (i) is 0.  We can check the far-right bit in two ways:  The first is to perform a bitwise AND on the piece and the number 1.
  462.  
  463. if (band(piece,1)==1) then
  464.  
  465. Another option is to use the % operator:
  466.  
  467. if (piece%2==1) then
  468.  
  469. If we want to test any bit instead of just bit 0, we need to change our methods a bit:
  470.  
  471. if (band(piece,2^i)==1) then
  472.  
  473. This works because each bit's value is double that of the previous one (in the same way that in base 10, each digit is "ten times as powerful" as the previous).
  474.  
  475. We can do a similar thing with the modulo version:
  476.  
  477. if ((piece/(2^i))%2>=1) then
  478.  
  479. Since the order of operations is on our side this time, we don't need any grouping symbols:
  480.  
  481. if (piece/2^i%2>=1) then
  482.  
  483. Note that the % version uses "greater than or equal" instead of "exactly equal," like the band() version.  This is because even though our modulus operation can remove all of the larger bits than the first one, pico8 only has one number type, which always includes fractional bits...so we're left with a bunch of straggling fractional-component bits to the right of our relevant ones-digit. We can ignore all of them by using the >= to say that "as long as we have the ones digit set to 1, we don't care what the fractional component is."
  484.  
  485. And there you have it - that's the most complicated part of this thing, I think.  This wacky indexing happens at the beginning of the cart's final if statement, and then the second half of the if statement is drawing the current pixel and then checking if the pixel directly below it is already occupied.  Here's the expanded version again:
  486.  
  487. if (p[s-s%1]/2^i%2>=1) then
  488.     pset(u,v,s)
  489.     if (sget(u,v+1)!=9) then
  490.         d=1
  491.     end
  492. end
  493.  
  494. The 9 in the sget() line is the game's background color, and d being set to 1 means "the current piece has died."  You can see at the beginning of the overall code that when d is 1, we save the screen to the sprite sheet, pick a new piece, and put it at the top-center of the screen.
  495.  
  496. ____________________________
  497.  
  498. EPILOGUE
  499.  
  500. Okay, uh, so this turned out to be a lot longer than I expected. I hope you've learned something, and I hope to see some cool stuff out of you! Send me the shit you make! I want to see it!
  501.  
  502. // (20,117 chars)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top