Professional Documents
Culture Documents
Whatisweasel?
WhatisWeasel?
Weaselis,technically,asimulatedmicrocontroller.EachdevicewhichrunsWeasel,either ControllerorMiner,keepsaninstanceofWeaselEngine.Thisengineiscapableofrunning certainamountofinstructionswhenneeded,takescareofstack,memoryandbasicnetworking. WeaselwasdesignedforPowerCraft,whichmakesitreallyuniqueamongotherscripting enginesandinfactitisnotascriptingengine,itisavirtualmicrocomputer. Weaseliscompiled.Thatmeansthatifyouwritefor(i=1:10){bell()},itistranslatedtoa sequenceofIFs,LABELs,GOTOsandothersimplecommandsinfacttheWeaselassembler isverysimilartotheearliestversionsofBasic.Thisisnotacoincidence:Iveworkedalotwith Basicandevenusedrealassemblerinreal8bitmicrocomputers. ThatalsoexplainshowIgottheideatomakeWeasel,whereasothercodersusealready existinglanguages(eg.LuainComputerCraft)andspendlotsoftimemakingthemdowhatthey want.Incontrasttothis,Weaselwascodedexactlytodowhatweneed,anditmakesitso powerful.
Weaselgadgets
WeaselController themainchip.Eachofthesehasitsownnetwork.Rightclickitandgotosettingstoselect colourandnameforthisnetwork. eachnetworkcancontainonlyoneCore(this)andunlimitednumberofgadgets.
Rightclickweaselcorewithactivationcrystalthenetworkwillgetattachedtothecrystal. Rightclickwiththiscrystalonthegadgetstoconnectthemtoweasel.
Somethingaboutruntime
Functions l e e p ( t i c k s ) pausestheprogramexecutionforsometime.20ticks=1second. Statementp a u s e orp a u s e ( ) pausesitforonetick. Eachupdatetick400assemblerinstructionsareexecuted.Averageprogramhas30 instructions,soitismostlyneededforloopsandfunctioncalls.Ifyoucallpauseafteryoudo whatyouneededtodo,youcansavesomesystemtimeandreducelag. Makingaloop: w h i l e ( t r u e ) { d o s o m e t h i n g h e r e c h e c k p i n s , s e t d i s p l a y t e x t , c h e c k c h e s t s . . . p a u s e }
Functionupdate()
Weaselhas(butdoesnotneedtohave)afunctionupdate.Thisfunctioniscalledeachtime aredstonestatechangesonCore,oronsomeconnectedWirelessPort. ThisfunctionshouldratherbecalledINTERRUPTVECTOR. Thatmeansitisapieceofcodeexecutedafteraninterruptthepinchange. Themainprogramispausedforthetimethisfunctionisbeingexecuted(itcantakequitelong,if youusesleepinit),andthenthemainprogramisresumedwithabsolutelynodifferenceor problem,justlikeifthereneverwasanyinterrupt. f u n c t i o n u p d a t e ( ) { F = B L = R }
Variables
Weaselhastwokindsofvariables:globalandlocal. globalvariablesarevisibletofunctions,andifyoucallreset,theywillnotgeterased.Youcan thenusefunctionisset(varname)tocheckifthisvariablealreadyexists. Weaselallowsmakingboolean(true,false),integer(1,2,3...)andstringvariables(string). Unlikeotherlanguages,youdonotdeclarethem,butyoumustinitializethem. Strings h e l l o = " H e l l o " w e a s e l = " W e a s e l " t e r m i n a l . o u t ( h e l l o + " " + w e a s e l + " ! " ) Stringscanbeaddedwith+sign. Integers apples=30 peaches=13 lemons=1 fruits=apples+peaches+lemons or: fruits=sum(apples,peaches,lemons) Youcanusetheseoperatorswithintegers: sign + * / % meaning add subtract multiply divide modulo example 1+2+3 58 10*50 10/3 52%5 result 6 3 500 3.33333333333 2
power
3^2
NotethatwhileWeaselcantstorenonintegervalues(itroundsthem),insidecalculationsthese numbersareallrightandonlytheresultwillgetrounded. Booleans Boolean,akaflag,isavariablewhichcanhaveonlytwovalues:TRUEandFALSE. Youcanusetrueandfalseconstants,orsimply1and0,becausetheycanbeconvertedto boolean. Booleanoperators sign meaning &&or& AND ||or| OR
Youdonthavetowrite&&and||,single&or|workstoo. &&and||aremainlyforbooleans,becauseJEPmathparserdoesnotunderstandbinary operationssuchasxor,and,nor. These&&and||operatorsweremodifiedtoworkalsoforintegers,doingbitwiseoperations,but themathprioritiesarenotchanged.Ifyouwrite&or|,itwillgetconvertedto&&and||. Alwaysenclosebinaryoperationswith&or|intobracketstopreventproblemswiththese priorities.Eg. ( i n t v a r & 0 b 0 0 1 0 1 ) ! = 0 . Thereareafewadditionalfunctions. and(A,B),alsonot,or,xor,nor,nand,nor,nxor,xnor.theseworkbothforbinaryoperations, withbytes,andforbooleans.Theyhavevariableargumentcount,2ormore. Bitchecks even(bit,bit,bit...) odd(bit,bit,bit,bit...)checksifthebytemadeofthesebitshasodd/evenparity.Evenis0,2,4, oddis1,3,5. example: odd(1,1,1,0) true even(1,1,1,1) true
SYNTAX
Functions
Codestructures
Yousurelyknowthese,soskipthispartitisfornoobs. IFTHENELSEIFELSE i f ( a = = 1 ) { t e r m i n a l . o u t ( o n e ) } e l s e i f ( a = = 2 ) { t e r m i n a l . o u t ( t w o ) } e l s e i f ( a = = 3 ) { t e r m i n a l . o u t ( t h r e e ) } e l s e { t e r m i n a l . o u t ( I d o n t k n o w + a ) } IFTHEN i f ( F & & ! B ) b e l l ( )
LOOPS
Allloopscanusebreakandcontinuestatements,asdescribedlowerbutiamsureyouknow them. Notethanbreak2breakstwoloopsatonce. WHILE,UNTIL,DOWHILE,DOUNTIL Cycleswithcondition. UNTILcyclerunsuntiltheconditionreturnstrue WHILEcyclerunswhiletheconditionsreturnstrueandwhenitreturnsfalse,thecycleends. WhileandUntilareveryusefulforwaitingloops. # w a i t f o r l e v e r a t B t o b e p u s h e d u n t i l ( B ) { p a u s e } # w a i t f o r l e v e r a t B t o b e r e l e a s e d w h i l e ( B ) { p a u s e } d o { b e l l ( ) s l e e p ( 5 ) } u n t i l ( B ) d o { b e l l ( ) s l e e p ( 5 ) } w h i l e ( ! B ) u n t i l ( B ) { b e l l ( ) s l e e p ( 5 ) } w h i l e ( ! B ) { b e l l ( ) s l e e p ( 5 ) } Thedifferencebetweendo{}while()andwhile(){}isthatincaseofdowhile,thebodyoftheloop isexecutedatleastonetimebecausethecheckisattheend.
Specialcommands
restartsoftresettheprogramwillrestart,butnetworkdeviceswillnot. pausestopcurrentexecutioncycle,waitforstartofthenextone=somethinglikesleep(0) sleep(ticks)sleepticksticks breakbreakloop break2breaktwoloopsfornestedloops. thesamewithcontinue: continue continue2 returnendfuntion,returnnothing. returnvalueendfunction,returnvalue.
FunctionsprovidedbyWeaselController:
libCanDo("funcname") returnstrueifthereisanylibrarydiskprovidingthisfunction rebuild() recompiletheweaselprogram,addingorremovinglibrarydisksbasedoncurrent drivescontents.
Dynamicaccessors
Thisisaweaselspecificfeature,notcommonlyseeninscriptingengines. Youcanmakevariablenameorfunctionnamefromastring,dynamically. value=get(variableName) set(variableName,newValue) set(variableName,newValue,isGlobal) call(functionName,arguments,for,the,function,called,) Thiscanbeusedtoforexampleaccessportsinaledmatrixdisplay:namethenpx_ywherex andyarethecoordinates,andthensetvalue:set(p+x+_+y,true) Notethatsetcanbeusedalsotocreatevariableinthelocalnamespace(butnotglobal). Callcancallalsofunctionsongadgets.
Timefunctions
time()getMCtimeinMCseconds.Itisconvertedforyou,soadaytakes86400seconds,like realone. hours()MChours mins()MCminutes secs()MCseconds alsominutes(),seconds(). isDay(),isNight(),isRaining() Forrealtime: time_r(),hours_r()etc.
Mathfunctions
Therearemanyfunctions. byte(bit,bit,bit,bit...)makesbyteoranumberoutofgivenbits.itisrightaligned. bit(number,position)getsinglebit.positionisfromright,firstbitfromrightis0,then1etc. mean(num,num...)averagevalue min(num,num...)getminvalue max(num,num,...)getmaxvalue abs(num)absvalue bound(number,min,max)ifnumberisoutofrange,setittominormax. bound_c(number,min,max)ifnumberisoutofrange,cycleit eg.min0,max100,number=102>youget2number=5>youget95 color(r,g,b)makehexcolorofthree0255valuesforred,green,blue. color(name)makecolorforname,eg.red,navy,lime rgb(r,g,b)makecolorofrgb(0255) hsv(h,s,v)makeRGBnumberfromH,S,V0255. hhue,ssaturation,vvalue=brightness,also H=color S=0white,255color V=0verydark=blackcolor,255brightcolor rand,rnd,random(start,end)getrandomnumberfromstarttoend. random()random0.01.0
Stringfunctions
allofthemhavealiases,usewhichyoulikemore. Stringscanbeaddedtogetherwith+,otheroperatorswillcrashyourweasel. len,strlen(str)getlength strchar,charat(str,pos)getcharacteratposition,startsat0 zf,zerofill(number,length)makesstringofnumberandaddszerostomakeitaslongasyou want.
cf,cutfirst(string,length)returnsthetextwithoutfirstlengthcharacters. cl,cutlast(string,length)returnsthetextwithoutlastlengthcharacters. first,gf,getfirst(string,length)returnsthefirstlengthcharacters last,gl,getlast(string,length)returnsthelastlengthcharacters isnum(string)returnstrueforstringsthatcanbeconvertedtonumber(13) starts,startswith,startsWith(string,starts)checkifstringstartswithanotherstring ends,endswith,endsWith(string,ends)checkifstringendswithanotherstring matches(string,pattern) checkifstringmatchesaregexppattern. syntaxisthesameasinJava(guesswhy)) eg.matches(apple,app.*)returnstrue
Conversions
isnum(object)checkifvariablecanbeconvertedtonumber Tonumber: tonumber,toNumber,toNum,tonum,ton,toint,toInt,toi,atoi(object) Toboolean(true,false): toBoolean,toboolean,toBool,tobool,tob,atob(object) Tostring: toString,tostring,toStr,tostr,tos,atos(object)
I/Oports
Weaselhas6portssides,topandbottom. Usethemlikevariables:F,R,B,L,U,D,oralsoback,front,left,right,up,bottom,down,top ProgramforaNOTgate: f u n c t i o n u p d a t e ( ) { F = ! B }
Checkingchests
WeaselControllerhastheabilitytochecknearbychests. empty(side)returnstrueifthecheststgivensideisempty. sidecanbe:L,R,F,B,U,D.thesidesofthechip. full(side)checkifthereachestwillallslotsusedonside full(side,strict)setthestrictparametertotrueifyouwanttocheckcompletefullnessall slots64ormaxstacksize.
WeaselNET
Weaselscanaccesscommonglobalnetwork. NEWChangednames! nget(varname)getthevaluefromnet nset(varname,value)setthevaluetoaglobalvariable. nhas("varname")returnstrueifglobalnetworkhasgivenvariable Ifyoutrytogetavariablewhichdoesnotexistyet,yourweaselmaycrash
Radios
Weaselcanreceiveradiochannel:rx(channelname)returnsbooleanstate Itcanalsosetchannelstate:tx(channelname,state)stateisboolean. Donotforgettosetfalsetothechanneltoturnthesignaloff.Youcanputsomesleepthereto maketheneededpulse. Whenweaselrestarts,allitstransmittedchannelsareturnedoff.
***Accessinggadgets***
Ifyouconnectagadget,itsfunctionsandvariablesarevisibletoyourcode. Gadgetsareusuallyaccessedbytheirname: eg. s p e a k e r . o i n k ( ) m y P o r t . B = t r u e s c r e e n . a l i g n = R
s c r e e n . c o l o r = p i n k Eachgadgethasitsspecialfunctionsandvariables. Intheexamples,nameisthenameyousettothedevice.
PORT
Variables: name name=truesetallportsidesatonce myVar=portreadfrontside(theonewithmostpurplearrow) name.Ffrontside.AlsoL,R,B,U,Detc. name.reset()setalloutputstofalse name.on(F,L,D...)setsideson.Ifnosideisspecified,setsF name.off(F,L,D...)setsidesoff.Ifnosideisspecified,setsF name.toggle(F,L,D...)changeson/offstateofaside.Ifnosideisspecified,setsF name.empty(side) name.full(side) name.full(side,strict)justlikedescribedaboveforcorecheckingchests,sidebeingnameof thesideF,L,Detc.
DISPLAY
variables namethetext name.textthetext name.colorcoloroftext.useeitherhexformat(0xff00ff),orpurple.Manycoloursareallowed, settinginvalidcolourwillresultincrashsmokefromweaselanderrormessageinGUI. name.bgor name.bgcoloror name.backgroundthebackgroundcolor. name.alignalignment.1isleft,0iscenter,1isright.AlsoL,C,R. Youcanusesomeratherstrangeformattinginyourdisplayedstrings. ItisapartofMinecraftstextrenderer,andafaikitworksproperlyonlywithenglishfontrenderer. Theonewithuglylittlelettersfailssometimes. Thesethingsinsidedisplayedstringchangeformat.Theyworkbothwith[]and<>. <b>bold <i>italics <u>underline <red><green><pink><yellow><navy>etcchangecoloroftext <r>resetformat </anything>resetformat <random>makesstrangerandomflashingeffect,usedbythematrix()function Example: displayiscalledscr. leftalign,purpleonblack: s c r . a l i g n = " L " s c r . t e x t = " H e l l o M i n e c r a f t ! " s c r . c o l o r = " p u r p l e " s c r . b g c o l o r = " b l a c k " Nowsomeformatting. s c r = " < r e d > < b > B o l d r e d . "
SPEAKER
Speakerhasmanyfunctions. Thelastargumentofallfunctions,optionalone,isvolume. Volumeisbydefault10.30isforanoteblock,50ismaxallowed. name.moo() name.oink() name.baa() name.cluck() name.woof() makeanimalsound.theycanhaveoneparameter,thevolumeeg.moo(30) name.sound(stringresource) name.sound(stringresource,volume) playsrandomvariantofgivensound.Soundcanbesomethingfromresourcesfolder.eg. mob.creeper,mob.pigdeath,random.orb,step.stone,random.click. name.note(instrument,tone,volume) playinstrumentattone(024)andvolume.volumeisoptional,default30. instrument(aliases) bassdrum,drum,bd,stone snaredrum,snare,sd,sand
TERMINAL
name.getInput(),name.in()gettheoldestinput,removeitfromthebuffer name.print(string),name.out(string)printsomethingtoterminal.\nwillbeautoadded.
} e l s e { / / a l i a s f o r t e r m . o u t i s t e r m _ c a l l ( n a m e , I d o n ' t k n o w w h a t + t e x t + m e a n s . ) } }
TOUCHSCREENDISPLAY
Rightclicktoopentheinterfacingscreenfortouchandkeyboardinput. Sneakwhileclickingtoopenthenameeditgui. TShasanumericarrayusedtoshowtheimage,madeofRGBnumbers0xRRGGBB. Ifyouwanttousethetouchfeature,makethisfunctioninCORE: f u n c t i o n t o u c h E v e n t ( n a m e , e v e n t , x , y , b t n , k e y ) { } name nameofthetouchscreen event down,move,up,key(mousebutton,andkeyboard) x,y coordinatesonthescreen
btn key
mousebutton.0left,1right,othernumbersarepossibletooifyouhavemorebuttons. thelettertheplayertyped.Youcantcatchfunctionkeys.
Tosetcolortowholescreen: myDisplay=1 cleardisplay myDisplay=red fillwithred. Cleardisplay myDisplay.clear() Setpixelcolor name.set(x,y,color) or name(x,y,color) Getpixelcolor color=name.get(x,y) or color=name(x,y) Drawaline name.line(x1,y1,x2,y2,color)aliasname.draw.line Drawsometext name.line(x,y,Yourtext,color) xyislefttopcorner,andittakesonlyoneline.
NowwehavetheawesomeIMAGEfunctions. Thesewillnotwork,unlessyouhaveaDiskDriveconnectedtotheweasel, andanimagediskinit. Imagename=nameoftheimagediskyouwanttoread(eg.mydisk) Alternativelyyoucanusedrivename:myDrive.1getimagediskin1stslotofmyDrive. name.image(imgname,x,y) x,y=lefttopcorner name.image(imgname,x,y,startx,starty,width,height) thisallowsspritingknownfromcss. startxandstartyarecoordinatesintheimage,thelefttopcornerofthedrawnpart. widthandheightaredimensionsofthisdrawnpart.
Hereisasampleprogram:PAINTING. Connectatouchscreencalledts,openitsGUIanddraw. Presssomeletterstochangecolorandplaybellsound. //clearthescreen t s = 1 g l o b a l p e n = c o l o r ( " w h i t e " ) f u n c t i o n t o u c h E v e n t ( n a m e , e v e n t , x , y , b t n , k e y ) { i f ( e v e n t = = " d o w n " | | e v e n t = = " m o v e " ) { / / l e f t b u t t o n d r a w , r i g h t e r a s e i f ( b t n = = 0 ) t s ( x , y , p e n ) i f ( b t n = = 1 ) t s ( x , y , 1 ) } i f ( e v e n t = = " k e y " ) { # h e r e a s w i t c h s t r u c t u r e w o u l d b e h a n d y # b u t W e a s e l c a n t u s e i t
i f ( k e y = = " r " ) p e n = c o l o r ( " r e d " ) i f ( k e y = = " g " ) p e n = c o l o r ( " l i m e " ) i f ( k e y = = " b " ) p e n = c o l o r ( " b l u e " ) i f ( k e y = = " k " ) p e n = c o l o r ( " b l a c k " ) i f ( k e y = = " w " ) p e n = c o l o r ( " w h i t e " ) i f ( k e y = = " y " ) p e n = c o l o r ( " y e l l o w " ) i f ( k e y = = " o " ) p e n = c o l o r ( " o r a n g e " ) i f ( k e y = = " p " ) p e n = c o l o r ( " p i n k " ) i f ( k e y = = " v " ) p e n = c o l o r ( " p u r p l e " ) i f ( k e y = = " c " ) p e n = c o l o r ( " c y a n " ) b e l l ( ) } } f u n c t i o n u p d a t e ( ) { / / c l e a r i f t h e r e i s s i g n a l f r o m b a c k . i f ( b ) t s = 1 }
WEASELDISK
Yes,itsafloppy. Youget4blankdisksthisway,andyoucanuseDigitalWorkbenchtoformatthem. Thenputthemtoadriveandusebyweasel.
DIGITALWORKBENCHdiskeditor
Thisblockcanbeconnectedtoweasel,butithasnoeffect.itisusedtoedit,rename, formatandcolourweaseldisks.
Rightclicktoopengui. 1) Insertdiskstothecloneslotstocopydisktheseinthemiddlewithanarrow. Pressthisarrowtocopyleftdisktoright. 2) Insertdisktotheleftslot.Usebuttonsonrighttoformatit. Mouseoveryourdisktoseethatitsformatted. 3) Clickedittoeditthedisk. Allchangesareinstantlysavedtodisk.Takethediskofftheslot,anditwillstaythere. 4)TextandListeditingissimpleandobvious. 5)Imageediting. Clickintothecolorpickingareatoselectcolor. Pressfilltofillwholeimage,cleartosetittotransparentcolor. Useleftmousebuttontodrawinthearea,press+andbuttonstozoom. UserightmousebuttonasERASER. Imagescanbeupto260x130,buttheycauseabitoflag,pleaseusethesmallestsizeyou need.
WEASELDISKDRIVEreader/writer
map.myDiskdatadisk Inthefollowingexamples,replacenamewiththeidentifieryouwanttouse
Textdisk
nameistext.diskNameordrive.SLOT
Listdisk(Numbers/Strings)
nameislist.diskNameordrive.SLOT Variables: name.size name.lengthgetnumberofelements
Thisvariableisreadonly. Functions: name.get(index) indexisanumber0...length1 name.set(index,value) indexisanumber0length. ifyousetelementwithindex==length,thiselementwillbeappended. name.clear() eraseallelements name.add(value) appendanelement
Datadisk
nameismap.diskNameordrive.SLOT Datadiskcontainsamapofvariables,verysimilartotheoneusedtoholdglobalvariablesin weasel.Itisalsousedinsimilarway. name.has(varname) returnstrueifget(varname)willworkforthisname =ifthereissuchavariablestored name.get(varname) getvariablevalue.ThisdisksupportsINTEGER,STRING,BOOLEAN. name.set(varname,value) setvaluetoavariable.Thisdoesnotreallycareaboutdatatype. name.clear() removeallelements. name.remove(varname) or name.unset(varname) removesavariable example: map.MORSE_TABLE.get(f) ifyouhavef=...setinthedisk,youwillget...
Imagedisk
nameisimg.diskNameordrive.SLOT Imagescanbeeditedexactlythesamewayastouchscreen,seeabove. Additionalfunctions: name.resize(width,height) resizeimage,clearcontents. Thereisthesizelimit1x1260x130
Librarydisks
Youcannotaccesslibrarydisksfromprogram,buttheyarealllinkedautomatically. WorkinWeaselController(putthemintoadrive) WorkinMiner
Onlyfunctionsfromlibrarydisksareaccessible Functionsfromthelibrarydiskareliterallyaddedtothemainprogram,thoughnotthe sourcecode,butalreadycompiledonesthatiswhyyoumustpressCompileinthe editor. Iftherearemorefunctionsofthesamenameinyourprogram,itisnotaproblem. Disksareaddedlinebylinefromallconnecteddrivers,andtheirlabelshavenoeffect youcanprefixyourfunctionsasyouwishornotatall. Whenmakinguniversallibrarykeepinmindthatnamesoftheperipheralsmayvary useget("name")andset("name",value,andcall("name",args...)ifyouneed. Thisofcoursedoesnotapplytominers,minersareallequivalentandthelibrariesare 100%universal. Tipforusage: Ifyoumakeagameengineandwanttohaveeg.gamedisks,youcanmakemultipledisks,and oneachofthemcreateafunctionrunGame().Thenifyouswapthediskinadriveandrebuild theprogram,thefunctionfromthisgamediskwillbestarted.Ifyouinsertotherdiskwithother game,itwillstarttheotherversionofthisfunction. itisgoodtoaddprefixestofunctionnames,usuallyoneletterlongprefixissufficient. thisistopreventconflictwithotherlibrariesorthemainprogram.
NowyoucanstartreadingaboutMinerslinkatthetop