recursal/Fanatic-Fandom huggingface dataset:
Alien Abduction

Creator
 Genre
 Player Count

## Description

“Fetch" as many "puny humans” as you can “for...gruesome experiments etc.” for your High Commander XL'ARGH!

## Rules

* Abduct humans! The player must maneuver their U. F. O. down towards Earth while avoiding projectiles launched from buildings and later planes that travel the skies. Once the player is close enough to a human, they must use their tractor beam to suck it up, then take them high into the atmosphere so the alien mothership can collect the human from there.
* Being hit by a plane or building projectile will cost the player a U. F. O. and the game will end when there are no more U. F. O.s in reserve.
* If a plane's fire hits a human or if a human dies after being dropped by the U. F. O. (if it is too high up) being shot down then the player will be penalized 100 points for each lost human.

## Controls

* Use the Z or X keys to start a game.
* Use the arrow keys to move U. F. O.s.
* Use the Z key to activate the tractor beam.
* Use the Escape or Enter keys to pause the game.
Poke2

poke2( addr, [...] )
Writes one or more 16-bit values to contiguous groups of two consecutive memory locations.
addr

The address of the first memory location.

...

The 16-bit values to write to memory. If these are omitted, a zero is written to the first 2 bytes.

The `poke2()` function writes one or more 16-bit values to contiguous groups of two consecutive bytes in the addressable memory region (0x0000-0x7fff). The values are interpreted in the Little Endian representation, which stores the lowest 8 bits in the first byte.

See Memory for information about the memory layout.

## Examples

```
poke2(0x4300, 0x0cff)

b0,b1 = peek(0x4300, 2) -- 0xff,0x0c

```

## See also

* Memory
* `peek()`
* `peek2()`
* `peek4()`
* `poke()`
* `poke4()`
* `memcpy()`
* `reload()`
* `cstore()`
* `memset()`
Color

color( [col] )
Sets the draw color in the draw state.
col

The index of the color to use. Default is 6 (light gray).

*return-value*

The previous draw color.
The col parameter accepts a numeric color argument in the range of 0 to 15, representing a color from the 16-color PICO-8 palette. This color will be saved in the draw state to use for future draw calls. This is sometimes called the "pen color".

Many graphics functions also have an optional col parameter that behaves exactly like the one here. When this parameter is not filled, the current color in the draw state is used by default. When an actual color argument is provided to these functions, it is used, and then the draw state is updated to use that color in the future, as if `color()` had been called with that value.

The previous color is returned when calling `color()`, allowing it to be saved and restored if needed.

## Use with patterns

Normally only the lo nybble of the value passed in `col` matters. However, when using fill patterns (see `fillp()` for details), the hi nybble represents the second color in the pattern. For example, to fill with brown and orange, call `col(0x49)`.

## Technical notes

The current pen color is memory-mapped and may be read or written directly with `peek()` and `poke()`:

* 0x5f25 / 24357: current pen color

## Examples

```
cls()

color(7)  -- white
circfill(20, 20, 10)
circfill(60, 60, 10)

color(8)  -- red
circfill(20, 60, 10)
circfill(60, 20, 10)

pal(7, 10)  -- white -> yellow
color(7)
circfill(20, 100, 10)
circfill(60, 100, 10)

-- get the current color from its memory-mapped address
cur\_color=peek(0x5f25)

```

## See also

* Draw state
* Graphics
* `circ()`
* `circfill()`
* `line()`
* `print()`
* `pset()`
* `rect()`
* `rectfill()`
* `sset()`
* `pal()`
Sfx

sfx( n, [channel,] [offset,] [length] )
Plays a sound effect.
n

The number of the sound effect to play (0-63), -1 to stop playing sound on the given channel, or -2 to release the sound of the given channel from looping.

channel

The channel to use for the sound effect (0-3). The default is -1, which chooses an available channel automatically. Can be -2 to stop playing the given sound effect on any channels it plays on.

offset

The note position in the sound effect to start playing (0-31). The default is 0 (the beginning).

length

The number of notes in the sound effect to play (0-31). The default is to play the entire sound effect.

A sound effect is a sequence of tones or notes. You can design sounds in the sound effect editor. A cartridge can have up to 64 sounds, numbered 0-63. A sound effect can represent a single effect played by a call to the `sfx()` function, or can be a series of notes played in a single channel of a music pattern.

The `sfx()` function plays a sound on one of PICO-8's four sound channels. If an explicit channel number is not specified, PICO-8 will attempt to select a channel automatically, giving priority to an unused channel so that two concurrent sounds may overlap.

If music is currently playing, the sound effect will attempt to honor the *channel mask* set by the call to the `music()` function to avoid channels that are important to the music. If you specify an explicit channel to `sfx()`, the music's channel mask is ignored.

It's possible to detect the current sfx being played for each channel, along with the index of the current note of each sfx. See `stat(16..23)` for details.

## Examples

```
-- play sound 3 on any available channel
sfx(3)

-- play sound 3 starting from note position 21 on any available channel
sfx(3, -1, 21)

-- stop playing sound on channel 2
sfx(-1, 2)

-- release a looping sound on channel 2
sfx(-2, 2)

```

## See also

* `music()`
* `stat(16..23)`
Init

The `_init()` function is called by PICO-8 to initialize a cartridge.

This function can be defined in a game's source code. It takes no arguments.

PICO-8 calls this function after evaluating all of the source code. In typical usage, a cartridge's source code includes definitions for functions and variables, an `_init()` function, and then an `\_update()` function and `\_draw()` function for the game loop. PICO-8 calls `_init()` once before starting the game loop.

If any code outside of functions has side effects, these effects occur before `_init()` is called. (This is trivial if the code consists only of function and global variable definitions.)

## Examples

```
function \_init()
  -- start player in lower center of screen
  player\_x=64
  player\_y=100
end

```

