recursal/Fanatic-Fandom huggingface dataset:
Draw zoomed sprite (zspr)

I find the syntax of **sspr** involves too much work, so I wrote a wrapper function that requires less arguments and less thinking. So...

**zspr**

Arguments:

--n: standard sprite number

--w: number of sprite blocks wide to grab

--h: number of sprite blocks high to grab

--dx: destination x coordinate

--dy: destination y coordinate

--dz: destination scale/zoom factor

```
 function zspr(n,w,h,dx,dy,dz)

 sx = 8 \* (n % 16)

 sy = 8 \* flr(n / 16)

 sw = 8 \* w

 sh = 8 \* h

 dw = sw \* dz

 dh = sh \* dz

 sspr(sx,sy,sw,sh, dx,dy,dw,dh)

end

```
Сейзо

**Звезд** - ★★★

**Класс** - Танк

**Позиция** - Передний ряд

**Тип атаки** - Физическая

## Описание

Стрелок переднего ряда. Основная атака - физическая. Может спокойно передвигаться среди врагов.

## Навыки

**Сумасшедшая резня**

Наносит физический урон врагам перед ним.

**Супер-удар**

Наносит физический урон врагам на территории.

**Барьер из лезвий**

Восстанавливает энергию, увеличивает магическую и физическую защиту.

**Мастер меча**

Увеличивает физический урон Сайзо.
Затмившая луну

## Описание

**Звезд** - ★

**Класс** - Маг

**Позиция** - Средний ряд

**Тип атаки** - Магическая

Маг средней линии. Основная атака - магическая. Имеет мощный потенциал на поле боя.

## Навыки

**Вихрь**

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

**Сердцеедка**

   Наносит магический урон противнику, вызывая у цели кровотечение на 8 секунд.

**Охотница**

    Выбрасывает несколько лезвий (до 5 целей) нанося магический урон.

**Взлет**

    После того как вражеский юнит умирает, герой восстановит себе часть здоровья и увеличиться скорость атаки на 5 сек.
Trace

trace( [coroutine,] [message,] [skip] )
Returns a description of the current call stack as a string.
coroutine

Optionally get the stack trace for a coroutine. Defaults to the current one or the main thread.

message

Adds the given string to the top of the trace report. Defaults to blank.

skip

Number of levels of the stack to skip. Defaults to 1, to skip the trace() call's own level.

Undocumented feature
This article describes a feature that is not mentioned in the official Pico-8 documentation. The feature was known to work at the time the article was written, but
it may be removed or changed in a future version.

The `trace()` function returns a description of the current call stack as a string. This string is long, and is only useful when printed to a terminal window with `printh()`.

Note that, despite the expected Lua practice of only being able to leave out trailing arguments, the first argument, for the coroutine, can be left out while still supplying the message and skip arguments.

Note that the message argument is useful for inserting the exception string returned from a failed coroutine. See `coresume()` for details on how to do this.

As of PICO-8 v0.1.6, the string includes useless information referring to internal details. For example, if the cart uses the game loop, this stack trace includes the hidden `_mainloop` function.

## Examples

Here's a simple program that counts up to 30, prints the stack trace to the host console, then calls `stop()`.

```
v = 0

function next\_tick()
  if v > 30 then
    printh(trace("final tick reached!"))
    stop()
  end
  return v + 1
end

function \_update()
  v = next\_tick()
end

function \_draw()
  cls()
  print(v, 0, 0, 7)
end

```

As of PICO-8 v0.1.12c, the host console shows the trace as follows:

```
final tick reached!
stack traceback:
	[string "-- pico-8 header..."]:7: in function 'next'
	[string "-- pico-8 header..."]:14: in function '_update'
	[string "-- pico-8 header..."]:31: in function '_mainloop'
	[string "-- pico-8 header..."]:38: in main chunk

```

## See also

* Lua
* `assert()`
* `coresume()`
* `stop()`
Laser emitter

The laser emitter i one of the more complex tokenens in ChessAdventures, when activated it's emmiting a laser beam diagonally. Laser beams react diffrently when they hit different materials, marble stops the laser, steel reflects it, wood catches fire, it passes straight through glass, obsidian splitts it and ice bends it a little (straight laser beams becomes diagonal ones and vice versa).
Flip

flip( )
Copies the graphics buffer to the screen, then synchronizes to the next frame at 30 frames per second.
Carts that use the built-in game loop functions \_update() and \_draw() do not need to call `flip()`. It can, however, be used to synchronize with the 30-frames-per-second draw timer in carts that implement their own custom game loop.

**Note:** If no \_draw() function is implemented, PICO-8 will copy the graphics buffer to the screen 30 times per second automatically even if `flip()` is not called as often. `flip()` waits until the next frame has been copied, synchronizing program execution to the frame timer.

## Examples

```
for x=4,124 do
  cls()
  circfill(x, x, 4, 8)
  flip()
end

```

This example animates a circle moving diagonally across the screen, one pixel per frame for 120 frames (four seconds).

If the call to `flip()` is removed, the code above clears the graphics buffer and draws the circle 120 times, but the buffer is only copied to the screen when the program exits.

## See also

* `_update()`
* `_draw()`
* `holdframe()`
ChessAdventures Wikia

## ChessAdventures

ChessAdventures is a complex level-based puzzle game.

The latest stable verision can be found here:

http://chessadventures.ml/

A ChessAdvenures level consists of three basic elements Tokens, Tiles and Entities.

## Latest activity

Photos and videos are a great way to add visuals to your wiki. Find videos about your topic by exploring Wikia's Video Library.

File:Placeholder
Чарльз

**Звезд** - ★★★

**Класс** - Танк

**Позиция** - Передняя линия

**Тип атаки** - Физическая

## Описание

