BazzBasic_AI_Guide / SKILL.md
EkBass's picture
Update SKILL.md
949ab82 verified
|
Raw History Blame Contribute Delete
37.4 kB
---
name: bazzbasic-code
description: "BazzBasic BASIC interpreter language reference. Use when writing, debugging, or explaining BazzBasic code (.bas files). Triggers on BazzBasic syntax, $ and # variable suffixes, SDL2 graphics in BASIC, SCREEN/DRAWSHAPE/LOADIMAGE commands, DEF FN functions, BazzBasic file I/O, sound commands, or any question about BazzBasic features. Always use this skill before writing any BazzBasic code. "
---
# BazzBasic Language Reference
**Version:** 1.6 | **Author:** Kristian Virtanen (EkBass) | **Platform:** Windows x64 only (SDL2 via P/Invoke — no Linux, macOS, browser or Android)
**Homepage:** https://ekbass.github.io/BazzBasic/
**GitHub:** https://github.com/EkBass/BazzBasic
**Manual:** https://ekbass.github.io/BazzBasic/manual
**Examples:** https://github.com/EkBass/BazzBasic/tree/main/Examples
**Rosetta Code:** https://rosettacode.org/wiki/Category:BazzBasic
**Rosetta Code solutions:** https://github.com/EkBass/BazzBasic/tree/main/Examples/rosetta-code
**BazzBasic-AI-Guide:** https://huggingface.co/datasets/EkBass/BazzBasic_AI_Guide
**BazzBasic Beginner's Guide:** https://github.com/EkBass/BazzBasic-Beginners-Guide/releases
BazzBasic is a BASIC meant for beginners and for small, fun experiments (simple games, quizzes, bouncing balls). It is not a high-performance game engine — keep generated code simple and readable rather than clever.
---
## ⚠️ Critical Rules — Read First
| Rule | Detail |
|------|--------|
| Variables end with `$` | `name$`, `score$`, `x$` — the suffix does NOT mean string type |
| Constants end with `#` | `MAX#`, `PI#`, `TITLE#` — `#` only means immutable |
| Arrays declared with `DIM`, end with `$` | `DIM items$` |
| First use of variable requires `LET` | `LET x$ = 0` — after that `x$ = x$ + 1` |
| FOR and INPUT auto-declare, no LET needed | `FOR i$ = 1 TO 10` |
| Case-insensitive | Keywords, variables and labels. Only string contents are case-sensitive |
| Functions defined **before** they are called | Put at top or INCLUDE — forward references don't resolve |
| Function name ends with `$`, called with `FN` | `FN MyFunc$(a$, b$)` |
| Function return value **must** be used | `PRINT FN f$()` or `LET v$ = FN f$()` |
| `DEF FN` scope is fully isolated | Only global `#` constants are visible. No `$` variables, no global arrays. Arrays cannot be passed as parameters — see *Passing Arrays to Functions* |
| `+` does both add and concatenate | If either side is a string, the other is auto-converted: `"Score: " + 5` → `"Score: 5"`, no `STR()` needed |
| Division always returns float | `10 / 3` → `3.333...` |
| Division by zero returns `0` silently | Guard with `IF b$ = 0 THEN ...` if correctness matters |
| No integer-division operator | Use `INT(a / b)`, `FLOOR(a / b)`, or `CINT(a / b)` |
| Errors halt the program | No `TRY`/`CATCH` or `ON ERROR` — line-numbered message printed |
| No line-continuation char | Leave an operator at line end or open a `(` — see *Line Continuation* |
| No line numbers | Never supported. Use `[labels]` |
| `:` separates statements on one line | `FOR i$ = 1 TO 3 : PRINT i$ : NEXT`. A `:` inside a label like `[sub:init]` is part of the label name, not a separator |
| `NOT` binds tighter than comparisons | `NOT a$ = b$` means `(NOT a$) = b$`. Parenthesize: `IF NOT (a$ = b$) THEN`, or use `<>` |
| Comments: `'` or `REM` | `' comment` anywhere on a line; `REM` as a statement, also after `:` (`PRINT x$ : REM note`) |
---
## 🚫 Common AI Mistakes (avoid these)
These are the patterns LLMs most often produce when extrapolating from QBASIC, FreeBASIC, or VB. None of them are valid BazzBasic.
```basic
' ❌ WRONG ' ✓ CORRECT
LET x = 5 LET x$ = 5
LET MAX = 10 LET MAX# = 10
score$ = 0 ' first use LET score$ = 0
DEF FN doStuff(a, b) DEF FN DoStuff$(a$, b$)
FN MyFunc$(5) ' return ignored LET v$ = FN MyFunc$(5)
LET handle$ = LOADIMAGE("x.png") LET HANDLE# = LOADIMAGE("x.png")
CLS ' in graphics mode LINE (0,0)-(W,H), 0, BF
PRINT "x:", x$ ' in graphics mode DRAWSTRING "x:" + x$, 10, 10, WHITE#
FSTRING("Hi {{name$}}") ' Python-style FSTRING("Hi {{-name$-}}") ' triple-char markers
ISSET(arr$(0)) ' expecting error ' returns 0 silently — ISSET only sees scalars
LET x$ = a$ + _ ' VBA continuation LET x$ = a$ + ' just leave the operator
LET x$ = a$ + \ ' Python continuation LET x$ = a$ + ' or open a paren
IF NOT a$ = b$ THEN ' QBASIC habit IF NOT (a$ = b$) THEN
```
---
## When Generating BazzBasic Code
- Prefer `FSTRING` over long `+` concatenation chains for multi-variable strings
- Place `DEF FN` definitions at the top of the file or via `INCLUDE`
- Store every `LOADIMAGE` / `LOADSOUND` / `LOADSHAPE` handle as a `#` constant. They return stable integer handles owned by SDL2 that never change. For many handles, an array is fine: `sprites$("player") = LOADIMAGE(...)`
- Declare all variables and constants in `[inits]`, not inside loops — this avoids repeated existence checks
- Precompute colors: `LET WHITE# = RGB(255, 255, 255)` in `[inits]`, never `RGB()` inside a game loop
- In graphics mode: clear with `LINE (0,0)-(W,H), 0, BF` (much faster than `CLS`), draw text with `DRAWSTRING` (`PRINT` flickers), and wrap each frame in `SCREENLOCK ON` / `SCREENLOCK OFF`
- If a feature isn't documented in this guide, say so rather than inventing one — BazzBasic does not silently inherit QBASIC, FreeBASIC, or VB conventions
---
## Minimal Valid Program
```basic
[inits] ' [name] is a plain jump label, not a keyword
LET name$ = "World"
[main]
PRINT "Hello, " + name$
END
' subroutines go after END
[sub:drawScreen]
' draw
RETURN
```
Programs flow top to bottom. `[inits]` and `[main]` are organizational labels, not required syntax. `END` halts execution; place it at the end of the main flow so control doesn't fall through into subroutines.
---
## Line Continuation
The lexer figures out continuation automatically using two rules. Never emit `_`, `\`, `&` or any other continuation marker.
**Rule 1 — operator at end of line.** If a line ends in a token that cannot legally end an expression, the next line continues it:
```basic
LET total$ = price$ * count$ -
discount$
IF score$ >= 0 AND
score$ <= 100 THEN
PRINT "Valid"
END IF
LET counter$ +=
step$
```
Tokens that trigger this: `+ - * / % = <> < <= > >= AND OR += -= *= /= ,`
> `%` is a real binary modulo operator and triggers continuation. `MOD(a, b)` is a function, so it does not (a `)` at line end never continues).
**Rule 2 — open paren.** Anything inside an unmatched `(` keeps reading until the matching `)`:
```basic
LET dist$ = DISTANCE(
x1$, y1$,
x2$, y2$
)
```
---
## Variables & Constants
Variables are dynamically typed, like in JavaScript.
```basic
LET a$ ' Declare without value
LET b$, c$, d$ ' Multiple declarations without value
LET e$, f$ = "foo", g$ = 10 ' e$ stays empty, f$ and g$ get values
LET name$ = "Alice" ' String
LET score$ = 0 ' Number
LET PI# = 3.14159 ' Constant (immutable)
LET TITLE# = "My Game" ' String constant
```
**Compound assignment** (variables only — **not** allowed with `#` constants):
```basic
LET x$ = 1
x$ += 5
x$ -= 3
x$ *= 2
x$ /= 4
LET s$ = "Hello"
s$ += " World" ' concatenation
```
**Scope:** All main-code variables share one scope — `IF`, `FOR`, and `WHILE` do NOT create a new scope.
**Comparison:** `"123" = 123` is TRUE (cross-type), but keep types consistent for speed.
### Built-in Constants
- **Boolean:** `TRUE` (`1`), `FALSE` (`0`) — plain numbers. `IF x$ = 1` and `IF x$ = TRUE` are identical.
- **Math:** `PI#`, `HPI#` (π/2 = 90°), `QPI#` (π/4 = 45°), `TAU#` (2π = 360°), `EULER#` (e)
- **System:** `PRG_ROOT#` (program base directory path, ends with a separator)
- **Version:** `BBVER#` (current BazzBasic version as a string, e.g. `"1.6"`)
- **Keyboard:** `KEY_ESC#`, `KEY_ENTER#`, `KEY_SPACE#`, `KEY_UP#`, `KEY_DOWN#`, `KEY_LEFT#`, `KEY_RIGHT#`, `KEY_F1#`…`KEY_F12#`, `KEY_A#`…`KEY_Z#`, `KEY_0#`…`KEY_9#`, `KEY_NUMPAD0#`…`KEY_NUMPAD9#`, `KEY_NUMPAD_PLUS#`, `_MINUS#`, `_MUL#`, `_DIV#`, `_DOT#`, `KEY_LSHIFT#`, `KEY_LCTRL#`, `KEY_RSHIFT#`, `KEY_RCTRL#`, `KEY_LALT#`, `KEY_RALT#`, `KEY_LWIN#`/`KEY_RWIN#`, `KEY_TAB#`, `KEY_BACKSPACE#`, `KEY_INSERT#`, `KEY_DELETE#`, `KEY_HOME#`, `KEY_END#`, `KEY_PGUP#`, `KEY_PGDN#` — see *Keyboard Input*
- **Gamepad:** see *Gamepad*
---
## Arrays
Arrays are fully dynamic and support numeric, string, or mixed indexing.
```basic
DIM scores$ ' Declare (required before use)
DIM a$, b$, c$ ' Multiple
scores$(0) = 95 ' Numeric indices are 0-based
scores$("name") = "Alice" ' String keys: associative, insertion-ordered
matrix$(0, 1) = "A2" ' Multi-dimensional
DIM sounds$
sounds$("guns", "shotgun_shoot") = "shoot_shotgun.wav"
sounds$("guns", "ak47_shoot") = "shoot_ak47.wav"
sounds$("food", "ham_eat") = "eat_ham.wav"
PRINT LEN(sounds$()) ' 3 - total elements across all groups
PRINT ROWCOUNT(sounds$()) ' 2 - "guns" & "food"
DIM car$
car$("manufacturer") = "Ford"
car$("engine") = "1.6 Eco"
FOR i$ = 0 TO LEN(car$()) - 1 ' No FOREACH — LEN + ARRKEY is the idiom
LET key$ = ARRKEY(car$(), i$)
PRINT key$; " = "; car$(key$)
NEXT i$
```
| Function/Command | Description |
|-----------------|-------------|
| `LEN(arr$())` | Total element count across all dimensions |
| `ROWCOUNT(arr$())` | Count of first-dimension rows — use this for FOR loops over multi-dim arrays |
| `ARRKEY(arr$(), i)` | Key at 0-based index `i`, in insertion order. Errors on out-of-range index |
| `HASKEY(arr$(key))` | 1 if exists, 0 if not — **always check before reading possibly uninitialized elements** |
| `DELKEY arr$(key)` | Remove one element |
| `DELARRAY arr$` | Remove entire array (can re-DIM after) |
| `JOIN dest$, src1$, src2$` | Merge two arrays; matching `src2$` keys overwrite `src1$` at the same level. Use an empty `src1$` to copy an array |
> `DIM arr$ = value` stores the value at `arr$(0)` — NOT as a scalar. If a scalar is what you want, use `LET`.
---
## Control Flow
```basic
' Block IF
IF score$ >= 90 THEN
PRINT "A"
ELSEIF score$ >= 80 THEN
PRINT "B"
ELSE
PRINT "F"
END IF ' ENDIF also works
' One-line IF
IF lives$ = 0 THEN GOTO [game_over]
IF key$ = KEY_ESC# THEN GOTO [menu] ELSE GOTO [play]
' FOR (auto-declares variable)
FOR i$ = 1 TO 10 STEP 2 : PRINT i$ : NEXT
FOR i$ = 10 TO 1 STEP -1 : PRINT i$ : NEXT
' WHILE
WHILE x$ < 100
x$ = x$ * 2
WEND
' Labels, GOTO, GOSUB
[start]
GOSUB [sub:init]
GOTO [start] ' Avoid jumping into the middle of IF/WHILE blocks
[sub:init]
LET x$ = 0
RETURN
' Dynamic jump (variable must contain "[label]" with brackets)
LET target$ = "[menu]"
GOTO target$
SLEEP 2000 ' Pause for milliseconds
END ' Terminate program
```
Labels may contain almost any printable character. Whitespace is trimmed; everything between `[` and `]` is the label name.
---
## I/O
| Command | Description |
|---------|-------------|
| `PRINT expr; expr` | `;` = no space, `,` = tab, can be mixed |
| `PRINT "text";` | Trailing `;` suppresses newline |
| `INPUT "prompt", var$` | Splits on whitespace/comma; quoted strings are single values |
| `INPUT "prompt", a$, b$` | Multiple values |
| `LINE INPUT "prompt", var$` | Read entire line with spaces |
| `CLS` | Clear screen (console) |
| `LOCATE row, col` | Move cursor (1-based) |
| `CURPOS("row")` / `CURPOS("col")` | Read cursor row or col (1-based, matches LOCATE) |
| `CURPOS()` | Read cursor as `"row,col"` string |
| `COLOR fg, bg` | Text colors, palette 0–15 only (`RGB()` does not work here) |
| `GETCONSOLE(row, col, type)` | Read console cell. type: 0=char (ASCII), 1=fg color, 2=bg color |
| `SHELL("cmd")` | Run shell command, returns output |
| `SHELL("cmd", ms)` | With timeout in ms (default 5000) |
**Escape sequences in strings:** `\"` `\n` `\t` `\\` `""`
**SHELL + SQLite.** The `sqlite3` CLI is the recommended way to add a database — see the *SQLite Database* page in the manual. When wrapping SQL in SHELL:
- Always append `2>&1`, or SQL errors disappear silently.
- Wrap the SQL with `\"`: `SHELL("sqlite3 db.sqlite \"SELECT * FROM users\" 2>&1")`.
- In paths use `/` or `\\` — never a single `\`.
### Keyboard Input
| Function | Returns | Notes |
|----------|---------|-------|
| `INKEY` | Key value or 0 | Non-blocking |
| `KEYDOWN(key#)` | TRUE/FALSE | Held-key detection, graphics mode only |
| `WAITKEY(key#, ...)` | Key value | Blocks until key pressed; `WAITKEY()` = any key |
- **Layout-safe keys:** letters, digits, arrows, Space/Enter/Esc, F-keys, numpad and modifiers are the same on every layout — use these for controls. Main-keyboard punctuation (`+ - = , . /`) depends on the layout: never bind controls to `ASC("+")` or `ASC("-")`; use letters or `KEY_NUMPAD_PLUS#` / `KEY_NUMPAD_MINUS#`.
- Letters always return uppercase codes (`"a"` and `"A"` → `KEY_A#`), in both graphics and console mode.
- `KEYDOWN` follows the key *label* on the current layout, same as `INKEY`. If no key types a punctuation character without modifiers (e.g. `=` on a Finnish keyboard), `KEYDOWN` of that constant is always FALSE.
- Numpad Enter = `KEY_ENTER#`.
- `INKEY` consumes the key: read it once per loop pass (`LET k$ = INKEY`) and compare the variable. A second `INKEY` in the same pass returns 0.
- Console mode: `INKEY`/`WAITKEY` return the typed character (except letters and special keys); numpad returns the typed digit, not `KEY_NUMPAD*#`.
### Mouse (graphics mode only)
`MOUSEX`, `MOUSEY` — cursor position
`MOUSELEFT`, `MOUSERIGHT`, `MOUSEMIDDLE` — 1 if pressed, 0 otherwise
`MOUSEHIDE` / `MOUSESHOW` — hide / restore the cursor
### Gamepad (console AND graphics mode)
| Function | Returns | Notes |
|----------|---------|-------|
| `GAMEPADS()` | Number of connected pads | Parentheses optional |
| `PADBUTTON(pad, button)` | TRUE/FALSE | TRUE while held (like `KEYDOWN`) |
| `PADAXIS(pad, axis)` | Number | Sticks -1.0…1.0, triggers 0.0…1.0, built-in dead zone |
| `PADNAME(pad)` | String | e.g. `"PS4 Controller"`, `""` if not connected |
| `PADRUMBLE pad, strength, ms` | — (statement) | strength 0.0…1.0, non-blocking, parentheses optional |
- Pad index is **0-based**, max 8 pads. Slots are stable while connected (not re-packed on disconnect). Hot-plug works.
- **No `SCREEN` needed** — works in console programs too.
- **Disconnected pad = no input, never an error:** `PADBUTTON` → FALSE, `PADAXIS` → 0, `PADNAME` → `""`. Don't guard every read with `IF GAMEPADS() > 0`; use `GAMEPADS()` only to show a "connect a pad" message.
- Buttons (Xbox naming): `PAD_A#` `PAD_B#` `PAD_X#` `PAD_Y#`, `PAD_UP#` `PAD_DOWN#` `PAD_LEFT#` `PAD_RIGHT#`, `PAD_LB#` `PAD_RB#`, `PAD_LSTICK#` `PAD_RSTICK#`, `PAD_BACK#` `PAD_START#` `PAD_GUIDE#`, `PAD_MISC#`, `PAD_TOUCHPAD#`. PlayStation: A=Cross, B=Circle, X=Square, Y=Triangle. Raw 0–20 valid (16–19 = Elite paddles); outside → error.
- Axes: `PAD_LX#` `PAD_LY#` `PAD_RX#` `PAD_RY#` `PAD_LT#` `PAD_RT#`. Raw 0–5; outside → error.
- **Y axis: negative = up**, same as screen Y. `y$ = y$ + PADAXIS(0, PAD_LY#) * SPEED#` is correct — do not invert.
- **L2/R2 are triggers, not buttons:** read with `PADAXIS(pad, PAD_LT#)`. Never pass an axis constant to `PADBUTTON` — `PADBUTTON(0, PAD_LT#)` silently reads button 4 (`PAD_BACK#`).
- For one action per press, keep previous state: `IF now$ = TRUE AND was$ = FALSE THEN ...` then `was$ = now$`.
- Stick as digital direction: `IF PADAXIS(0, PAD_LX#) < -0.5 THEN ...`
- Pad OR keyboard: `IF PADBUTTON(0, PAD_LEFT#) OR KEYDOWN(KEY_LEFT#) THEN dx$ = -1`
- Many third-party pads identify as PS4/Xbox controllers — normal, mapping is still correct.
---
## User-Defined Functions
```basic
DEF FN Clamp$(val$, lo$, hi$)
IF val$ < lo$ THEN RETURN lo$
IF val$ > hi$ THEN RETURN hi$
RETURN val$
END DEF
PRINT FN Clamp$(5, 1, 10) ' ✓ return value used
LET v$ = FN Clamp$(15, 0, 10) ' ✓
FN Clamp$(5, 1, 10) ' ✗ ERROR — return value unused
```
- Scope is isolated (see *Critical Rules*). Touching a global array gives: `Global array G$ is not visible inside DEF FN - pass it as a parameter with ASJSON() and rebuild it with ASARRAY()`
- `DIM` inside a function creates a **fresh, empty, local** array on every call and every recursion level:
```basic
DEF FN Count$(x$)
DIM t$
t$(x$) = 1
RETURN LEN(t$())
END DEF
PRINT FN Count$(1) ' 1
PRINT FN Count$(2) ' 1 (not 2)
```
- Parameters are passed **by value**
- Labels inside functions are local — GOTO/GOSUB cannot jump outside
- Recursion uses the real call stack, so thousands of levels can overflow it. GOSUB/RETURN uses a separate heap-based stack with no such limit.
---
## String Functions
| Function | Description |
|----------|-------------|
| `ASC(s$)` | ASCII code of first char |
| `CHR(n)` | Character from ASCII code |
| `INSTR(s$, search$)` | Position (1-based), 0=not found; case-sensitive |
| `INSTR(s$, search$, mode)` | mode: 0=case-insensitive, 1=case-sensitive |
| `INVERT(s$)` | Reverse string |
| `LCASE(s$)` / `UCASE(s$)` | Lower / upper case |
| `LEFT(s$, n)` / `RIGHT(s$, n)` | First/last n chars |
| `LEN(s$)` | String length |
| `LTRIM(s$)` / `RTRIM(s$)` / `TRIM(s$)` | Strip whitespace |
| `MID(s$, start)` | Substring from start (1-based) |
| `MID(s$, start, len)` | Substring with length |
| `REPEAT(s$, n)` | Repeat string n times |
| `REPLACE(s$, a$, b$)` | Replace a$ with b$ in s$ |
| `SPLIT(arr$, s$, sep$)` | Split into array (keys `0`..`count-1`), returns count. Array is emptied first. `arr$()` also accepted |
| `SRAND(n)` | Random alphanumeric string of length n. `n = 0` → `""`; **negative n crashes** with an overflow error — never pass an unvalidated length |
| `STR(n)` | Number to string |
| `VAL(s$)` | String to number |
| `SHA256(s$)` | SHA256 hash (64-char hex) |
| `BASE64ENCODE(s$)` / `BASE64DECODE(s$)` | Base64 encode/decode |
---
## FSTRING — String Interpolation
`FSTRING(template$)` substitutes `{{-name-}}` placeholders with the value of variables, constants, or array elements.
```basic
LET name$ = "Krisu"
LET LEVEL# = 5
PRINT FSTRING("Hello {{-name$-}}, level {{-LEVEL#-}}")
' Output: Hello Krisu, level 5
```
The triple-character markers `{{-` and `-}}` are deliberately unusual. There is no escape syntax — literal `{{-...-}}` is always parsed as a placeholder.
| Form | Resolves to |
|------|-------------|
| `{{-var$-}}` | Variable `var$` |
| `{{-CONST#-}}` | Constant `CONST#` (built-ins like `{{-PI#-}}` work too) |
| `{{-arr$(0)-}}` | Element at numeric index `0` |
| `{{-arr$(i$)-}}` | Element at index from variable `i$` |
| `{{-arr$(KEY#)-}}` | Element at index from constant `KEY#` |
| `{{-arr$(name)-}}` | Element at literal string key `"name"` (no quotes inside FSTRING) |
| `{{-arr$(0, i$)-}}` | Multidimensional, mixed literal and variable indices |
**Index resolution** — for each comma-separated index, FSTRING checks:
1. Ends with `$` or `#` → variable / constant lookup. Halts if undefined.
2. Parses as a number → numeric index. `arr$(01)` and `arr$(1.0)` both resolve to key `1`.
3. Otherwise → literal string key.
So `{{-name-}}` (no suffix) is a literal array key, **not** variable `name$`. Always include the suffix.
**Notes:** Whitespace inside placeholders is trimmed. Numbers auto-stringify. FSTRING returns a value and must be used — a bare `FSTRING(...)` statement is an error. Undefined names, missing `-}}`, empty `{{--}}`, malformed or uninitialized array access all halt with a line-numbered message.
**Not supported:** arithmetic, function calls, nested lookups, or quoted literals inside placeholders. Pre-compute into a variable:
```basic
' ❌ WRONG
PRINT FSTRING("Total: {{-a$ + 5-}}")
PRINT FSTRING("Name: {{-UCASE(name$)-}}")
PRINT FSTRING("{{-arr$(arr2$(0))-}}")
' ✓ RIGHT
LET total$ = a$ + 5
LET upper$ = UCASE(name$)
LET k$ = arr2$(0)
PRINT FSTRING("Total: {{-total$-}}, Name: {{-upper$-}}, Item: {{-arr$(k$)-}}")
```
**Full example:**
```basic
DIM player$
player$("name") = "Krisu"
player$("class") = "Bass"
player$("level") = 99
DIM grid$
grid$(1, 0) = "."
grid$(1, 1) = "X"
LET row$ = 1
PRINT FSTRING("{{-player$(name)-}} the {{-player$(class)-}}, lvl {{-player$(level)-}}")
PRINT FSTRING("Row {{-row$-}}: [{{-grid$(row$, 0)-}}{{-grid$(row$, 1)-}}]")
END
' Output:
' Krisu the Bass, lvl 99
' Row 1: [.X]
```
---
## Math Functions
| Function | Description |
|----------|-------------|
| `ABS(n)` | Absolute value |
| `ATAN(n)` | Arc tangent |
| `ATAN2(y, x)` | Angle in radians from the positive x-axis to point (x, y) |
| `BETWEEN(n, min, max)` | TRUE if min ≤ n ≤ max |
| `INBETWEEN(n, min, max)` | TRUE if min < n < max (strict) |
| `CEIL(n)` / `FLOOR(n)` | Round up / down |
| `CINT(n)` | Round to nearest integer |
| `CLAMP(n, min, max)` | Constrain n to [min, max] |
| `COS(n)` / `SIN(n)` / `TAN(n)` | Trig (radians) |
| `DEG(rad)` / `RAD(deg)` | Radians ↔ degrees |
| `DISTANCE(x1,y1, x2,y2)` | 2D Euclidean distance |
| `DISTANCE(x1,y1,z1, x2,y2,z2)` | 3D Euclidean distance |
| `EXP(n)` | e^n |
| `INT(n)` | Truncate toward zero |
| `LERP(start, end, t)` | Linear interpolation (t: 0.0–1.0) |
| `LOG(n)` | Natural logarithm |
| `MAX(a, b)` / `MIN(a, b)` | Larger / smaller of two |
| `MOD(a, b)` / `a % b` | Remainder (function and operator forms are equivalent) |
| `POW(base, exp)` | Power |
| `RND(n)` | Random integer 0 to n-1 (n > 0) |
| `RND(0)` | Random float 0.0–1.0 |
| `ROUND(n)` | Nearest integer, half away from zero (`0.5→1`, `-0.5→-1`) — NOT banker's rounding |
| `SGN(n)` | Sign: -1, 0, or 1 |
| `SQR(n)` | Square root |
### Fast Trigonometry
About 20× faster than `SIN(RAD(x))`, 1-degree precision, ~5.6 KB memory. Use for raycasting, sprite rotation, particle systems — anything calling trig hundreds of times per frame.
```basic
FastTrig(TRUE) ' Enable lookup tables (must call first)
LET x$ = FastCos(45) ' Degrees, auto-normalized 0–359
LET y$ = FastSin(90)
LET r$ = FastRad(180) ' Deg→rad (no FastTrig needed)
FastTrig(FALSE) ' Free memory
```
---
## ISSET
`ISSET(name)` returns `1` if the named variable (`$`) or constant (`#`) is declared, `0` otherwise. The argument is **not evaluated**, so `ISSET(undef$)` safely returns `0`.
- **Scalars only.** `ISSET(arr$)` and `ISSET(arr$(0))` always return `0`, never an error.
- **Bare name only.** Expressions, string literals, numbers or an empty argument (`ISSET(a$ + b$)`, `ISSET("a$")`, `ISSET(42)`, `ISSET()`) error with "invalid parameter".
- **Suffix is part of the name:** `a$` and `A#` are different names.
- **`LET name$` without a value still counts as set.** ISSET reports declaration, not "has a meaningful value".
```basic
IF ISSET(playerName$) = FALSE THEN
LET playerName$ = "Anonymous"
END IF
```
---
## Graphics
```basic
SCREEN 12 ' 640×480 VGA
SCREEN 0, 800, 600 ' Custom size
SCREEN 0, 1024, 768, "My Game" ' Custom size + title
FULLSCREEN TRUE ' Borderless fullscreen (graphics only)
FULLSCREEN FALSE ' Windowed
```
Classic modes: 1, 7, 13 = 320×200 · 2, 9 = 640×350 · 12 = 640×480.
### Drawing Primitives
```basic
PSET (x, y), color ' Pixel
LINE (x1,y1)-(x2,y2), color ' Line
LINE (x1,y1)-(x2,y2), color, B ' Box outline
LINE (x1,y1)-(x2,y2), color, BF ' Box filled
CIRCLE (cx,cy), radius, color ' Circle outline
CIRCLE (cx,cy), radius, color, 1 ' Circle filled
PAINT (x, y), fillColor, borderColor ' Flood fill
LET c$ = POINT(x, y) ' Read pixel color
LET COL# = RGB(r, g, b) ' Create color (0–255 each)
```
**Color values:** All drawing primitives (`PSET`, `LINE`, `CIRCLE`, `PAINT`, `DRAWSTRING`, `LOADSHAPE`) accept a palette index 0–15 or an `RGB(r, g, b)` value. Never hand-construct packed integers (e.g. `16711680`) — `RGB()` tags its value internally, and a raw integer is misread as a palette index.
**Palette (0–15):** 0=Black, 1=Blue, 2=Green, 3=Cyan, 4=Red, 5=Magenta, 6=Brown, 7=Lt Gray, 8=Dk Gray, 9=Lt Blue, 10=Lt Green, 11=Lt Cyan, 12=Lt Red, 13=Lt Magenta, 14=Yellow, 15=White
### Screen Control
```basic
SCREENLOCK ON ' Start frame (buffer drawing)
SCREENLOCK OFF ' Present buffer
VSYNC(TRUE) ' Enable VSync (default) — loop runs at monitor refresh rate
VSYNC(FALSE) ' Disable VSync (benchmarking)
```
### Shapes & Images
```basic
LET RECT# = LOADSHAPE("RECTANGLE", w, h, color) ' or "CIRCLE", "TRIANGLE"
LET IMG_PLAYER# = LOADIMAGE("player.png") ' PNG (alpha) or BMP
LET IMG_REMOTE# = LOADIMAGE("https://example.com/a.png") ' Download + load
' Sprite sheet — sprites indexed 0-based
DIM sprites$
LOADSHEET sprites$, 128, 128, "sheet.png" ' tileW, tileH, file
MOVESHAPE sprites$(0), x, y
MOVESHAPE RECT#, x, y ' Position
ROTATESHAPE RECT#, angle ' Degrees (absolute)
SCALESHAPE RECT#, scale ' 1.0 = original size
DRAWSHAPE RECT# ' Render to buffer
SHOWSHAPE RECT# / HIDESHAPE RECT# ' Toggle visibility
REMOVESHAPE RECT# ' Free memory (always clean up)
```
**Anchor point:** `LOADSHAPE` primitives are center-anchored; `LOADIMAGE` images are top-left-anchored.
### Text Rendering (requires SDL2_ttf.dll next to the interpreter)
```basic
DRAWSTRING "Hello!", 100, 200, WHITE# ' Default font: Arial, 16px
LOADFONT "comic.ttf", 24 ' Becomes the new default
LOADFONT ' Reset to Arial 16px
```
`DRAWSTRING text, x, y, color` positions the top-left of the text.
---
## Sound
```basic
LET SND_JUMP# = LOADSOUND("jump.wav") ' Load (WAV recommended)
SOUNDONCE(SND_JUMP#) ' Play once, non-blocking
SOUNDONCEWAIT(SND_JUMP#) ' Play once, wait for finish
SOUNDREPEAT(SND_JUMP#) ' Loop continuously
SOUNDSTOP(SND_JUMP#) ' Stop specific sound
SOUNDSTOPALL ' Stop all sounds
```
Load all sounds at startup. Call `SOUNDSTOPALL` before `END`.
---
## File I/O
```basic
LET data$ = FILEREAD("file.txt") ' Read as string
DIM cfg$ : LET cfg$ = FILEREAD("settings.txt") ' Read as key=value array
FILEWRITE "save.txt", data$ ' Create/overwrite (array → key=value format)
FILEAPPEND "log.txt", entry$ ' Append
LET ok$ = FILEEXISTS("file.txt") ' 1=exists, 0=not
FILEDELETE "temp.dat" ' Delete file
DIM files$
LET n$ = FILELIST(files$, "levels", "*.txt") ' Names into files$(0..n-1), returns n
```
**key=value parsing:** When `FILEREAD` assigns to a `DIM`'d array, lines `key=value` become `arr$("key")`; lines starting with `#` are comments. Round-trips with `FILEWRITE`. Good for `.env` files:
```basic
DIM env$
LET env$ = FILEREAD(".env")
LET API_KEY# = env$("OPENAI_API_KEY")
```
**FILELIST:** files only (no folders, not recursive), names only (no paths), sorted alphabetically ignoring case, hidden/system files skipped. The array is cleared first. Pattern supports `*` and `?`, default all files. Missing folder → returns `0`. To open a listed file, prepend the folder: `FILEREAD("levels/" + files$(i$))`.
**Paths:** Use `/` or `\\` — never a single `\` (escape char). Relative paths are from `PRG_ROOT#`, which already ends with a separator: `PRG_ROOT# + "data.txt"`.
---
## Network
```basic
LET res$ = HTTPGET("https://api.example.com/data")
LET res$ = HTTPPOST("https://api.example.com/submit", "{""key"":""val""}")
' Optional headers
DIM headers$
headers$("Authorization") = "Bearer mytoken"
headers$("Content-Type") = "application/json"
LET res$ = HTTPGET("https://api.example.com/data", headers$)
LET res$ = HTTPPOST("https://api.example.com/data", body$, headers$)
' Optional timeout in seconds, AFTER headers (default 30, 0 = no limit)
LET res$ = HTTPPOST("http://localhost:11434/v1/chat/completions", body$, headers$, 120)
```
### Local HTTP server (LISTEN)
Local-only server, typically glue between a static HTML page and a BazzBasic script on the same machine.
```basic
STARTLISTEN 8080 ' Bind 127.0.0.1:8080, no admin needed
STARTLISTEN 8080, 5000 ' Optional timeout in ms
LET body$ = GETREQUEST() ' POST/PUT/PATCH body or GET query string ("" on timeout)
SENDRESPONSE "{""status"":""ok""}" ' Must be called or the browser hangs
STOPLISTEN
```
- **Always pair `GETREQUEST()` with `SENDRESPONSE`.**
- **Bound to `127.0.0.1` only.** Do not generate code that tries to expose it on a LAN or the internet.
- **Body or query string only** (no `?`). Headers, method and URL path are not exposed. Parse JSON bodies with `ASARRAY`.
- **OPTIONS preflight and CORS are automatic.** Don't handle `OPTIONS`; every response carries `Access-Control-Allow-Origin: *`.
- **One listener at a time.** Call `STOPLISTEN` before another `STARTLISTEN`.
- **Always 200 OK, always `text/plain`.** To return JSON, put JSON text in the body — browser-side `response.json()` still works.
```basic
STARTLISTEN 8080
PRINT "Waiting for browser..."
LET json$ = GETREQUEST()
DIM data$
LET count$ = ASARRAY(data$, json$)
PRINT "Got name: " + data$("name")
SENDRESPONSE "{""status"":""ok""}"
STOPLISTEN
END
```
---
## Arrays & JSON
Nested JSON maps to comma-separated keys: `data$("player,name")`, `data$("skills,0")`.
```basic
LET json$ = ASJSON(arr$) ' Array → JSON string
DIM data$
LET count$ = ASARRAY(data$, json$) ' JSON string → array, returns element count
LOADJSON arr$, "file.json" ' Load JSON file
SAVEJSON arr$, "file.json" ' Save JSON file
```
### Passing Arrays to Functions
Serialize with `ASJSON`, pass the string, rebuild inside with `ASARRAY`. The function gets an independent copy — changes inside do not affect the original. Nested keys work normally.
```basic
DEF FN ProcessPlayer$(data$)
DIM arr$
LET count$ = ASARRAY(arr$, data$)
RETURN arr$("name") + " score:" + arr$("score")
END DEF
[inits]
DIM player$
player$("name") = "Alice"
player$("score") = 9999
player$("address,city") = "New York"
[main]
LET json$ = ASJSON(player$)
PRINT FN ProcessPlayer$(json$)
END
```
---
## Date & Time
```basic
LET t$ = TIME() ' Default "HH:mm:ss" -> "15:21:22"
LET t2$ = TIME("dd.MM.yyyy") ' .NET DateTime format -> "04.09.2026"
LET t3$ = TIME("dddd") ' -> "Friday"
LET start$ = TICKS ' Milliseconds since program start
```
**Timing — SLEEP and TICKS do different jobs:**
- **Frame pacing:** in graphics mode, VSync (on by default) waits at `SCREENLOCK OFF`, limiting the loop to the monitor's refresh rate — usually 60 FPS, but 144 FPS on a 144 Hz monitor. Do NOT add `SLEEP 16` to a graphics loop — together they halve the frame rate.
- **SLEEP ms:** use for deliberate pauses (title screens, "Game Over" delays) and to keep console loops from using 100% CPU (`SLEEP 10` in an `INKEY` polling loop).
- **TICKS:** use for measuring time — timers, cooldowns, animation speed, and movement that should stay the same speed on every monitor.
```basic
[inits]
LET running$ = TRUE
LET lastTick$ = TICKS
LET delta$
LET x$ = 0, speed$ = 2 ' several variables in one LET
[main]
WHILE running$
delta$ = TICKS - lastTick$
lastTick$ = TICKS
x$ = x$ + speed$ * delta$ / 16 ' same speed regardless of frame rate
GOSUB [sub:draw]
WEND
END
```
---
## Command-Line Arguments
```basic
' bazzbasic.exe myprog.bas arg1 arg2
PRINT ARGCOUNT ' 2
PRINT ARGS(0) ' "arg1"
PRINT ARGS(1) ' "arg2"
```
0-based; does not include the interpreter or script name.
---
## Libraries & INCLUDE
```basic
INCLUDE "helpers.bas" ' Insert source at this point
INCLUDE "MathLib.bb" ' Load compiled library
' Compile library (functions only — no loose code)
' bazzbasic.exe -lib MathLib.bas → MathLib.bb
' Function names auto-prefixed: MATHLIB_functionname$
PRINT FN MATHLIB_add$(5, 3)
```
- Library functions can read main-program constants (`#`).
- `.bb` files are **version-locked** to the build that produced them — recompile after upgrading.
- **No extension fallback:** `INCLUDE "helpers"` does NOT try `helpers.bas`.
- **Path resolution:** relative to the including file's directory first, then the program's base path.
- **Circular includes** halt with `Circular INCLUDE detected: <file>`.
---
## Program Structure
```basic
' ---- 1. FUNCTIONS (or INCLUDE) ----
DEF FN Clamp$(v$, lo$, hi$)
IF v$ < lo$ THEN RETURN lo$
IF v$ > hi$ THEN RETURN hi$
RETURN v$
END DEF
' ---- 2. INIT — declare ALL constants & variables here ----
[inits]
LET SCREEN_W# = 640
LET SCREEN_H# = 480
LET MAX_SPEED# = 5
LET PLAYER_COLOR# = RGB(0, 255, 0)
SCREEN 0, SCREEN_W#, SCREEN_H#, "My Game"
LET x$ = 320
LET y$ = 240
LET running$ = TRUE
' ---- 3. MAIN LOOP ----
[main]
WHILE running$
IF INKEY = KEY_ESC# THEN running$ = FALSE
GOSUB [sub:update]
GOSUB [sub:draw] ' SCREENLOCK OFF + VSync paces the loop to the monitor refresh rate
WEND
SOUNDSTOPALL
END
' ---- 4. SUBROUTINES (or INCLUDE) ----
[sub:update]
IF KEYDOWN(KEY_LEFT#) THEN x$ = x$ - MAX_SPEED#
IF KEYDOWN(KEY_RIGHT#) THEN x$ = x$ + MAX_SPEED#
RETURN
[sub:draw]
SCREENLOCK ON
LINE (0,0)-(SCREEN_W#, SCREEN_H#), 0, BF
CIRCLE (x$, y$), 10, PLAYER_COLOR#, 1
SCREENLOCK OFF
RETURN
```
**Naming conventions:** variables `camelCase$`, constants `UPPER_SNAKE_CASE#`, functions `PascalCase$`, labels `[gameLoop]` for jump targets and `[sub:name]` for subroutines.
---
## IDE
From version 1.6, the IDE (`BazzBasic-IDE.exe`) and interpreter (`BazzBasic.exe`) are separate programs in the same release .zip. Launching the interpreter without arguments tries to open the IDE; if that fails, it prints a message to the console.
| Menu | Items |
|------|-------|
| **File** | New, Open, Save, Save As, Save All, Close Tab, Close All, Restore Session on Startup¹, Print, Exit |
| **Edit** | Undo, Redo, Cut, Copy, Paste, Select All, Comment Selection, Uncomment Selection |
| **Search** | Find, Replace |
| **View** | Tree View¹ (DEF FN functions and labels on the left), Open Console², Open File Browser², Light Mode¹, Dark Mode (experimental)¹, Syntax Coloring¹ (off = monochrome), Take a Screenshot to Clipboard (IDE window only), Zoom In, Zoom Out |
| **Run** | Run Program (F5), Compile as Exe, Compile as Library (.bb), Path to BazzBasic.exe³ |
| **Help** | About, Homepage, Online Manual, Beginner's Guide, Rosetta Code, Check for Updates |
¹ Saved to `%AppData%\BazzBasic\ide.json`
² Opens in the current file's folder
³ Used if set; otherwise the IDE's own folder, then `PATH`
- Compile commands auto-save the file first.
- Help-menu links open the URLs listed at the top of this guide.
- CLI equivalents: `bazzbasic.exe -guide` / `-help` prints the Beginner's Guide URL, `bazzbasic.exe -checkupdates` checks for a newer version.
- New files get this template:
```basic
' BazzBasic version {ver_num}
' https://ekbass.github.io/BazzBasic/
```
## Examples
Example programs can be found in the `Examples/` directory (relative to the directory for this skill).
- Before writing BazzBasic code, review the examples most relevant to the task and follow the practices demonstrated in them (naming conventions, structure, typical idioms).
- The examples are organized into folders, such as "graphics", "console", "API", "GamePad", etc.