## See also

* game loop
* `_update()`
* `_draw()`
Pget

pget( x, y )
Gets the color value of a pixel at the given coordinates.
x

The x coordinate.

y

The y coordinate.

The `pget()` function reads the color value of a pixel from the graphics buffer.

It will read from the buffer even if the buffer has not yet been copied to the display.

It will return 0 (black) if given coordinates outside the range (0-127,0-127).

## Examples

```
pset(10, 10, 7)                 -- sets (10, 10) to white
print(pget(10, 10), 0, 112, 7)  -- prints 7

pset(10, 10, 8)                 -- sets (10, 10) to red
print(pget(10, 10), 0, 120, 7)  -- prints 8

flip()  -- displays the red (8) pixel and the messages

```

## See also

* Graphics
* `mget()`
* `mset()`
* `pset()`
* `sget()`
* `sset()`
Tostring

tostring( val )
Converts a non-string value to a string representation, using the vanilla Lua implementation.
val

The value to convert
Returns the string representation of the value, using vanilla Lua code instead of PICO-8's custom `tostr()` function. Please refer to that function for full documentation, as that is the one typically used, and therefore only the differences from it are documented here.

At the moment, these are the known differences from PICO-8's custom implementation:

* There is only one parameter, whereas `tostr` accepts a second optional argument to control formatting of numbers.

* Object references (tables, functions, coroutines), are formatted without square brackets and include the internal pointer associated with the reference, e.g. `"table: 0x11eada34"` vs. `tostr()`'s simpler `"[table]"`.

* Passing nothing, also known as the "empty" value, results in a runtime error, whereas `tostr()` will return a zero-length string.

* The string version of `nil` will not have square brackets.

(If you, the reader, know of any other differences, please feel free to document them here.)

## Warning

As an undocumented function, `tostring()` cannot be relied on for a game. Its functionality may change or be removed in future versions. Still, some may find a pragmatic use for it in tools or demos. Just be aware that you use it at your own risk.

## Examples

```
s = 'v: '..tostring(12345)            -- 'v: 12345'
s = 'v: '..tostring(-12345.67)        -- 'v: -12345.67'

s = 'v: '..tostring(0x0f)             -- 'v: 15'

-- runtime error: attempt to concatenate a boolean value
s = 'v: '..true

s = 'v: '..tostring(true)             -- 'v: true'
s = 'v: '..tostring('my string')      -- 'v: my string'

s = 'v: '..tostring(nil)              -- 'v: nil'
s = 'v: '..tostring({1, 2, 3})        -- 'v: table: 0x0f31335e'

f = function() print('hi') end
s = 'v: '..tostring(f)                -- 'v: function: 0x0f313c1a'

-- f is a function that does not return a value
f = function() return end
a = 'v: '..tostring(f())              -- runtime error

```

## See also

* `tonum()`
* `tostr()`
* Math
* Lua
Battlebone

Creator
 Genre
 Player Count

## Description

You are stuck in a dank chamber. Survive as long as you can against the skeleton hordes.

## Rules

* One or more skeletons will instantly appear at the beginning of a game. Their location can be seen on the radar display at the top left area of the screen.
* Each skeleton takes three hits from the player’s sword in order to be destroyed. One or more skeletons will instantly take a defeated skeleton’s place, however.
* Skeletons can inflict damage on the player which is tracked via the bar at the top center of the screen. Once the bar is totally depleted the game ends. However, the player can earn points and regain a bit of health by touching the giant gold doubloons on the playfield (shown on the radar).

## Controls

* At the title screen, press z, c or x to start the game.
* Use the arrow keys to move.
* Use the x or z keys to stab.
* Use the enter or p key to pause the game and/or reset the cart.
Bor

Superseded / Deprecated
The feature described in this article has been superseded by a newer feature. This feature still works in PICO-8, but the new feature should be used instead. See the article's "Superseded by..." section for specific details.

bor( first, second )
Calculates the bitwise-or of two numbers.
first

The first number.

second

The second number.

*return-value*

The bitwise-or of first and second.
## Superseded by `|` operator

The `|` operator added in 0.2.0 performs the same function as `bor()` and is now the recommended way to do bitwise or, as it uses fewer tokens, costs fewer cycles at runtime, and runs on the real host CPU much more efficiently. Simply replace `bor(a,b)` with `a|b`.

## Examples

```
-- 0x5 = 0101 binary
-- or 0x9 = 1001 binary
-- -------
-- 0xd = 1101 binary
print(bor(0x5, 0x9))  -- 13 (0xd)

print(0x5 | 0x9)      -- preferred method

```

## See also

* Math
* `band()`
* `bxor()`
* `bnot()`
* `lshr()`
* `shl()`
* `shr()`
* `rotl()`
* `rotr()`
Keyboard Shortcuts

*!!! Work in progress !!!*

Not all PICO-8 hardware has a keyboard, but when it does, there are many keyboard shortcuts that one can use. Known shortcuts are listed here.

**Important:** the lists below all start with the shortcuts for a **QWERTY** keyboard layout on a **Windows** build of PICO-8. Key bindings for other keyboard layouts or platform builds are only listed if they are known to be *different* from the Windows Build.
If your key isn't listed, or doesn't work right, try to use the Windows-style shortcut the way you would usually expect one to be done in your own OS. For instance, if you know Undo is Ctrl-Z on Windows, you'd want to try Cmd-Z on MacOS. Certain MacOS functions, but not all, permit the use of either the Ctrl or Cmd keys interchangeably. For instance, both Ctrl+C and Cmd+C will copy text on MacOS. As such, certain functions may have multiple redundant shortcuts listed under the MacOS column. As these are functionally equivalent, you can choose whichever shortcut works best for your workflow and/or preference.
Also, if you are on a different regional layout, such as AZERTY or QWERTZ, try using the key that would be in the same *physical* position as the QWERTY key. And remember, there is a `keyconfig` command you can use to change in-game button assignments.
**Readers with knowledge of other platforms are encouraged to fill in the blanks if they know of keys that differ from the Windows layout.** Don't worry too much about following the tricky formatting in these tables, unless you want to. Feel free to just enter whatever helpful notes you have, even if they aren't put into the tables. Someone else can do the formatting later if needed. Thanks!

