BazzBasic_AI_Guide / BazzBasic-AI-guide.txt
EkBass's picture
Update BazzBasic-AI-guide.txt
a31960f verified
---
name: bazzbasic
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.3 | **Author:** Kristian Virtanen (EkBass) | **Platform:** Windows x64
**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
---
## ⚠️ Critical Rules — Read First
| Rule | Detail |
|------|--------|
| Variables end with `$` | `name$`, `score$`, `x$` |
| Constants end with `#` | `MAX#`, `PI#`, `TITLE#` |
| 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` |
| Functions defined **before** they are called | Put at top or INCLUDE |
| 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$()` |
| Arrays **cannot** be passed to functions directly | Pass individual elements, or serialize to JSON string — see *Passing Arrays to Functions* section |
| Case-insensitive | `PRINT`, `print`, `Print` all work |
| `+` operator does both add and concatenate | `"Hi" + " " + name$` |
| Division always returns float | `10 / 3` → `3.333...` |
---
## ABOUT
BazzBasic is built around one simple idea: starting programming should feel nice and even fun.
Ease of learning, comfort of exploration and small but important moments of success.
Just like the classic BASICs of decades past, but with a fresh and modern feel.
## STORY
Although over the years, as my own skills have grown, I have moved on to more versatile and modern languages, BASIC has always been something that has been fun to try out many different things with.
Sometimes it's great to just make a simple adventure game again, a lottery machine, a quiz, or even just those balls bouncing on the screen.
BazzBasic was created with this in mind.
I wanted to create a language that makes it easy for you to give free rein to your curiosity and program something.
And when you finish your first little game, you may crave something bigger and better.
Maybe one day you will move on to another programming language, but then BazzBasic will have succeeded in doing what it was intended for.
To arouse your curiosity.
## Variables & Constants
```basic
LET a$ ' Declare without value
LET name$ = "Alice" ' String variable
LET score$ = 0 ' Numeric variable
LET x$, y$, z$ = 10 ' Multiple declaration
LET PI# = 3.14159 ' Constant (immutable)
LET TITLE# = "My Game" ' String constant
```
**Compound assignment operators** (variables only — **not** allowed with `#` constants):
```basic
x$ += 5 ' add
x$ -= 3 ' subtract
x$ *= 2 ' multiply
x$ /= 4 ' divide
s$ += " World" ' string concatenation
```
**Scope:** All main-code variables share one scope (even inside IF blocks).
`DEF FN` functions are fully isolated — only global constants (`#`) accessible inside.
**Comparison:** `"123" = 123` is TRUE (cross-type), but keep types consistent for speed.
### Built-in Constants
- **Boolean:** `TRUE`, `FALSE`
- **Math:** `PI#`, `HPI#` (π/2 = 90°), `QPI#` (π/4 = 45°), `TAU#` (2π = 360°), `EULER#` (e) — `#` suffix required
- **System:** `PRG_ROOT#` (program base directory path)
- **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_LSHIFT#`, `KEY_LCTRL#`, etc.
---
## Arrays
```basic
DIM scores$ ' Declare (required before use)
DIM a$, b$, c$ ' Multiple
scores$(0) = 95 ' Numeric index (0-based)
scores$("name") = "Alice" ' String key (associative)
matrix$(0, 1) = "A2" ' Multi-dimensional
```
| Function/Command | Description |
|-----------------|-------------|
| `LEN(arr$())` | Total element count (note empty parens) |
| `ROWCOUNT(arr$())` | Count of first-dimension rows — use this for FOR loops over multi-dim arrays |
| `HASKEY(arr$(key))` | 1 if exists, 0 if not |
| `DELKEY arr$(key)` | Remove one element |
| `DELARRAY arr$` | Remove entire array (can re-DIM after) |
| `JOIN dest$, src1$, src2$` | Merge two arrays; `src2$` keys overwrite `src1$`. Use empty `src1$` as `COPYARRAY`. |
**Always check with `HASKEY` before reading uninitialized elements.**
---
## 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 (GOTO/GOSUB only)
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 [main]
[sub:init]
LET x$ = 0
RETURN
' Dynamic jump (variable must contain "[label]" with brackets)
LET target$ = "[menu]"
GOTO target$
' Other
SLEEP 2000 ' Pause ms
END ' Terminate program
```
---
## I/O
| Command | Description |
|---------|-------------|
| `PRINT expr; expr` | `;` = no space, `,` = tab |
| `PRINT "text";` | Trailing `;` suppresses newline |
| `INPUT "prompt", var$` | Splits on whitespace/comma |
| `INPUT "prompt", a$, b$` | Multiple values |
| `LINE INPUT "prompt", var$` | Read entire line with spaces |
| `CLS` | Clear screen |
| `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 (0–15 palette) |
| `SHELL("cmd")` | Run shell command, returns output |
| `SHELL("cmd", ms)` | With timeout in ms (default 5000) |
**Escape sequences in strings:** `\"` `\n` `\t` `\\`
### 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 |
### Mouse (graphics mode only)
`MOUSEX`, `MOUSEY` — cursor position
`MOUSELEFT`, `MOUSERIGHT`, `MOUSEMIDDLE` — 1 if pressed, 0 otherwise
### Console Read
`GETCONSOLE(row, col, type)` — type: 0=char (ASCII), 1=fg color, 2=bg color
---
## User-Defined Functions
```basic
' Define BEFORE calling. Name must end with $.
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) ' ✓ OK — return value used
LET v$ = FN Clamp$(15, 0, 10) ' ✓ OK
FN Clamp$(5, 1, 10) ' ✗ ERROR — return value unused
```
- Isolated scope: no access to global variables, only global constants (`#`)
- Parameters passed **by value**
- Labels inside functions are local — GOTO/GOSUB cannot jump outside
- Supports recursion
- Arrays as parameters not allowed. Use ASJSON to make array as JSON-string to pass it.
- Use `INCLUDE` to load functions from separate files if many
---
## 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 by default |
| `INSTR(s$, search$, mode)` | mode: 0=case-insensitive, 1=case-sensitive |
| `INSTR(start, s$, search$)` | Search from position (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, returns count |
| `SRAND(n)` | Random alphanumeric string of length n |
| `STR(n)` | Number to string |
| `VAL(s$)` | String to number |
| `SHA256(s$)` | SHA256 hash (64-char hex) |
| `BASE64ENCODE(s$)` / `BASE64DECODE(s$)` | Base64 encode/decode |
---
## Math Functions
| Function | Description |
|----------|-------------|
| `ABS(n)` | Absolute value |
| `ATAN(n)` | Arc tangent |
| `BETWEEN(n, min, max)` | TRUE if min ≤ n ≤ max |
| `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)` | Remainder |
| `POW(base, exp)` | Power |
| `RND(n)` | Random integer 0 to n-1 |
| `ROUND(n)` | Standard rounding |
| `SGN(n)` | Sign: -1, 0, or 1 |
| `SQR(n)` | Square root |
**Math constants:** `PI#`, `HPI#` (PI/2), `QPI#` (PI/4), `TAU#` (PI*2), `EULER#`
---
## Graphics
```basic
SCREEN 12 ' 640×480 VGA (recommended)
SCREEN 0, 800, 600 ' Custom size
SCREEN 0, 1024, 768, "My Game" ' Custom size + title
FULLSCREEN TRUE ' Borderless fullscreen (graphics only)
FULLSCREEN FALSE ' Windowed
```
| Mode | Resolution |
|------|-----------|
| 1 | 320×200 |
| 2 | 640×350 |
| 7 | 320×200 |
| 9 | 640×350 |
| 12 | 640×480 ← recommended |
| 13 | 320×200 |
### 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 (FAST — use instead of CLS)
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 palette (COLOR command, 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 ' Buffer drawing (start frame)
SCREENLOCK OFF ' Present buffer (end frame)
VSYNC(TRUE) ' Enable VSync (default, ~60 FPS)
VSYNC(FALSE) ' Disable VSync (benchmarking)
CLS ' Clear screen (slow — prefer LINE BF)
```
### Shapes & Images
```basic
' Create shape
' LOADSHAPE and LOADIMAGE return a stable integer handle — never reassigned.
' SDL2 owns the resource; your code only ever holds this one reference. Use constants.
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 1-based
DIM sprites$
LOADSHEET sprites$, 128, 128, "sheet.png" ' tileW, tileH, file
MOVESHAPE sprites$(1), x, y ' sprites$(1) = first sprite
' Transform
MOVESHAPE RECT#, x, y ' Position by center point
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)
```
---
### Text Rendering (SDL2_ttf.dll required)
#### DRAWSTRING & LOADFONT
```basic
' Default font (Arial)
DRAWSTRING "Hello!", 100, 200, RGB(255, 255, 255)
' Load alternative font — becomes the new default
LOADFONT "comic.ttf", 24
DRAWSTRING "Hello!", 100, 200, RGB(255, 255, 255)
' Reset to Arial
LOADFONT
```
`DRAWSTRING x, y` positions the top-left of the text. Requires `SDL2_ttf.dll` in the same directory as the interpreter. Prefer this over PRINT, which makes graphic screen easily blinking.
---
## Sound
```basic
' LOADSOUND returns a stable integer handle — SDL2 manages the resource.
' The handle never changes; store it in a constant to protect it from accidental reassignment.
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
FileAppend "log.txt", entry$ ' Append
LET ok$ = FileExists("file.txt") ' 1=exists, 0=not
FileDelete "temp.dat" ' Delete file
```
**key=value parsing:** When `FileRead` assigns to a `DIM`'d array, lines `key=value` become `arr$("key")`. Lines starting with `#` are comments. Perfect for `.env` files.
```basic
DIM env$
LET env$ = FileRead(".env")
LET API_KEY# = env$("OPENAI_API_KEY")
```
**Paths:** Use `/` or `\\` — never single `\` (it's an escape char). Relative paths are from `PRG_ROOT#`.
**FileWrite with array** saves in key=value format (round-trips with FileRead).
---
## Network
```basic
LET res$ = HTTPGET("https://api.example.com/data")
LET res$ = HTTPPOST("https://api.example.com/submit", "{""key"":""val""}")
' With headers (optional last parameter)
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$)
```
---
## Arrays & JSON
Nested JSON maps to comma-separated keys: `data$("player,name")`, `data$("skills,0")`
```basic
' Array → JSON string
LET json$ = ASJSON(arr$)
' JSON string → array (returns element count)
DIM data$
LET count$ = ASARRAY(data$, json$)
' Load/save JSON files
LOADJSON arr$, "file.json"
SAVEJSON arr$, "file.json"
```
---
## Fast Trigonometry
~20× faster than `SIN(RAD(x))`, 1-degree precision. Uses ~5.6 KB memory.
```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
```
Use for raycasting, sprite rotation, particle systems, any high-freq trig.
---
## Command-Line Arguments
```basic
' bazzbasic.exe myprog.bas arg1 arg2
PRINT ARGCOUNT ' number of args (2 in this example)
PRINT ARGS(0) ' first arg → "arg1"
PRINT ARGS(1) ' second arg → "arg2"
```
`ARGCOUNT` and `ARGS(n)` are 0-based; ARGS 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.
---
## Passing Arrays to Functions
Arrays cannot be passed directly to `DEF FN` functions, but a clean workaround exists using JSON serialization. Convert the array to a JSON string with `ASJSON`, pass the string as a parameter, then deserialize inside the function with `ASARRAY`. This is the accepted pattern in BazzBasic v1.2+.
```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
```
**Notes:**
- The function receives a full independent copy — changes inside do not affect the original array
- Nested keys work normally: `arr$("address,city")` etc.
- Overhead is similar to copying an array manually; acceptable for most use cases
---
## Program Structure
```basic
' ---- 1. FUNCTIONS (or INCLUDE "functions.bas") ----
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, not inside loops) ----
' Performance: variables declared outside loops avoid repeated existence checks.
[inits]
LET SCREEN_W# = 640
LET SCREEN_H# = 480
LET MAX_SPEED# = 5
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]
SLEEP 16
WEND
SOUNDSTOPALL
END
' ---- 4. SUBROUTINES (or INCLUDE "subs.bas") ----
[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, RGB(0, 255, 0), 1
SCREENLOCK OFF
RETURN
```
**Key conventions:**
- Variables: `camelCase$` | Constants: `UPPER_SNAKE_CASE#` | Functions: `PascalCase$`
- Labels: `[gameLoop]` for jump targets, `[sub:name]` for subroutines
- Image/sound/shape IDs are stable integer handles — **always** store as constants: `LET MY_IMG# = LOADIMAGE("x.png")` — never use `$` variables for these
- Group many IDs → use arrays: `DIM sprites$` / `sprites$("player") = LOADIMAGE(...)` — but prefer named constants when count is small
---
## Performance Tips
- `LINE (0,0)-(W,H), 0, BF` to clear — much faster than `CLS`
- Always wrap draw code in `SCREENLOCK ON` / `SCREENLOCK OFF`
- Store `RGB()` results in constants/variables — don't call RGB in hot loops
- Declare all variables in `[inits]`, not inside loops or subroutines
- Use `FastTrig` for any loop calling trig hundreds of times per frame
- `SLEEP 16` in game loop → ~60 FPS
---
## IDE Features (v1.3)
### New File Template
When the IDE opens with no file (or a new file), this template is auto-inserted:
```basic
' BazzBasic version 1.3
' https://ekbass.github.io/BazzBasic/
```
### Beginner's Guide
- **IDE:** Menu → **Help** → **Beginner's Guide** — opens `https://github.com/EkBass/BazzBasic-Beginners-Guide/releases` in default browser
- **CLI:** `bazzbasic.exe -guide` or `bazzbasic.exe -help` — prints URL to terminal
### Check for Updates
- **IDE:** Menu → **Help** → **Check for updated...** — IDE reports if a newer version is available
- **CLI:** `bazzbasic.exe -checkupdate`
### Compile via IDE
- **Menu → Run → Compile as Exe** — compiles open file to standalone `.exe` (auto-saves first)
- **Menu → Run → Compile as Library (.bb)** — compiles open file as reusable `.bb` library (auto-saves first)