File size: 16,915 Bytes
221f1c7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 | # METADATA:
Name: BazzBasic
Description: BazzBasic BASIC interpreter language reference. Use when writing, debugging, or explaining BazzBasic code (.bas files). Triggers on BazzBasic syntax, BASIC programming with $ and # suffixes, SDL2 graphics in BASIC, or references to BazzBasic interpreter features
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.
Purpose: This guide has been provided with the idea that it would be easy and efficient for a modern AI to use this guide and through this either guide a new programmer to the secrets of BazzBasic or, if necessary, generate code himself.
Version: This guide is written for BazzBasic version 1.1d and is updated 26.03.2026 Finnish time.
# END METADATA
---
# BazzBasic Language Reference
**Version:** 1.1b (March 2026) | **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 | Pass individual elements by value |
| 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
```
**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)
- **System:** `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$())` | Element count (note empty parens) |
| `HASKEY(arr$(key))` | 1 if exists, 0 if not |
| `DELKEY arr$(key)` | Remove one element |
| `DELARRAY arr$` | Remove entire array (can re-DIM after) |
**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) |
| `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
- 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 |
| `INSTR(start, s$, search$)` | Search from position |
| `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
LET id$ = LOADSHAPE("RECTANGLE", w, h, color) ' or "CIRCLE", "TRIANGLE"
LET img$ = LOADIMAGE("player.png") ' PNG (alpha) or BMP
LET img$ = 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 id$, x, y ' Position by center point
ROTATESHAPE id$, angle ' Degrees (absolute)
SCALESHAPE id$, scale ' 1.0 = original size
DRAWSHAPE id$ ' Render to buffer
SHOWSHAPE id$ / HIDESHAPE id$ ' Toggle visibility
REMOVESHAPE id$ ' Free memory (always clean up)
```
---
## Sound
```basic
LET snd$ = LOADSOUND("jump.wav") ' Load (WAV recommended)
SOUNDONCE(snd$) ' Play once, non-blocking
SOUNDONCEWAIT(snd$) ' Play once, wait for finish
SOUNDREPEAT(snd$) ' Loop continuously
SOUNDSTOP(snd$) ' 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 `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.
---
## 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.
---
## Program Structure
```basic
' ---- 1. CONSTANTS (or INCLUDE "constants.bas") ----
LET SCREEN_W# = 640
LET SCREEN_H# = 480
LET MAX_SPEED# = 5
' ---- 2. 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
' ---- 3. INIT (declare ALL variables here, not inside loops) ----
' Performance: variables declared outside loops avoid repeated existence checks.
[inits]
SCREEN 0, SCREEN_W#, SCREEN_H#, "My Game"
LET x$ = 320
LET y$ = 240
LET running$ = TRUE
' ---- 4. MAIN LOOP ----
[main]
WHILE running$
IF INKEY = KEY_ESC# THEN running$ = FALSE
GOSUB [sub:update]
GOSUB [sub:draw]
SLEEP 16
WEND
SOUNDSTOPALL
END
' ---- 5. 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 IDs that never change → use constants: `LET MY_IMG# = LOADIMAGE("x.png")`
- Group many image/sound IDs → use arrays: `DIM sprites$` / `sprites$("player") = LOADIMAGE(...)`
---
## 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 |