## While running

See `btn()` for details on default controller/keyboard mappings, and `keyconfig` for info on changing those mappings.

## Sprite editor

(n/a?)

Lower sprite sheet area:

Note: When a sprite or range of sprites is copied to the clipboard, they may be pasted into other programs as a text-encoded representation. This representation can be uploaded in a BBS post and will show as the actual sprite. Similarly, a sprite encoded in text may be copied from outside of PICO-8 and pasted into the sprite editor.

## SFX editor

#### Note view

*For each of the transpose shortcuts, you need to have notes selected.*
Making the player move

## Coding

The solution of making the player move is to change the players **x** and **y**.

To do that we need to make 2 variables named **x** and **y**,

```
player = {x=0,y=0}

```
after we do that we need to actually draw the sprite so we need to make a draw function.

```
player = {x=0,y=0}

function \_draw()
 spr(1,player.x,player.y)
end

```
Now we need to change the **x** and **y**.

```
player = {x=0,y=0}

function \_update()
 if btn(→) then
    player.x += 1
 end

 if btn(←) then
    player.x -= 1
 end

 if btn(↑) then
    player.y -= 1
 end

 if btn(↓) then
    player.y += 1
 end

function \_draw()
 spr(1,player.x,player.y)
end

```
If you do this then you are done!

## Explanation

If i press the right (or the binded key) then the player.x is gonna add a one and the sprite will move cause its using the player.x.

-- Before i press right

-- After i press right

This goes for every direction.
Peek2

peek2( addr, [n] )
Reads one or more 16-bit values from contiguous groups of two consecutive memory locations.
addr

The address of the first memory location.

n

The number of values to return. (1 by default, 32767 max)
The `peek2()` function reads and returns 16-bit values from groups of two consecutive bytes in the addressable memory region (0x0000-0x7fff). The value is interpreted in the Little Endian representation, which stores the lowest 8 bits in the first byte.

See Memory for information about the memory layout.

## % operator

The unary-`%` operator added in 0.2.0 performs the same function as `peek2(address)` and is now the recommended way to read one 16-bit word of memory at a time, as it uses fewer tokens, costs fewer cycles at runtime, and runs on the real host CPU much more efficiently. Simply replace `peek2(address)` with `%address`.

## Examples

```
poke(0x4300, 0xff, 0x0c)

b = peek2(0x4300)  -- 0x0cff, or 3327 in decimal

b = %0x4300        -- preferred method

```

## See also

* Memory
* `peek()`
* `peek4()`
* `poke()`
* `poke2()`
* `poke4()`
* `memcpy()`
* `reload()`
* `cstore()`
* `memset()`
Храм Героев

* Кодекс Героя
* Усиление снаряжения
* Храм Дракона
* Срытая энергия - 95 lvl.
* Звёздная душа - 88 lvl.
* Талант - 70 lvl.
* Ядра рун - 90 lvl.

## Защита Души Зверя

По достижении 55 уровня герои могут начать связывать компоненты Души зверя. Эти души являются средством увеличения атрибутов вашего героя и предоставления ему дополнительных навыков, которые он может использовать в бою.

После того, как Душа установлена, ее можно удалить и заменить, но она не может быть установлена на другого героя без предварительного освобождения, что стоит 5 драгоценных камней. Установив Душу, вы можете начать процесс совершенствования и развития души, чтобы увеличить статические бонусы, которые она дает вашему герою.

В настоящее время существует 10 наборов душ зверей. Каждый набор состоит из 4 предметов и может быть синего, фиолетового или оранжевого цвета. По мере того, как герой собирает больше предметов из определенного набора, он приобретает новые навыки зверя в бою. Эти навыки будут повышаться по мере того, как вы будете собирать и улучшать души, которые вы экипировали. Кроме того, чем выше качество Души Зверя, тем выше уровень, которым может стать навык Зверя. Души зверей оранжевого качества, полностью развитые и усовершенствованные, полностью пробудят силу Зверя и повысят все навыки Зверя, которые вы получите от него.

* Агарес (Поддержка мага) - это набор, который существенно продлит жизнь вашему магу. Душа увеличивает здоровье, броню и сопротивление магии.
* Смертельный Скорпион (физическая поддержка)
* Свирепый Грифон (физический ДПС)
* Морозный дракон (наполовину танк / наполовину ДПС)
* Гигантское Чудище (Чистый Танк)
* Святой Единорог (Целитель)
* Бессмертный Феникс (Маг DPS) - Набор может резко увеличить наносимый урон, превращая одного героя в целую армию.
* Кошмар души (Поддержка мага)
* Тиамат (Чистый Танк)
* Гидра подземного мира (Устойчивая атака / Герой двойной атаки)===
Bxor

Superseded / Deprecated
The feature described in this article has been superseded by a newer feature. This feature still works in PICO-8, but the new feature should be used instead. See the article's "Superseded by..." section for specific details.

bxor( first, second )
Calculates the bitwise-xor (exclusive or) of two numbers.
first

The first number.

second

The second number.

*return-value*

The bitwise-xor of first and second.
## Superseded by ^^ operator

The `^^` operator added in 0.2.0 performs the same function as `bxor()` and is now the recommended way to do bitwise xor, as it uses fewer tokens, costs fewer cycles at runtime, and runs on the real host CPU much more efficiently. Simply replace `bxor(a,b)` with `a^^b`.

