#!/usr/bin/env python3 """Build the tokenised BASIC application, native sprite and RISC OS ZIP. Python 3 standard library only. Run this script from any directory. The lexer deliberately supports this source's uppercase keywords and lowercase identifiers; it is not a general-purpose BBC BASIC tokeniser. """ from pathlib import Path import datetime import math import re import struct import zipfile ROOT = Path(__file__).resolve().parent APP = ROOT / '!PengBowl' # BBC BASIC V token bytes (BBC BASIC Reference Manual, Appendix B). # ELSE is contextual: 8B in a single-line IF, CC on its own line. TOKENS = { 'SQR':'b6','SGN':'b4','EXP':'a1','ATN':'99','GET$':'be','STOP':'fa','OTHERWISE':'7f','ABS':'94','ASC':'97','RND':'b3','OPENIN':'8e','CLOSE':'d9','READ':'f3','DATA':'dc','AND':'80','DIV':'81','EOR':'82','MOD':'83','OR':'84','ERROR':'85', 'STEP':'88','THEN':'8c','COS':'9b','ERL':'9e','ERR':'9f','FALSE':'a3', 'FN':'a4','INT':'a8','LEN':'a9','NOT':'ac','PI':'af','SIN':'b5', 'TO':'b8','TRUE':'b9','VAL':'bb','CHR$':'bd','LEFT$(':'c0', 'MID$(':'c1','RIGHT$(':'c2','STR$':'c3','CASE':'c88e', 'CIRCLE':'c88f','FILL':'c890','RECTANGLE':'c893','WHILE':'c895', 'QUIT':'c898','SYS':'c899','WHEN':'c9','OF':'ca','ENDCASE':'cb', 'ENDIF':'cd','ENDWHILE':'ce','DEF':'dd','DIM':'de','DRAW':'df', 'END':'e0','ENDPROC':'e1','FOR':'e3','IF':'e7','LOCAL':'ea', 'MOVE':'ec','NEXT':'ed','ON':'ee','VDU':'ef','PLOT':'f0', 'PRINT':'f1','PROC':'f2','REM':'f4','REPEAT':'f5','REPORT$':'f624', 'REPORT':'f6','RETURN':'f8','UNTIL':'fd','OFF':'87' } TOKENS = {k:bytes.fromhex(v) for k,v in TOKENS.items()} KEYWORDS = sorted(TOKENS, key=len, reverse=True) def tokenise_line(line): result = bytearray() i = 0 while i < len(line): if line[i] == '"': # Preserve quoted text, including doubled quote sequences. j = i + 1 while j < len(line): if line[j] == '"': if j+1 < len(line) and line[j+1] == '"': j += 2 continue j += 1 break j += 1 else: raise ValueError('Unterminated string: '+line) result.extend(line[i:j].encode('ascii')) i = j elif line[i] == '&': m = re.match(r'&[0-9A-Fa-f]+',line[i:]) if not m: raise ValueError('Bad hexadecimal literal: '+line) result.extend(m[0].encode('ascii')) i += len(m[0]) elif line.startswith('ELSE',i): result.append(0xcc if line.strip()=='ELSE' else 0x8b) i += 4 elif line[i].isupper(): for k in KEYWORDS: if line.startswith(k,i): result.extend(TOKENS[k]) i += len(k) if k in ('REM','DATA'): result.extend(line[i:].encode('ascii')) i = len(line) break else: raise ValueError('Unknown uppercase keyword: '+line[i:]) else: result.append(ord(line[i])) i += 1 return bytes(result) def build_basic(): out = bytearray() lines = (APP/'Source').read_text(encoding='ascii').splitlines() for number,line in enumerate(lines,1): tokenised = tokenise_line(line) length = 4+len(tokenised) if length > 255: raise ValueError(f'BASIC line {number*10} too long') out.extend(bytes((13, (number*10)>>8, (number*10)&255, length))) out.extend(tokenised) out.extend(b'\r\xff') (APP/'!RunImage').write_bytes(out) return len(lines) import array import random import sys import json def soundcode(): # ARM-state ARMv4-compatible, position independent, 32-bit return. # Context: start,end,position,fraction,loop,step at offsets 0..20. # SharedSound's helper routines handle mixing, volume and resampling. ops=[];labels={};fix=[];listing=[] def label(s): labels[s]=len(ops)*4; listing.append(s+':') def emit(op,s): ops.append(op);listing.append(' '+s) def branch(cond,target): fix.append((len(ops),target));emit((cond<<28)|0x0a000000,'B'+{14:'',3:'LO',0:'EQ',2:'HS'}[cond]+' '+target) emit(0xe92d5ff7,'STMFD sp!, {r0-r2,r4-r12,lr}') emit(0xe1a0c000,'MOV r12,r0') emit(0xe59c4008,'LDR r4,[r12,#8]') emit(0xe59c5004,'LDR r5,[r12,#4]') emit(0xe59c900c,'LDR r9,[r12,#12]') emit(0xe59c6014,'LDR r6,[r12,#20]') label('loop') emit(0xe1540005,'CMP r4,r5');branch(3,'data') emit(0xe59ca010,'LDR r10,[r12,#16]') emit(0xe35a0000,'CMP r10,#0');branch(0,'silence') emit(0xe59c4000,'LDR r4,[r12,#0]') emit(0xe3a09000,'MOV r9,#0') emit(0xe1540005,'CMP r4,r5');branch(2,'silence') label('data') emit(0xe1a0e00f,'MOV lr,pc') emit(0xe598f008,'LDR pc,[r8,#8]') emit(0xe1510002,'CMP r1,r2');branch(3,'loop');branch(14,'finish') label('silence') emit(0xe1a0e00f,'MOV lr,pc') emit(0xe598f004,'LDR pc,[r8,#4]') emit(0xe59c4004,'LDR r4,[r12,#4]') label('finish') emit(0xe58c4008,'STR r4,[r12,#8]') emit(0xe58c900c,'STR r9,[r12,#12]') emit(0xe1a03000,'MOV r3,r0') emit(0xe8bd9ff7,'LDMFD sp!, {r0-r2,r4-r12,pc}') for i,target in fix: ops[i]|=((labels[target]-(i*4+8))//4)&0xffffff (APP/'SoundCode').write_bytes(struct.pack('<'+'I'*len(ops),*ops)) (ROOT/'SoundARM').write_text('; SharedSound fill callback, assembled by Build\n'+'\n'.join(listing)+'\n') # Appended to Build by the development step; the delivered Build is standalone. class Canvas: def __init__(self,w,h):self.w=w;self.h=h;self.p=[[None]*w for _ in range(h)] def dot(self,x,y,c): if 0<=xy+.5)!=(b[1]>y+.5) and x+.5<(b[0]-a[0])*(y+.5-a[1])/(b[1]-a[1])+a[0]:inside=not inside j=i if inside:self.dot(x,y,c) def flip(self): o=Canvas(self.w,self.h);o.p=[row[::-1] for row in self.p];return o def sprite_bytes(name,c): stride=((c.w*4+31)//32)*4 image=bytearray(stride*c.h);mask=bytearray(stride*c.h) for y,row in enumerate(c.p): for x,col in enumerate(row): if col is not None: off=y*stride+x//2;shift=x%2*4 image[off]|=col<466:c.rect(x,y,x+2,y+1,3) return c def artwork(): items=[('arena',backdrop()),('penguin',penguin()),('tumbler',tumble()),('tumblel',tumble(True))] items += [(f'ball{n}',ball(n)) for n in range(4)] area(APP/'Sprites',items) icon=Canvas(34,34);p=penguin() for y in range(32): for x in range(22):icon.dot(x+2,y,p.p[min(47,y*48//32)][min(31,x*32//22)]) b=ball(0) for y in range(16): for x in range(16): v=b.p[y*2][x*2] if v is not None:icon.dot(x+18,y+18,v) area(APP/'!Sprites',[('!pengbowl',icon)]) return items def audio(): sr=11025;bank=bytearray();index=[] durations=[1.2,.18,.38,1.3,.85,.65,1.8,.07] for name,duration in zip(['Roll','Bowl','Hit','Strike','Spare','Gutter','Finish','Click'],durations): rng=random.Random(name);pcm=array.array('h');low=0 for i in range(int(sr*duration)): t=i/sr;white=rng.uniform(-1,1);low=.88*low+.12*white envelope=min(1,t/.012)*min(1,(duration-t)/.035) if name=='Roll': s=.12*low+.055*white*(.6+.4*math.sin(2*math.pi*10*t)) elif name=='Bowl':s=.28*white*math.exp(-t*17)+.13*math.sin(2*math.pi*(170*t-220*t*t))*math.exp(-t*15) elif name=='Hit': s=.24*white*math.exp(-t*24)+.16*math.sin(2*math.pi*(620*t-520*t*t))*math.exp(-t*7) for at in (.09,.17): if t>at:s+=.15*white*math.exp(-(t-at)*38) elif name=='Gutter':s=.17*math.sin(2*math.pi*(330*t-180*t*t)) elif name=='Click':s=.12*math.sin(2*math.pi*900*t)*math.exp(-t*45) else: notes={'Strike':[523.25,659.25,783.99,1046.50], 'Spare':[523.25,659.25,783.99], 'Finish':[523.25,659.25,783.99,659.25,1046.50]}[name] n=min(len(notes)-1,int(t/duration*len(notes)));f=notes[n] nt=t%(duration/len(notes));gate=min(1,nt/.01)*math.exp(-nt*2) s=(.14*math.sin(2*math.pi*f*t)+.035*math.sin(2*math.pi*2*f*t))*gate v=int(max(-.9,min(.9,s*envelope))*27000) pcm.extend((v,v)) if sys.byteorder!='little':pcm.byteswap() raw=pcm.tobytes();index.append((name,len(bank),len(raw)));bank.extend(raw) (APP/'Sounds').write_bytes(bank) (ROOT/'SoundIndex').write_text(json.dumps(index,indent=2)+'\n') return index def sources(items,index): tail=['REM Generated asset table.','DEF PROCassets','LOCAL i%,name$', 'DIM sprite%(7),spritew%(7),soundoff%(7),soundlen%(7)', 'FOR i%=0 TO 7',' READ name$,spritew%(i%)', ' SYS "OS_SpriteOp",&118,sprites%,name$ TO ,,sprite%(i%)','NEXT', 'FOR i%=0 TO 7',' READ soundoff%(i%),soundlen%(i%)','NEXT','ENDPROC',':'] tail += [f'DATA "{name}",{c.w}' for name,c in items] tail += [f'DATA {off},{size}' for name,off,size in index] (APP/'Source').write_text((ROOT/'Main').read_text()+'\n'+(ROOT/'Game').read_text()+'\n'+'\n'.join(tail)+'\n') def make_zip(): target=ROOT.parent/'PenguinBowl-riscos5.zip,a91' stamp=int((datetime.datetime.now(datetime.timezone.utc)-datetime.datetime(1900,1,1,tzinfo=datetime.timezone.utc)).total_seconds()*100) types={'OakLogo':0xff9,'!Run':0xfeb,'!Boot':0xfeb,'!RunImage':0xffb,'!Sprites':0xff9,'Sprites':0xff9,'Sounds':0xffd,'SoundCode':0xffd} with zipfile.ZipFile(target,'w',zipfile.ZIP_DEFLATED) as z: for p in sorted(ROOT.rglob('*')): if not p.is_file() or '__pycache__' in p.parts:continue zi=zipfile.ZipInfo(p.relative_to(ROOT).as_posix(),datetime.datetime.now().timetuple()[:6]) zi.create_system=13;zi.compress_type=zipfile.ZIP_DEFLATED load=0xfff00000|(types.get(p.name,0xfff)<<8)|((stamp>>32)&255) data=struct.pack('<4sIIII',b'ARC0',load,stamp&0xffffffff,0x33,0) zi.extra=struct.pack('