Танк передней линии. Основная атака - физическая. Способен телепортироваться к союзникам и защищать их.

## Навыки

**Предельная защита**

Телепортируется к союзнику и защищает его. В области телепортиции враги получают оглушение. (Чарльз и союзник получат щиты почти сразу, даже если телепортация будет прервана.*)*

**Предельный удар**

Наносит магический урон врагу и позволяет союзником использовать эти повреждения, чтобы исцелить себя.

**Предельный рывок**

Врывается в ряды противника, причиняя магический урон, и накладывает на противника эффект провокации.

**Максимальный удар**

Увеличивает шанс критического удара.

## Вывод

Чарльз - отличный танк для ранней и поздней игры. На ранних стадиях невероятно толстый, а благодаря сайленсу и вампиризму от 2 и 3 умения, почти всегда выигрывает у вражеских танков "первую кровь". После получения пассивной способности получает приличную добавку к урону. Ульта у героя не слишком хорошо реализована - скорость телепорта и прочность щита не сбалансированы.
Catapult

The idea of the catapult was thought of very early in the ChessAdventures development (before the release of 1.0.0), but it was decided to not implement it because of its similarities to the cannon. The idea was brought up again right before the release of 1.2.0 and this time it was actually implemented. The catapult is a unique token in many ways, its the olny token that renders outside its square (exept for the laser but that doesn't count), its one of the to ways to directly move a token over a wall (the other one is knights/hookshoters).
Costatus

costatus( cor )
Tests a coroutine and returns a string representing its status.
cor

The coroutine to test.

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 `costatus()` function takes a coroutine object and returns its status as a string value, either `'running' 'suspended' 'normal'` or `'dead'`. You can use this to test whether the most recent call to `coresume()` yielded or terminated.

 suspended
 normal
 dead

## Technical notes

When a coroutine dies unexpectedly, this status merely goes to `'dead'`, but additional information is also available about the reason and the location. See `coresume()` and `trace()` for details.

## See also

* `cocreate()`
* `coresume()`
* `trace()`
* `yield()`
Gel

Gels are the only things in the game that can alter materials (besides the editor). If a token steps on a gel, the token changes material to the gels material, and the gels use count goes down one step. If a gel is set on fire the whole gel is consumed, no matter the use count and the material of the tile beneth is changed to the material of the gel.

## Trivia

There was once an idea to have black and white gels to change white/black status, but that idea was disregarded because it seemed too over powered.
Wall

The wall is like the standard tile, a very simple tile it can't do much. The only difference between the standard tile and the wall is that the wall is high, which means tokens cant walk passed it cannons and archers cant shoot over it. Only a few things can get passed a high tile such as the wall, knights and hookshooters can jump over walls and catapults can launch tokens over walls.
King

The king is a token that also can be found in regular chess. The king can pick up and use entities like the bow and arrow. It also has the ability to ride on tokens. The king, cannon and monopole magnet are the only tokens that default to black.

The king was added in ChessAdventures 1.0.0 prerelease 1. Once upon a time the king was supposed to ride on knights but it was scrapped because the programer didn't think it was necessary.
History

The idea of ChessAdventures was born 14 december 2012.

## ChessAdventures 1.0.0 prerelease 1

*The changelog of this update is reconstructed.*

+ Added a window.

+ Added a graphical engine.

+ Added selection mechanic.

+ Added Tile.

+ Added King.

+ Added keyboard shortcuts (alt -> place King, space -> place Tile).

## ChessAdventures 1.0.0 prerelease 2

*The changelog of this update is reconstructed.*

+ Added walking mechanic.

## ChessAdventures 1.0.0 prerelease 3

*The changelog of this update is reconstructed.*

+ Added a menu bar.

+ Added a white background.

+ Added Pawn.

+ Added keyboard shortcut (windows key -> place Pawn).

## ChessAdventures 1.2.3

+ Added level 22 and 23.

+ Added a new achievement.

+ Added the option to undo when winning a level.

+ Added the option to go right to the next level when winning a level.

\* Made minor fixes to the save system (without breaking any levels).

\* Made it possible to teleport to dead-end teleporters.

\* It now shows which level you won.

## ChessAdventures 1.2.4

+ Added Dummy.

+ Added Level 24 and 25.

+ Added a record storage function.

\* Changed the cutting order.

\* Fixed a save system bug to make all options load properly.

\* Improved the cutting mechanic.

\* Fixed a possible cheat and added a hint to level 15.
Сунь Укун

**Звезд** - ★★★

**Класс** - Танк

**Позиция** - Передний ряд

**Тип атаки** - Физическая

## Описание

Танк переднего ряда. основная атака - физическая. Его ультимейт может прерывать навыки противника.

## Навыки

**Удар урагана**

Сунь Укун, как ураган, проносится среди врагов, подбрасывая их и нанося физический урон.

**Ужасающий удар**

Атакует впереди стоящих врагов, нанося физический урон и ослабляя их физическую защиту.

**Фантомный удар**

Освобождает призрака для атаки врага,наносит физический урон.

**Щит Кинг-Конга**

Повышает физическую и магическую защиту Сунь Укуна.
Pico-Kit

An opinionated collection of PICO-8 helpers that add a couple of useful bits of functionality. It comes with four libraries:

* oop - an implementation of classes and objects that uses metatables
* tools - various tools for manipulating tables
* debug - improved printing that allows you to print an entire table, among other things
* physics - a tiny physics engine

To get started, just download the 'starter.p8' file off of the github page and open it up with PICO-8.
Monopole Magnet

The monopole magnet is a special kind of magnet but instead of affecting things after each turn it has to take an action of it own. Like the normal magnet the monopole magnet pulls things towards it then red and pushes things away while white.

## Trivia

Theoreticly monopole magnets could exist in real life, but no one have ever managed to make one.

https://en.wikipedia.org/wiki/Magnetic\_monopole

The monopole magnets in ChessAdventures was originally inspired by the hypothetical ones.
Level Editor

The level editor is a "game mode" in which levels can be created.

## Shortcuts

Ctrl + A - Select all

Ctrl + C - Copy selected region

Ctrl + V - Paste selected region

Ctrl + E - Extend the board

Ctrl + S - Save the level

Ctrl + O - Open a level

Ctrl + P - Set level pasword

Ctrl + H - Set Level hint

Del - Delete selected entities

Shift + Del - Delete selected tokens

Ctrl + Del - Delete selected tiles

Shift + M - Change the material of the selected tokens

Ctrl + M - Change the material of the selected tiles

Shift + B - Toggle black/white on selected tokens

Shift + D - Change the direction of the selected tokens

Ctrl + D - Change the direction of the selected tiles

F1 - Moves the game a "tick" forward (fires burn, stuff falls down, etc)

Home - Resets zooming and paning (works in play mode too)
P8Jam

P8Jam is a game jam hosted by Lexaloffle Games focused on the Pico-8 platform. There have been two rounds of the game jam. Each round lasted nine days and was based on a theme. A "winner" was chosen by community voting using a special feature of the forum built for the jams.

* p8jam #1, November 21-29, 2015, theme: "Rain"
	+ Announcement: http://www.lexaloffle.com/bbs/?tid=2769
	+ Theme reveal: http://www.lexaloffle.com/bbs/?tid=2794
	+ Entries: http://www.lexaloffle.com/bbs/?cat=7&tag=p8jam1
	+ Results: http://www.lexaloffle.com/bbs/?tid=2870

* p8jam #2, May 21-29, 2016, theme: "Chain Reaction"
	+ Announcement: http://www.lexaloffle.com/bbs/?tid=3330
	+ Theme reveal: http://www.lexaloffle.com/bbs/?tid=3399
	+ Entries: http://www.lexaloffle.com/bbs/?cat=7&tag=p8jam2
	+ Results: http://www.lexaloffle.com/bbs/?tid=3558
Another World: SURVIVAL

Creator
 Genre
 Player Count

## Description

Imagine the game Another World, but with endless waves of enemies to fight!

## Rules

* On the first Wave, the player, controlling Lester Knight Chaykin, must avoid tentacles from a submerged creature nearby and kill leech-like creatures by kicking them. Killing a certain number of creatures will end the Wave and take Chaykin to the next one.
* Having a tentacle grab Chaykin or a leech creature make contact with him will kill Chaykin and the Wave will restart.
* Wave 2 is identical to Wave 1, but with the addition of creatures crawling along a cavern ceiling, which they can drop down on Chaykin and kill him if allowed. Again, killing a certain number of creatures will end the Wave and take Chaykin to the next one.
* Starting with Wave 3, Chaykin becomes armed with a gun and he encounters a bunch of alien soldiers. He can shoot the soldiers, along with defending himself via creating forcefields with the gun. Creating a super shot with the gun will destroy a soldier’s force field. Killing a certain number of soldiers will start the next Wave.
* If Chaykin gets shot then the Wave starts over.
* Starting from Wave 4 and onwards, Chaykin will advance to the next Wave after killing leech creatures and soldiers, but coming into contact with either (or a soldier’s gun blast) will cause the Wave to restart.

## Controls

* At the title screen, press the z key to play the game.
* Use the arrow keys to move (left/right to move and down to crouch).
* To kick, press the z key.
* To fire the pistol (Wave 3 and onwards), press the x key.
* To create a force field, press and hold the x key briefly, then release it.
* To create a super shot, hold the x key for several seconds, then release it.
* Use the enter or p keys to pause the game and/or reset the cart.
P8URLFormat

The PICO-8 education version can save cartridges consisting of code and sprites (but not map nor sound) to a URL.

The format of the URL is https://www.pico-8-edu.com/?c=<code>&g=<sprites>

The format uses a variation of base64, where character '\_' stands for 62 and '-' for 63. (Note: this is the other way around from the usual url-safe base64 encoding!)

## Code

First, the code is optionally compressed (if doing so saves space) via the format described in this page.

Next, the code is encoded in the aforementioned base64 variation, with padding.

## Sprites

The sprite sheet is taken as a 128x128 sequence of colors (from left to right, then top to bottom).

Next, all trailing zeroes (the color 0) are removed from it, except that if the sprite sheet is entirely filled with zeroes - a single zero remains.

Next, the colors are compressed into a sequence of 6-bit values:

* 0..15 : colors 0 through 15
* 16..31 : colors 0 through 15 repeated twice
* 32..47 : colors 0 through 15 repeated three times.
* 48..63 : colors 0 through 15 repeated (N+4) times, where N is the next 6-bit value.

Finally, the 6-bit values are each encoded via the aforementioned base64 variation, without any padding.
Люк

**Звезд** - ★★★

**Класс** - Пушка

**Позиция** - Средний ряд

**Тип атаки** - Физическая

## Описание

Стрелок средней линии. Физическая атака - основная. Может отпрыскивать врагов, нанося большой урон по области.

## Навыки

**Торпедный удар**

Выпускает 7 торпед в цель, нанося физический урон по территории.

**Тяжелая артиллерия**

Выстреливает в цель ракетой и наносит физический урон по территории и наносит физический урон.

**Пулемет Гатлинга**

Проводит мощный обстрел по территории, наносит физический урон.

**Первоклассное оружие**

Увеличивает физическую атаку Люка.
Tonum

tonum( value, [format\_flags] )
Attempts to return the given value as a number. Result is empty on failure.
value

The value to be converted: strings, booleans, and numbers are accepted.

format\_flags

A bitfield which allows different operations to occur in the conversion.

*return-value*

The provided value converted to a native number format, if possible; otherwise an empty result.
Returns a number if value can be converted to a number, or value already is a number. If not, the result will be *empty*, which for most purposes will work as if `nil` had been returned.

If value is a *string*, `tonum()` will try to parse it as one of these supported number formats:

* Decimal, e.g.: "255", "3.14159"

* Hexadecimal, e.g.: "0xff", "0x3.243f"

* Binary, e.g.: "0b11111111", "0b11.0010010000111111"

* Scientific/exponential, e.g.: "2.55e2", "3.14159e0"

Note that leading or trailing 0s are ignored, as one would expect, which may be useful when extracting fixed-width fields from a string.

If `value` is a *boolean*, it will return `0` for `false` and `1` for `true`, thus providing a simple way to convert booleans to numbers.

If `value` is *already* a number, it will be returned as-is.

The format\_flags parameter is composed of individual bits that control the conversion process:

```
 0x1: Read using hexadecimal notation, without requiring the "0x" prefix.
      Note: Non-hexadecimal characters, including '.' and '-', are taken to be '0'.

 0x2: Shift the value right 16 bits to create a 16.16 fixed-point number.
      This works with all formats, even booleans: true becomes 0x.0001.

 0x4: When value cannot be converted to a number, return 0 instead of nothing.

```

## Technical Notes

* If the string represents a number outside of the range of PICO-8 numbers, it wraps the number to that range before returning. Effectively, the result is bitwise-anded with 0xffff.ffff to fit in the PICO-8 16.16 fixed-point number format.

* When presented with a non-number, e.g. `tonum("xyz")`, the result will technically be *empty* to indicate that the string can't be parsed as a number. In Lua, the concept of *empty* is technically distinct from `nil`, but when *empty* is assigned to a variable, the variable becomes `nil`, and if *empty* is directly tested (e.g. `if tonum("xyz") then ... end`) it will be considered `false`.

## Examples

```
x = tonum('12345')          -- 12345
x = tonum('-12345.67')      -- -12345.67
x = tonum('-1.23456789e4')  -- -12345.6789

x = tonum('0x0f')           -- 15
x = tonum('0x0f.abc')       -- 15.6709
x = tonum('0b1001')         -- 9

x = tonum('32767')          -- 32767
x = tonum('99999')          -- -31073 (wrapped)
x = tonum('xyz')            -- nil

-- Examples with format\_flags bitfield

x = tonum("ff",       0x1)  -- 255
x = tonum("1146880",  0x2)  -- 17.5
x = tonum("1234abcd", 0x3)  -- 0x1234.abcd
x = tonum("xyz",      0x4)  -- 0 (instead of nil)

```

## See also

* `tostr()`
* Lua
Chr

chr( [ord [, ord2, [... ordn]]] )
Gets the character(s) corresponding to ordinal (numeric) value(s).
ord [, ord2, [... ordn]]

Zero or more ordinal values (typically one) to be converted into characters in a string.

*return-value*

A string consisting of as many characters as there were ordinal values. Default output is an empty string.
This function permits conversion of an arbitrary number of ordinal values to the character(s) they correspond to, in the form of a string.

The ordinal(s) can be obtained either from some reference or data source, or by calling `ord()` on one or more characters in an existing string.

This can be used to easily produce characters from their numeric representations:

```
> print(chr(104))
h
> print(chr(105))
i
> print(chr(33))
!
> print(chr(104)..chr(105)..chr(33)) -- concatenate 3 single characters
hi!
> print(chr(104, 105, 33)) -- or have chr() return a 3-character string
hi!

```

This allows a string to be easily and rapidly created from a list of ordinals that represent it. There are many ways this might be done, including reading strings from memory or save data, or sending strings through an arithmetic encryption/decryption process.

## Examples

This implements reading a length-prefixed "Pascal" string from memory:

```
-- read a string from memory containing a pascal-format string:
-- bytes 0,1: 16-bit length
-- bytes 2->: character ordinals
function peekstr(mem\_addr, max\_len)
  -- read the 16-bit length stored in the first 2 bytes
  local len = peek2(mem\_addr)
  -- limit the length in case it is corrupt
  len = min(len, max\_len)
  -- build a string from the stored ordinal bytes after the 2 'len' bytes
  return chr(peek(mem\_addr + 2, len))
end

```

(See `ord()` for the complementary `pokestr()` code example.)

This is a rather naïve implementation of the simple ROT13 cipher most programmers learn about during their education, which can be used both to encode and decode strings:

```
function rot13(s)
  local r = ""
  for c in all(s) do
    if c>='a' and c<='z' then
      -- subtract ord('a') == 97 to make the range 0..25,
      -- but also add 13 to rotate the alphabet by half,
      -- giving -97 + 13 = -84, then modulo and add 97 back
      c = chr((ord(c) - 84) % 26 + 97)
    end
    r = r..c
  end
  return r
end

```

```
> print(rot13("omg!"))
bzt!
> print(rot13("bzt!"))
omg!

```

## Technical notes

* Every `ord` argument is ultimately treated as an 8-bit unsigned integer, as if `chr()`'s implementation begins with `ord &= 0xff`. In other words, it is floored to a whole number, modulo 256.

* If an `ord` argument is a *string* that satisfies the conditions of `tonum(ord)`, it will be converted internally to a number. This means that both `chr(33)` and `chr("33")` will return "!".

* Other types, and strings that cannot be converted to numbers, will be treated as if ord were 0.

* `chr()` is similar to `string.char()` in native Lua, but is more flexible. For instance, while the string to number conversion was already part of `string.char`, the modulo 256 operation was not.

## See also

* `ord()`
* `peek()`
* `sub()`
Official Levels

All official levels has to have a complexity below 40%.

Complexity: 9.1%

Hint: If you don't know the rules of chess look it up, you play as black.

Current record: 4 turns.

## Level 2

Complexity: 10.6%

Hint: Try to kill all the white tokens before they kill you. They won't do anything unless they can take you in one move.

Current record: 13 turns.

## Level 3

Complexity: 15.2%

Hint: To pick up items press space. The bow and arrow can be useful to take out tokens that are protecting each other.

Current record: 21 turns.

## Level 5

Torch to burn tokens (The laws of nature haven’t been explained so this level is half weird)

## Level 8

Cannons (The hint on this level is kind of weird)

## Level 13

Hook shoot used to draw tiles (you also see that u can draw entities which is not explained earlier or not explained in the hint)

## Level 14

Keys, Hook shoot used to draw wooden tokens.

## Level 15

Pushing monopole – magnets.(First time ever interacting with a steel token and a magnetizer and first level with a white cannon)

## Level 19

Switching polarity on a monopole magnet (The hint has already been explained on LEVEL\_15)

## Level 24

Buffers (wire wall has never been used before and teleporters that require power haven’t been used earlier as well)

## Level 31

Cut glass tokens with glass cutter? (Pretty sure it’s this level)

## Level 34

You can’t shoot obsidian with arrow or burn obsidian (no hint)
Dset

dset( index, value )
Sets a value in persistent cartridge data.
index

The index of the value.

value

The new value to set.

A cartridge can store 64 numbers (256 bytes) of data to persistent storage. This data is available the next time the user runs the cart, and persists in the player even if the cartridge is replaced with a new version of the same cartridge.

The `dget()` function retrieves the value for the given index (0 to 63).

## See also

* `cartdata()`
* `dget()`
Tower Defense

Tower Defense (англ. Башенная защита), сокращенно TD — задача игрока в играх подобного жанра — расправиться с наступающими врагами, называемыми в некоторых играх «крипы» (от англ. creep, ползучая тварь), до того, как они пересекут карту, с помощью строительства башен, атакующих их, когда те проходят вблизи. Противники и башни обычно различаются по характеристикам и цене. Когда враги побеждены, игрок зарабатывает деньги или очки, которые используются для покупки или модернизации башен.

Подбор башен и их расположение — неотъемлемая стратегия игры. Обычно ползучие твари пробегают через подобие лабиринта, что дает игроку возможность стратегического размещения башен, но также существуют известные версии игры, названные линейными TD, где используются прямые пути вместо лабиринтов. В некоторых версиях игрок может сам выстраивать лабиринт из башен и блоков.

Информация взята с сайта Википедия
Circfill

circfill( x, y, [r,] [col] )
Draws a filled-in circle shape.
x

The x coordinate of the center of the circle.

y

The y coordinate of the center of the circle.

r

The radius of the circle, in pixels. If omitted, the radius will be 4.

col

The color of the circle and fill. If omitted, the color from the draw state is used.

## Examples

```
-- draw a large red filled circle in the middle
circfill(64, 64, 32, 8)

```

```
-- draw ten small white filled circles in random places
color(7)
for n=1,10 do
  circfill(rnd(128), rnd(128), 6)
end

```

## See also

* Graphics
* Draw state
* `circ()`
* `line()`
* `rect()`
* `rectfill()`
Extcmd

extcmd( cmd )
Executes an administrative command from within a program.
cmd

The command name, as a string.

The command can be one of the following:

* `'label'`: Sets the cart label to the current screen.
* `'screen'`: Saves a screenshot.
* `'rec'`: Sets the video recording start point.
* `'video'`: Saves an animated GIF to the desktop.
* `'audio_rec'`: Starts audio recording.
* `'audio_end'`: Ends audio recording and saves to the desktop.
* `'pause'`: Activates the pause menu, as if the player pressed the pause button.
* `'reset'`: Resets the currently running cart, as if the player pressed the reset key sequence (Control-R or Command-R).
* `'breadcrumb'`: After a cart uses load() with the breadcrumb parameter to load another cart, loads the original cart, as if the player selected the breadcrumb menu item.
* `'shutdown'`: Exits the program if used in an exported binary.
* `'set_filename'`: Set the filename of the next screenshot or gif.
* `'set_title'`: set window title (useful for exported binaries)
* `'folder'`: opens the folder where carts are. Nice for opening to a created file or something similar.

These commands mirror actions a user can perform while running a PICO-8 cart and pressing function keys or running shell commands. The `extcmd()` function allows triggering these actions at precise moments that may be difficult to capture by pressing keys, or when running in non-interactive "headless" mode (via the `-x` command line flag).

## Examples

```
function achievement\_unlocked(str)
  show\_toast(str)
  extcmd('screen') -- save a screenshot of the moment
end

```
Draw

The `_draw()` function is the second part of the game loop.

If a cartridge's source code includes both an `_update()` function and a `_draw()` function, then PICO-8 will attempt to call these functions once for each animation frame, at a rate of 30 frames per second (60 if `_update60()` is used.)

You define this function in your game's source code. It takes no arguments.

The intended purpose of `_draw()` is to draw the state of the game onto the screen, such as with calls to map() and spr(). A typical `_draw()` function starts with a call to cls() to clear the screen then draws all of the game elements, but this is not required.

If `_update()` and `_draw()` together take longer than 1/30th of a second (or 1/60th with `_update60()`) to complete, PICO-8 may decide not to call `_draw()` for a given frame. See the entry on the game loop.

## Examples

```
function \_draw()
  cls()
  print("hello, world!", rnd(76), rnd(124), rnd(15)+1)
end

```

## See also

* Game loop
* `_init()`
* `_update()`
* `stat()`
Tostr

tostr( val, [format\_flags] )
Converts a non-string value to a string representation.
val

The value to convert.

format\_flags

Bitfield which allows different operations to occur in the conversion
Returns the string representation of the value.

Given a number value, `tostr()` returns a string of the signed decimal representation of the number. If you set the optional second parameter to `true` (or 1), it will return an unsigned fixed point hexadecimal representation. (Use `sub()` on the result if you only want a portion of this string.)

Given a non-number value type, `tostr()` attempts to return something useful. Passing in a Boolean returns `'true'` or `'false'`. Passing in a string returns the string. `nil`, tables, functions, and threads return `[nil]`, `[table]`, `[function]`, and `[thread]`, respectively.

This is especially useful when concatenating values into string messages. The string concatenation operator (`..`) only accepts a string or a number on the right-hand side. A value of any other type must be converted to a string with `tostr()` before being concatenated to a string.

`[format_flags]` is a bitfield:

```
  0x1: For numbers, return a string with their full unsigned hexadecimal value (like '0x0012.8400')
       For tables and functions, return a string that uniquely identifies this object (e.g. 'table: 0x1234567')
  0x2: For numbers, return a string with a signed 32-bit integer by shifting the number left by 16 bits.

```

## Examples

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

s = 'v: '..tostr(0x0f)             -- 'v: 15'
s = 'v: '..tostr(0x0f, true)       -- 'v: 0x000f.0000'
s = 'v: '..tostr(-12345.67, true)  -- 'v: 0xcfc6.547b'

s = 'v: '..sub(tostr(0x0f, 3, 6))  == 'v: 000f'

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

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

s = 'v: '..tostr(nil)              -- 'v: [nil]'
s = 'v: '..tostr({1, 2, 3})        -- 'v: [table]'

f = function() print('hi') end
s = 'v: '..tostr(f)                -- 'v: [function]'

-- f is a function that does not return a value
f = function() return end
a = 'v: '..tostr(f())              -- 'v: [no value]'

```

## See also

* `tonum()`
* `tostring()` (vanilla Lua version)
* Math
* Lua
Parameters vs. Arguments

One of the most basic parts of programming is passing values to a function to get a result. It's useful to know how to describe those values to another programmer. There are two terms used to refer to them, which are *parameters* and *arguments*, and it's good to know when to use each of them.

A *parameter* is part of a function definition. It's usually a descriptive word that represents what kind of value should be passed into the function, and inside the function definition, it becomes a variable that holds the passed value. For instance, PICO-8's `cls(col)` function may be passed a color index to create a clear screen with. In this case, the *parameter* would be "col".

An *argument*, on the other hand is the *actual* value that is passed *into* a function parameter. So, in the case of clearing the screen to yellow with `cls(10)`, the *argument* would be "`10`".

## Remembering the difference

One method sometimes recommended to remember the difference is this:

* a **P**arameter is a **P**laceholder inside the function
* an **A**rgument is an **A**ctual value sent from outside the function

So, when referring to the passed value by name, it's a parameter, but when referring to actual, literal values that were passed in, it's an argument.

## Other options

It's worth noting that in a more academic context, especially among higher-level mathematicians, parameters and arguments might instead be called *formal parameters* and *actual parameters*. However, this is uncommon in the programming world, which seems to have settled on the definitions above.

## Disclaimer

This is all, of course, just semantics. It is *not* a critical thing to keep straight and usually no one will be upset if one is used when the other ought to be. Most programmers mix up these two words and use them almost interchangeably. This page exists purely to let anyone interested know the true difference, and perhaps to help guide them when editing the wiki.
Assert

assert( cond, [message] )
Causes a runtime error if a conditional expression is false.
cond

The conditional expression to assert.

message

A message to print when the assertion fails.

*return-value*

All arguments as passed to `assert()` in a tuple (if the assert didn't fail).
The purpose of `assert()` is to confirm what is assumed to be true any any given point. If the conditional expression evaluates to false, `assert()` triggers a runtime error, and PICO-8 stops the program and reports the error and line number of the assert.

An optional message may be passed to `assert()` to replace the default message, "assertion failed".

**Caution:** A runtime error inside of a coroutine will abort the coroutine, but will not automatically stop the application and report the error. Assertions inside of coroutines must be detected by the code that spawns and monitors the coroutines. See `coresume()` for information on detection and reporting.

## Examples

```
function divide(num, denom)
  assert(denom != 0, 'cannot divide by zero')
  return num/denom
end

print(divide(12, 4))  -- 3
print(divide(7, 0))   -- runtime error, assertion failed

```

## See also

* Lua
* `stop()`
Controllers

PICO-8 supports controllers out of the box.

Just plug in any game controller that can be connected to a computer, either with a wired USB connection or a wireless Bluetooth connection. PICO-8's controller support is based on the SDL library.

A game can have up to 8 simultaneous players. Players 1 and 2 can use game controllers or corresponding keys on the keyboard. Players 3-8 must use game controllers.

## Keyboard controls

While a game is playing, PICO-8 recognizes keyboard presses as controls for players 1 and 2. For example, player 1 can use the cursor keys, Z, and X for the six possible inputs.

For a complete list of default key mappings for players 1 and 2, see btn().

You can customize the key mappings for players 1 and 2 interactively using the keyconfig command. You can also edit config.txt directly.

## Configuring controllers

You can configure controller mappings by editing the `sdl_controllers.txt` file in the PICO-8 configuration directory. Each line of the file is a controller mapping in the format used by SDL. You only need one line for each kind of controller you wish to use.

Here is an example of a mapping line:

```
79000000000000001100000000000000,Retrolink Classic Controller,x:b3,a:b2,b:b1,y:b0,back:b8,start:b9,leftshoulder:b4,rightshoulder:b5,leftx:a3,lefty:a4,platform:Mac OS X,

```

You can generate this line using one of these tools:

* General Arcade's GamepadTool for Windows, Mac and Linux
* The `controllermap` tool distributed with SDL2
* Find your SDL2 controller mapping in this list.

The complete procedure for using GamePadTool:

1. Connect a controller to your computer.
2. Start GamePadTool. The tool should detect the controllers and allow you to select between them.
3. Make sure that the controller is selected, then click "Copy Mapping String." This copies the mapping string to your clipboard.
4. Edit the `sdl_controllers.txt` file in the PICO-8 configuration directory. Paste the mapping string onto its own line, then save the file.
5. Start (or restart) PICO-8 to use the new configuration.

## Connecting controllers

PICO-8 assigns controllers to players in roughly the order they are detected when PICO-8 starts up.

By default, player 1 gets the first controller. You can change which player gets the first controller by providing the `-joystick` command line argument when starting PICO-8. Its value is a number from 0 to 7 (player 1 through 8). For example, to start assigning controllers with player 3:

`pico8 -joystick 2`

There is no way to assign specific controllers to specific players.

If you connect a controller while PICO-8 is running, you must restart PICO-8 before you can use it.

## Testing controllers

Here is code for a simple cart that lets you test controllers for all players:

```
function _update()
end

glyphs={"\139","\145","\148","\131","\142","\151"}
function _draw()
  cls()
  for p=0,8 do
    print(''..p..':', 0, p*7, 1)
    for b=0,6 do
      if btn(b,p) then
        print(glyphs[b+1], b*8 + 10, p*7, p+1)
      end
    end
  end
end

```

## See also

* Configuration
* keyconfig
* SDL
Hydra

Creator
 Genre
 Player Count

## Description

Starting off on a large island, the player must find, enter, and make their way through three dungeons before facing a hydra boss in hopes of defeating the game.

## Rules

* The player must walk around the countryside until they find a dungeon entrance, then enter it.
* While inside, the player must swipe at enemies with their sword. Each one will take a few hits until they are killed; meanwhile, if they make contact with the player’s character, that will cause damage to the player (as shown on the player’s strength meter at bottom left of screen). If the player takes enough damage then the game will end, although the player has unlimited continues. Also, some enemies, upon being slain, will leave behind some “life essence that could be absorbed” by the player, which will partially heal them.
* A compass is included at the top part of the screen, along with a map at the bottom right corner, showing the layout of the current dungeon the player is in.
* All dungeons have two save areas that the player can continue their game with if they want to go back to it later, along with areas that will state that the dungeon was cleared, even if there are still rooms that the player has not yet encountered.
* Green creatures make up all dungeons, evil mages appear with the second dungeon, and the hydra appears during the final dungeon.

## 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 and enter/exit dungeons and doors.
* Use the x key to attack.
* Use the z key to strafe.
* Face each statue in the final dungeon in order to light them up to continue to the hydra.
Blockrush

## Information

This game was made by Oskar Zanota and Eddy Rashed, for the Pixeler’s game jam, that they won. It was made in 2 days, but the full version is still in development.

## How to play

You play as a cube in a 2D world. When you move, you cannot stop until you reach a solid object. To finish a level, get to the treasure chest ! There are also hidden crowns that you can (you don’t have to) pickup during your game.

* Play the game jam’s version here : https://oskar-codes.itch.io/blockrush
* Play the latest version here : https://oskar-codes.github.io/Blockrush

## Controls

Menu :

* Left and right arrow to navigate
* X, V, or M to select a level
* C, Z, or N to toggle music

In game :

* Move with arrow keys
* X, V, or M to reset the level, or to teleport if on a teleporter
* C, Z, or N to go back to the menu

## Objects

* Treasure chest : pick it up to finish the level
* Crown : an optional collectible that can be picked up in each level, picking it up brings you to the start of the level.
* Orb : stops you on your track and allows you to change direction.
* Teleporter : teleports you to the teleporter of the corresponding color when X, V, or M is pressed.
* Wall teleporter : teleports you to the corresponding teleporter on the same line when moving towards it. Your direction remains the same.
* Electricity : kills you whenever you touch it.
* Wall spikes : kills you if you move towards them.
* Arrow : changes your direction to the arrow's direction.
* WannaBeBlock : a block that destroys itself if you move towards it from far enough. (not available in the game jam’s version)
Руны

## Мощь магии

* Здоровье +60
* Маг.атака +3

## Медитация

* Маг.атака +7
* Сопротив.магии +2

## Священная сила

* Физ.атака +6
* Маг.атака +12

## Иллюзия

* Маг.атака +8
* Проникн.магии +2

**Синтез**: Дух иллюзий +  ++

## Покровительство

* Здоровье +140
* Сопротив.магии +2

**Синтез**: Здоровье + Сопротив.маг

## Всадник

* Здоровье +600
* Восст.Здоровья +150

**Синтез**: Дух всадника + Сильная судьба + Регенерация + Регенерация

## Повелитель войны

* Физ.атака +20
* Маг.атака +10

**Синтез:** Дух Бога войны + Осада + Двойной удар

## Воин

* Здоровье +300
* Броня +6
* Сопротив.магии +6

**Синтез:** Дух Война + Банши +  + Сопротив.маг

## Боец

* Здоровье +700

**Синтез:** Дух бойца + Банши + Бессмертие

## Шаман

* Маг.атака +30

**Синтез:** Дух шамана + Русалка

## Мудрец

* Здоровье +150
* Маг.атака +12
* Проникн.магии +4

**Синтез**: Дух мудреца + ++

## Чародей

* Маг.атака +25
* Восст.Энергии +25

**Синтез**: Дух чародея + +  +

## Гадюка

* Физ.атака +12
* Маг.атака +12
* Проникн.магии +3

**Синтез:** Дух гадюки + Иллюзия + Осада

## Паук

* Сопротив.магии +10

**Синтез:** Фрагмент паука х5

## Питон

* Маг.атака +12
* Сопротив.магии +6

**Синтез:** Дух питона +  +

## Слон

* Броня +10

**Синтез**: Фрагмент слона х5

## Лев

* Физ.атака +18
* Маг.атака +18

**Синтез**: Дух льва +  + Осада

## Гризли

* Здоровье +200
* Физ.атака +10
* Маг.атака +10

**Синтез**: Дух гризли + Законопослушание + Бессмертие

## Платибелодон

* Здоровье +120
* Броня +15

**Синтез**: Дух платибелодона +  + Стойкость

## Скорпион

* Здоровье +280
* Сопротив.магии +10

**Синтез:** Банши +

## Ястреб

* Здоровье +220
* Маг.атака +12

**Синтез**: Дух ястреба + Сильная судьба +  +

## Русалка

* Маг.атака +8

**Синтез**: Фрагмент русалки х5

## Аксон

* Маг.атака +40
* Восст.Здоровья +300

**Синтез**: Дух Аксона +  + Восст.здоровья + Восст.здоровья

## Молния

* Маг.атака +40

**Синтез**: Фрагмент молнии х30

## Посейдон

* Здоровье +300
* Маг.атака+20
* Сопротив.магии +8

**Синтез**: Дух Посейдона +  +

## Песня сирены

* Маг.атака +30
* Проникн.магии +5

**Синтез:** Дух песни сирены +  +

## Сфинкс

* Здоровье +700
* Маг.атака +30
* Физ.атака +30

**Синтез:** Дух сфинкса +  +

## Геракл

* Маг.аткак +30
* Сопротив.магии +12
* Восст.Энергии +20

**Синтез** Дух Геракла +  + Страж + Страж
Keyconfig

keyconfig
Opens the interactive key configuration tool.
You can use the `keyconfig` tool to change which keyboard keys correspond with the player 1 and player 2 buttons, as well as the pause key.

When you run the command, the list of keys appears. When you press a key (other than Delete or Escape), that key is assigned to the highlighted button, and the highlight moves down. Once you have configured all of the buttons, PICO-8 saves the configuration.

The configuration persists between runs of the PICO-8 app. It is stored in the configuration file `config.txt`, as the `button_keys` property.

You can abort without saving by pressing the Escape key any time before the last key.

To reset a button to use its default key, press the Delete key when that key is highlighted. To reset all buttons to default keys, run `keyconfig`, then press Delete for every key.

## Examples

```
> keyconfig

```

## See also

* `config`
* Configuration
Ls

ls
Lists the files in the current working directory of the cartridge storage area.
dir
Alias for `ls`.
You execute this system command at the PICO-8 prompt.

Unlike the `ls` command of some operating systems, this command does not take arguments. To see the contents of a directory (folder) in the cartridge storage area, first use the `cd` command to change the current working directory, then use `ls`.

The `dir` command is an alias for this command.

This command can also be used by a program as a function: `ls()` The return value is a table of filenames. This returns the names of files only, and does not return subdirectories.

## Examples

At the command prompt:

```
> cd demos
> ls

```

In code:

```
-- get the list of files
files = ls()

```

## See also

* `cd`
* `dir`
``* `folder`

* `load`

* `save```
INext

inext( tbl, [index] )
A stateless iterator of index-value pairs for sequence elements in a table.
tbl

The table.

index

The current index.

The `inext()` function is the stateless iterator that underpins `ipairs()`, as used in `for k,v in ipairs(t)` to iterate over sequence elements in a table. It takes the table and the current index and returns the next index/value pair, or nil if there isn't one. The index passed in may be omitted or nil to retrieve the first index/value pair of the table.Under normal conditions, `inext()` is not referred to directly, instead being supplied under the hood by `ipairs()`.

## See also

* Lua
* Tables
* `add()`
* `all()`
* `del()`
* `foreach()`
Sin

sin( angle )
Calculates the sine of an angle.
angle

The angle, using a full circle range of 0.0-1.0 measured clockwise (0.0 to the right).

The `sin()` function calculates the sine of an angle.

PICO-8 uses an input range of 0.0 to 1.0 to represent the angle, a percentage of the unit circle. Some refer to these units as "turns". For instance, 180° or π (3.14159) radians corresponds to 0.5 turns in PICO-8's representation of angles. In fact, for fans of τ (tau), it's just a matter of dropping τ from your expression.

**Important:** PICO-8 measures the angle in a *clockwise* direction on the Cartesian plane, with 0.0 to the right, 0.25 downward, and so on. This is inverted from the convention used in traditional geometry, though the inversion only affects `sin()`, not `cos()`.

The inversion is useful because PICO-8's screen (like most graphics engines) uses inverted y coordinates: an increase in y goes downward. Many uses of `sin()` would need to be inverted anyway, so PICO-8 does it by convention.

(The clockwise direction of the angle is equivalent to going counterclockwise and negating `sin()`. This is how it is described in the official documentation.)

## Examples

```
for t=0,1,0.125 do
  print('sin('..t..') = '..sin(t))
end

```

prints:

```
sin(0) = 0
sin(0.125) = -0.7071
sin(0.25) = -1
sin(0.375) = -0.7071
sin(0.5) = 0
sin(0.625) = 0.7071
sin(0.75) = 1
sin(0.875) = 0.7071
sin(1) = 0

```

## See also

* Math
* `cos()`
* `atan2()`