## Examples

```
-- 0x5 = 0101 binary
-- xor 0x9 = 1001 binary
-- -------
-- 0xc = 1100 binary
print(bxor(0x5, 0x9))  -- 12 (0xc)

print(0x5 ^^ 0x9)      -- preferred method

```

## See also

* Math
* `band()`
* `bor()`
* `bnot()`
* `lshr()`
* `shl()`
* `shr()`
* `rotl()`
* `rotr()`
Header

PICO-8 injects a header and footer into every lua program before running it. These snippets implement some API calls and defines the creation and handling of the main game loop and functions. As of 0.1.12c they are as follows:

Header:

```
\_pausemenu = {}

function menuitem(index, label, callback)
 if (index < 1 or index > 5) then return end
 \_pausemenu[index] = {}
 \_pausemenu[index].label = label
 \_pausemenu[index].callback = callback
 \_menuitem(index, label)
end

function all(c)
 if (c == nil or #c == 0) then return function() end end
 local i = 1
 local li = nil
 \_\_refund\_cpu\_\_(-16)
 return function()
  if (c[i] == li) then i = i + 1 end
  while (c[i] == nil and i <= #c) do i = i + 1 end
  li = c[i]
  \_\_refund\_cpu\_\_(-17)
  return li
 end
end

function foreach(c, \_f) for i in all(c) do \_f(i) end end

function count(c)
 local total = 0
 for i = 1, #c do if c[i] ~= nil then total = total + 1 end end
 return total
end

function add(c, i)
 if (c == nil) then return end
 local num = #c
 c[num + 1] = i
 return i
end

function del(c, i)
 if (c == nil) then return end
 local num = #c
 if (num < 1) then return end
 local j
 local k
 for j = 1, num do
  if c[j] == i then
   for k = j, num - 1 do c[k] = c[k + 1] end
   c[num] = nil
   return i
  end
 end
end

```

Unknown:

```
if (\_mainloop) then
 \_mainloop()
else
 print("no \_mainloop()")
end

```

Footer:

```
\_end\_of\_program = 1

if (\_init ~= nil) then \_init() end

\_set\_mainloop\_exists(0)

if (\_mainloop ~= nil) then \_set\_mainloop\_exists(1) end

if (\_update60 ~= nil) then
 \_set\_fps(60)
 \_update = nil
else
 \_set\_fps(30)
end

if (\_mainloop == nil and (\_draw ~= nil or \_update ~= nil or \_update60 ~= nil)) then
 \_set\_mainloop\_exists(2)
 \_mainloop = function()
  while (true) do
   \_update\_buttons(\_update60 and 1 or 2)
   \_startframe()
   if (stat(7) == 60) then
    \_mark\_cpu(0)
    \_update60()
   elseif (stat(7) == 30 and \_update60) then
    \_update60()
    \_update\_buttons(1)
    \_mark\_cpu(0)
    \_update60()
   elseif (stat(7) == 30 and \_update) then
    \_mark\_cpu(0)
    \_update()
   elseif (stat(7) == 15 and \_update) then
    \_update()
    \_update\_buttons(2)
    \_mark\_cpu(0)
    \_update()
   end
   \_mark\_cpu(1)
   if (\_draw ~= nil) then \_draw() end
   \_mark\_cpu(2)
   flip()
   \_update\_framerate()
   for i = 1, 5 do
    if (\_get\_menu\_item\_selected(i)) then
     \_pausemenu[i].callback()
    end
   end
  end
 end
end

if (\_mainloop ~= nil) then \_mainloop() end

```

## Warning

As undocumented functionality, the header and footer cannot be relied on for a game. Its functionality may change or be removed in future versions. Still, some may find a pragmatic use for it in tools or demos. Just be aware that you use it at your own risk.
Known Bugs

Little wrinkles in PICO-8's language implementation.

### Overflow and Distance Calculations

Pico-8's numbers are 16.16 fixed point, with a maximum integer value of 32767. This means it's quite easy to overflow numbers when squaring for distance calculations: 181^2==32761, almost overflowing, so even pixels two screens away will overflow a naive distance calculation. One workaround is to move the fixed point artificially, like this:

```
-- works with x,y up to +/-8191
-- and distance up to 11584 by
-- sacrificing some precision
function dist(x0,y0,x1,y1)
  -- scale inputs down by 6 bits
  local dx=(x0-x1)/64
  local dy=(y0-y1)/64

  -- get distance squared
  local dsq=dx\*dx+dy\*dy

  -- in case of overflow/wrap
  if(dsq<0) return 32767.99999

  -- scale output back up by 6 bits
  return sqrt(dsq)\*64
end

```
Earth Was a Bad Choice

Creator
 Genre
 Player Count

## Description

An alien has become separated from his space ship after stopping on Earth for some “R and R”. Unfortunately the Earthlings are treating him like a “monster”, so he must make it back to his ship and flee the planet by running and becoming airborne.

## Rules

* The player's alien is constantly running, which takes up energy. Steering the alien into earth vehicles (cars, planes, bombs) will cause the alien to become airborne and not use up energy. If the player runs out of energy during a level the game will end, although the player is allowed unlimited continues. Making it to the end of a level refills the alien's energy level to its maximum amount.
* Destroying as many earth vehicles/weapons as possible without touching the ground will add to the player’s combo score (along with how much time the player was in the air max), which is displayed if the player is able to hit at least 10 vehicles and/or projectiles in a row without touching the ground.

## Controls

* Use the X or Z or any arrow key to start a game.
* Use the left/right arrow keys to move the alien.
* Use the left/right arrow keys to read text at the end of a level.
* Use the X + Z keys to toggle the music.
* Use the Escape or Enter keys to pause the game.
Type

type( value )
Returns the basic type of a given value as a string.
value

The value whose type to test.

The `type()` function is similar to the corresponding Lua built-in function.

## Examples

```
print(type(1))        -- "number"
print(type("hello"))  -- "string"
print(type(false))    -- "boolean"
print(type({}))       -- "table"
print(type(nil))      -- "nil"
print(type(print))    -- "function"

function print\_is\_number(v)
  if type(v) == "number" then
    print("it's a number")
  else
    print("it's not a number")
  end
end

```

## See also

* Lua
* `tostr()`
Coresume

coresume( cor, [...] )
Starts a coroutine, or resumes a suspended coroutine.
cor

The coroutine, as created by `cocreate()`.

...

The arguments to pass to the coroutine's function or the coroutine's subsequent yields.

*return-values*

A boolean indicating whether or not the coroutine is alive.
If the coroutine finished or yielded, there is an *undocumented* second value - the value returned or yielded.
If the coroutine failed, there *may* be a second value with an exception string.
A coroutine is a special kind of function that can yield control back to the caller without completely exiting. The caller can then resume the coroutine as many times as needed until the function exits.

The `coresume()` function starts or resumes a coroutine created by `cocreate()`. Control returns to the coroutine function until the function yields or exits.

`coresume()` returns `true` if the given coroutine was active (suspended) when `coresume()` was called, or `false` if it was given a dead coroutine (and no code was executed by resuming). If a resumed coroutine function exits (rather than yields), the coroutine goes from suspended to dead, and a subsequent call to `coresume()` with the same coroutine will return `false`. It is more typical to use the `costatus()` function to test the status of a coroutine, but the return value from `coresume()` may be used instead.

In the event that `coresume()` returns `false`, it *may* also return a second value containing a string describing an exception that caused the routine to die unexpectedly, e.g. "attempt to index a nil value". A full stack trace can also be obtained by passing the dead coroutine to `trace()`. In fact, the code below is a very simple way to `stop()` with full stack trace when a coroutine dies unexpectedly:

```
local active, exception = coresume(co)
if exception then
  stop(trace(co, exception))
end

```

As of PICO-8 0.2.4b, when `coresume()` returns true, it also returns a second value from the coroutine function - the value passed to `yield()` if the coroutine yielded, or the value passed to `return` otherwise. However, this doesn't appear to be documented right now, so there may be some danger in relying on this. Note also that if multiple values are yielded or returned, only the first of those values will be returned from `coresume()`

`coresume()` may pass extra arguments to the coroutine. These arguments will be mapped to the coroutine's function arguments on the first call, and will be used as return values for `yield()` on subsequent calls.

## Examples

```
function foo(a, b, c)
  print(a)
  print(b)
  print(c)
  a, \_, c = yield()
  print(a)
  print(b)
  print(c)
end

local thread = cocreate(foo)
coresume(thread, 1, 2, 3) --> prints: 1 2 3
coresume(thread, 4, 5, 6) --> prints: 4 5 6

```

See `cocreate()` for a general example.

## See also

* `cocreate()`
* `costatus()`
* `yield()`
Srand

srand( val )
Initializes the random number generator with an explicit seed value.
val

The seed value.

The random number generator used by `rnd()` is initialized with an unpredictable seed value when PICO-8 starts. You can reinitialize the generator with an explicit seed using `srand()`.

This is mostly useful for testing random behaviors in your game with a known sequence. You can call `srand()` before a call to `rnd()` and get a predictable result.

## Examples

```
print(rnd(20))   -- unpredictable, for example 3.837
print(rnd(20))   -- unpredictable, for example 19.089

srand(1)
print(rnd(20))   -- 7.081
print(rnd(20))   -- 1.989
print(rnd(20))   -- 16.593

srand(1)
print(rnd(20))   -- 7.081
print(rnd(20))   -- 1.989
print(rnd(20))   -- 16.593

```

## See also

* Math
* `rnd()`
CommandPrompt

The PICO-8 command prompt lets you interact with PICO-8 and the currently loaded cartridge using typed commands. By default, the command prompt is the first thing you see when starting PICO-8.

You use the command prompt to load and save cartridges, manage PICO-8 files, organize them into folders ("directories"), and perform other actions such as starting Splore.

```
> install_demos
> load demos/jelpi
> run

```

For a list of available commands, see CommandReference.

You can type Lua statements (such as `print()`) at the prompt to execute them. This is a good way to experiment with the PICO-8 built-in functions and try Lua.

**Note:** The PICO-8 prompt only accepts commands and statements. To see the value of an expression, you must use the `print()` statement.

## Getting back to the command prompt

When playing a cartridge, you can interrupt it and return to the command prompt by pressing the `Esc` key. You can enter Lua statements at the prompt to examine or change the program's global variables. In many cases, you can use the `resume` command to continue the program (but see `its documentation` for caveats).

If you started the cartridge from Splore, pressing Escape opens the Splore pause menu. To get to the command prompt from here, select Splore from this menu, then press Escape again.

At the command prompt, pressing `Esc` opens the cartridge editor interface. To return to the command prompt from here, press `Esc` again.

The command prompt is exclusive to the PICO-8 app, and is not available from the PICO-8 web player.

## Frame Advance

Typing a period, ".", and hitting enter will advance your program one frame by calling `\_update()` and then `\_draw()`. This can be useful to test behavior from frame to frame.
LexaloffleGames

Lexaloffle Games is a computer game company based on Kichijouji, Tokyo, Japan, founded by Joseph White (aka zep). Lexaloffle is the maker of the PICO-8 fantasy console, the Voxatron fantasy console, and PC games such as Jasper's Journeys and Zen Puzzle Garden.

Lexaloffle is located at Pico Pico Cafe in Kichijouji, just north of Inokashira Park (home of the Ghibli Museum). The cafe is open to the public on weekends and hosts a monthly show-and-tell event for designers called Picotachi.

* Website: http://www.lexaloffle.com/
* Contact: hey@lexaloffle.com
* Twitter: @lexaloffle
Corrupt Mode (corrupt pico-8 data)

This is a code snippet from Jelpi (by zep) that can be used in any game to oft hilarious effect.

```
for i=1,5 do
 poke(rnd(0x8000),rnd(0x100))
end

```

Here is an alternate corruptor, using a different method.

```
function _init()
 a=1
 b=1
 c=1
end
function _update()
 b=peek(a)
 a=a+c
 poke(a,b)

```

```
 if a < 0 then a = 1 end
 a=a+1
 srand(c)
 c=flr(rnd(30))
end

```
Rawget

rawget( tbl, member )
Read a table member, bypassing metamethods
tbl

The table whose member to read.

member

The member to read.

When creating things like class objects, one often overrides metamethods like `__index` and `__newindex` with custom code, but might then need to read directly from the table without going through those overrides. This can be done with `rawget()`.

## See also

* `setmetatable()`
* `getmetatable()`
* `rawset()`
* **`rawget()`**
* `rawlen()`
* `rawequal()`
* Metatables
* Tables
* Lua
Piconian

Creator
 Genre
 Player Count

## Description

Fly around, avoiding (or destroying) space debris while obliterating as many enemy bases as possible.

## Rules

* Use the radar display at the bottom right corner of the screen to locate enemy bases.
* Avoid or shoot space debris (asteroids, mines) along the way.

* The player's ship can wrap around the edge of a level (flying to the right edge will cause it to re-emerge at the left side of the screen, for example), providing shortcuts to bases.
* An enemy base can be destroyed in two ways: by either a shot straight up its middle or by shooting all six of its pods.
* Colliding with an asteroid, mine, base or missile fired from an enemy base will destroy the player's ship and the game will end when all lives have been exhausted.
* An extra ship is awarded with every thousand points.

## Controls

* At the title screen, use the left/right arrow keys to view high scores.
* At the title screen, press the x key to start a game.
* Use the arrow keys to start a new level.
* Use the x key to fire.
* Use the arrow keys to move (ship will thrust on its own).
* Use the z or enter key to pause the game and/or reset the cart.
Fillp

fillp( [pat] )
Sets the fill pattern.
pat

A bitfield representing the fill pattern to use.

The fill pattern is part of the draw state. It affects circ(), circfill(), rect(), rectfill(), pset(), and line().

The pattern is a bitfield, a single number that represents a 4x4 pixel pattern. These are the bit values for each pixel in the pattern, in both decimal and hex:

 2048
 128
 8

 0x0800
 0x0080
 0x0008

The easiest way to represent this pattern in source code is as a binary number literal:

```
fillp(0b0011001111001100)

-- A checkerboard pattern:
-- 0011
-- 0011
-- 1100
-- 1100

```

The default pattern is a solid fill (0b0000000000000000). You can reset the pattern by calling `fillp()` with no arguments.

The color parameter to the drawing functions (such as circfill()) can set two colors, to be used for the on bits (1's) and off bits (0's) of the pattern. The four lower bits of the color value are the "off" (default) color, and the higher bits are the "on" (pattern) color. For example, to draw the off bits as light blue (12, or `0xc`) and the on bits as dark blue (1), set the color to `0x1c` (28).

```
fillp(0b0011001111001100) -- or 0x33cc
circfill(60, 60, 10, 0x1c)

```

Alternatively, you can set the pattern to make the on bits transparent (showing what is drawn underneath). To do this, add `0b0.1`, or `0x0.8` if using hex, to the pattern value:

```
rectfill(0, 0, 127, 127, 3)
fillp(0b0011001111001100.1) -- or 0x33cc.8
circfill(60, 60, 10, 0xc)

```

## Technical notes

The current fill pattern is memory-mapped and may be read or written directly:

* 0x5f31 / 24369: pattern lo byte
* 0x5f32 / 24370: pattern hi byte
* 0x5f33 / 24371: transparency bit, 1=transparent, 0=opaque

## Predefined pattern values

The typeable special characters in the P8SCII range 128-135 are predefined as values that can be used as `fillp()` patterns. To use these, type Shift with a letter from A to Z in the code editor as the argument. Do *not* surround the value in quotes: these are predefined symbols similar to variable names.

```
-- type shift + m for a face-like pattern
fillp(😐)

```

## Examples

```
cls()
fillp()
rectfill(0,0,127,127,1)
fillp(0b0011001111001100)
circfill(40, 40, 10, 8)
fillp()
circ(40, 40, 10, 7)

circfill(80, 80, 10, 6)
fillp(0b0011001111001100.1)
circfill(80, 80, 10, 8)
fillp()
circ(80, 80, 10, 7)

fillp(0b0011011011000110)
rectfill(20, 100, 108, 120, 0xe8)

-- get the current fill pattern from its memory-mapped addresses
pattern = peek2(0x5f31)+peek(0x5f33)/2

```

## See also

* DrawState
* `circ()`
* `circfill()`
* `rect()`
* `rectfill()`
* `pset()`
* `line()`
Cursor

cursor( [x,] [y,] [col] )
Sets the left-margin cursor position for `print()`.
x

The x coordinate of the upper left corner of the line. The default is 0.

y

The y coordinate of the upper left corner of the line. The default is 0.

col

(Optional) The palette index to set the pen color to.

*return-value*

An x,y,c tuple representing the previous cursor position and color.
The draw state maintains a cursor location (and a pen color) for printing text with the `print()` function. PICO-8 uses this to maintain a scrolling display, especially for the command prompt.

The coordinates passed in set the starting location of the next `print()` call *as well as* setting the left margin for all subsequent calls.

See `print()` for a more detailed explanation of the text cursor's behavior.

## Other functions that affect the cursor

Calling `cls()` effectively also calls `cursor(0, 0)`.

Calling `print(str)`, *without* explicit coordinate arguments, will adjust the cursor's Y value when required for newlines and scrolling.

Calling `print(str, x, y)`, *with* explicit coordinate arguments, effectively also calls `cursor(x, y)` *after* the entire string is printed.

## Technical notes

The current cursor position is memory-mapped and may be read or written directly:

* 0x5f26: cursor x position
* 0x5f27: cursor y position
* 0x5f25: pen color (see `color()`)

## Examples

```
-- set the cursor position to (20, 24).
cursor(20, 24)

print("line one")
print("line two")
print("line three")

-- get the cursor position from its memory-mapped addresses
cursor\_x = peek(0x5f26)
cursor\_y = peek(0x5f27)

```

## See also

* Draw state
* `color()`
* `cls()`
* `print()`
Puzzle Cave - Raiders Of The Lost Potato

Creator
 Genre
 Player Count

## Description

Potatomonsters stole all potatoes from Pinkbunnyland. Help Pinkbunny to collect all stolen potatoes and save Pinkbunnyland!

## Rules

* Once Pinkbunny has collected all potatoes in a level, a key will appear; collecting the key will cause a door to disappear, leading to the next level. Collect the key to move to the next level.
* Diamonds start appearing in levels that block Pinkbunny's access to potatoes and certain areas of a level. Pinkbunny can push the single diamonds out of the way, however, to gain access to potatoes. Two diamonds together cannot be moved if there are no other paths around them.
* After several levels, green creatures begin appearing that will shoot off lasers if Pinkbunny enters their line of sight. These bring instantaneous death. However, they can be blocked by diamonds.
* If Pinkbunny gets stuck in a level with no way to solve it, the level can be reset.
* All levels, including the game, can be beaten..

## Controls

* Use the x or z key to start a new game.
* Use the p or Enter keys to pause a game.
* Use the arrow keys to move, push diamonds, collect potatoes and keys and exit levels.
* Use the x or z key to restart a level.
* Use the p or enter key to pause the game.
PlayingGames

The easiest way to start playing games is to visit the PICO-8 forum in a web browser. All cartridges published to the forum can be played in a web browser without the PICO-8 app.

From the PICO-8 app or a network-connected device (such as PocketC.H.I.P.), you can use the built-in Splore utility to browse and play all carts published to the forum. Type `splore` at the PICO-8 prompt and hit enter.

PICO-8 includes a small set of demonstration carts built in. To access these carts, you must first run the `install_demos` command at the PICO-8 prompt. This creates a `demos/` folder in the PICO-8 file system with carts that can be loaded, run, and edited.

You can download carts from the forum by clicking on the "Cartridge" link and saving the file. The file is a `.p8.png` file and appears as an image of a cartridge in a web browser. Use the folder command to open the PICO-8 file system location in your operating system's file browser, then move the file to that location to make it accessible to PICO-8.

To save a cartridge discovered within Splore, load and run the cart, hit Escape to open the pause menu, select Splore, then hit Escape again to return to the PICO-8 prompt. The loaded cart is still in memory. Use the save command to save it as a local file.
Btnp

btnp( [i,] [p] )
Tests if a button has just been pressed, with keyboard-style repeating.
i

The button number.

p

The player number.

*return-value*

If a button is specified, then `true` or false, otherwise a bitfield for multiple players.
The `btnp()` function is similar to `btn()` except that it only reports that a button is on if it was not pressed during the previous frame. In other words, it returns `true` only if a given button was pressed just now, and does not report `true` again for the same button in the next frame even if it is held down.

This is useful for detecting button presses that are meant to select menu options or initiate actions. If you were to use `btn()` to initiate an action, the player is likely to initiate the action multiple times that they didn't intend, because the button will register as on for multiple frames.

`btnp()` implements a keyboard-like repeat mechanism: if the player holds the button for 15 frames, it registers as on again for one frame, then again every four frames after that. The frame counter resets when the player releases the button. These frame counts are doubled for 60fps. Custom delays (in frames 30fps) can be set by poking the following memory addresses:

```
poke(0x5f5c, delay) -- set the initial delay before repeating. 255 means never repeat.
poke(0x5f5d, delay) -- set the repeating delay.

```

In both cases, 0 can be used for the default behaviour (delays 15 and 4)
Like `btn()`, `btnp()` can take a button number and a player number and return `true` or `false`, or can be called without arguments to return a bitfield of button states.

See `btn()` for a description of the arguments and return values.

## Predefined button values

The P8SCII character set includes 26 special glyphs that can be typed by holding `Shift` and pressing a letter from `A` to `Z` in the code editor or the prompt. PICO-8 pre-defines 26 single-character global variables with names from this set of glyphs and gives them useful values. In the case of `btnp()` the ones associated with U, D, L, R, O, and X (⬆️, ⬇️, ⬅️, ➡️, 🅾️, and ❎) are useful, because they represent the corresponding button indices 0 through 5.

These can be used as an argument to `btnp()` (or btn()) to represent the corresponding button. Do *not* surround the value in quotes, because these are not strings, they are predefined global variables with single glyphs for names.

```
-- test for the "left" button, typed as shift + l
if btnp(⬅️) and x > 0 then
 x -= 1
end

```

## Examples

```
sel = 0
items = {"a", "b", "c", "d",
         "e", "f", "g", "h"}

function \_update()
  if (btnp(0) and sel > 0) sel -= 1
  if (btnp(1) and sel < #items - 1) sel += 1
end

function \_draw()
  cls()

  for i=1,#items do
    print(items[i], 10 \* i, 10, 7)
  end

  rect(8 + (sel \* 10), 8,
       14 + (sel \* 10), 16,
end

```

Try replacing `btnp()` with `btn()` to see what happens.

## See also

* Controllers
* Configuration
* SDL
* `btn()`
Pal

pal( c0, c1, [p] )
Changes the draw state so all instances of a given color are replaced with a new color.
c0

The number of the original color to replace.

c1

The number of the new color to use instead.

p

0 to modify the palette used by draw operations, 1 to modify the palette for the screen already drawn, or 2 to modify the secondary screen palette. The default is 0.

All functions that draw to the screen, including `spr()` and `map()`, use the *draw palette* to decide which colors to write to the graphics buffer. The `pal()` function can modify this palette at any time to achieve certain effects, such as to temporarily replace a color used by a sprite with another color.

When the graphics buffer is copied to the screen (after `_draw()` executes or when the program calls `flip()`), it uses a *screen palette*. This gives the program another opportunity to replace colors for the entire graphics buffer for full screen effects such as fades, or perhaps very large explosions. You tell the `pal()` function to modify the screen palette by passing `1` as the optional third argument. Additionally, the secondary palette used by the fill pattern functionality and undocumented high-color modes can be modified by passing 2.

See Graphics for a table of color numbers.

To replace multiple colors at once, the `pal()` function may receive a single table argument optionally followed by the palette ID `p`. The key value of the entries in the table are the `c0` values, and each entry's value are the `c1` values. Any key outside the 0-15 range will be accepted, just that a modulo 16 will be applied to the key's number.

To reset the entire palette, call `pal()` without arguments. This also resets the transparency settings, as if you had also called `palt()` with no arguments, so it is not necessary to call both.

`pal()` is useful for a wide variety of effects. Just a few examples:

* Use different colors with the same sprite to create multiple distinct instances, such as two figures wearing different clothes.
* Embed multiple color patterns in a single sprite then change the palette to cause different patterns to appear for the same sprite, such as multiple kinds of wall tiles using the same sprite.
* Animate color changes in one or more sprites to indicate status, such as a successful hit to an enemy, or a bomb about to explode.
* Change the palette of an entire environment to indicate the time of day.

## Examples

```
blink\_frame = false
t = 0

function \_update()
  -- every 8th frame is a "blink frame"
  t = (t + 1) % 8
  blink\_frame = (t == 0)
end

function \_draw()
  cls()

  -- reset the palette
  pal()

  if blink\_frame then
    -- replace dark grey with red
    pal(5, 8)
  end

  -- draw the blinking light sprite
  spr(16, 56, 72)
end

```

## See also

* Draw state
* Graphics
* Palette
* `color()`
* `palt()`
GPIO

The PICO-8 builds for Raspberry Pi and PocketChip include support for reading and writing to the GPIO pins on those devices (added in v0.1.9). You can also use the GPIO interface from read/write to JavaScript in web exports of PICO-8 carts (added in v0.1.7).

## API

To access the GPIO pins, `peek()` or `poke()` to bytes

```
0x5f80..0x5fff / 24448..24575

```

in memory. PICO-8 will automatically set a pin to read mode when you peek the memory address or write mode when you poke to the address.

In the web exports, you may use arbitrary bytes in these memory locations to be read from and written to by JavaScript code. To access it, you have to declare a new array, as following:

```
var pico8\_gpio = new Array(128);

```

You can then write to the bytes like so :

```
pico8\_gpio[0] = 10;

```

This allows JavaScript to communicate with PICO-8.

In the hardware implementations, the GPIO pins act digitally, with 0 representing 0 and 255 representing 1. Also, hardware implementations may not support all 128 pins. Raspberry Pi, for instance, reportedly only supports the first 8 pins.

## Raspberry Pi Setup

### Raspberry Pi B+

On a Raspberry Pi B+ model, no additional setup was necessary (using v0.1.10). Run the **pico8** binary via

```
> sudo ./pico8

```

to enable access to the GPIO pins. If you do not use sudo to run PICO-8, the program will crash with a WiringPi error when your cart tries to access the GPIO memory space.

### Raspberry Pi 2 and newer models

On newer Raspberry Pi models, the version of WiringPi included in the statically-linked **pico8** binary.\* Instead, you will have to build and install SDL 2.0.5 from source as well as a more recent version of WiringPi. Then, use the **pico8\_dyn** binary to run PICO-8.

***\* Requesting assistance:** Is it included? Is it not included? What is the issue here? Would appreciate someone with a Raspi 2 or newer clarifying what this means in less broken English. Feel free to delete this when done.*

### Older models

On older models of the Raspberry Pi than the B+ model, GPIO may not work at all with PICO-8.

## PocketChip Setup

**TODO:** document experience using PocketChip with PICO-8. Example: I think we had to install a newer (unofficial?) version of PICO-8 using the Debian package manager.
The Stroll

Creator
 Genre
 Player Count

## Description

Go for a walk! However, is this just a normal "stroll", or does the drab background/colors and blood-spattered bodies littering the landscape suggest that something much more sinister is afoot?

## Rules

* Just move! The player will mostly move to the right during the entire game.
* Barriers impede the player's progress; buildings must be entered in order to defeat them. The player can either take an additional exit to bypass a barrier or they will run across one or more consoles complete with one or more red lights. Interacting with the consoles will turn the lights to green; once this has been accomplished, the barriers will be removed, the player can exit the building and continue on their way.
* Once the player encounters the monster, they must get close enough for it to realize the player is near so it can attack and kill the player, thus completing the game. There is no way to avoid or defeat the monster.

## Controls

* Use the right arrow key to start a game.
* Use the left/right arrow keys to move the player.
* Use the up and down arrow keys to enter and exit buildings (respectively) while standing in a doorway.
* Use the up arrow key to interact with a console while standing in front of it.
* Use the Escape or Enter keys to pause the game.