You are on page 1of 132
THE {HIM NextTech SERIES Smmegenc(e); Setar (Si) =rand(4) + 1; while () (Sse for (Si= ae petar_x(Si), “.”); } $screen>refresh; enn SM 9 Gem install rails -version-3.2.12 $ rbenv rehash $ rails Mem SE direct to Glask, notice: «..’ } format.json { head -no content J else hte i Sieeeeeedle entity) $ bundle exec tails generate migration add_pnonity (oleae Seems elidate duc at is in the past def due at is_in the past emOmeammm™ Seeeecom import randrange MAX STARS = ‘co soonest) eel Bar = [randrange(0, 629), randrange(0, 479), randrange(], 16) a Se 0) usr/bin/perl Snumstars = 100; use Time::HiRes ); use Curses ee fond(0), Ssiar_y(Si| = rand(24); $star s[Si] = rand(@) + a se ‘Sscreen-1eiresnas ee 22.0" $ gem install bundler § gem install rails 12$ thenvat cto (o @iask, notice: \v )OHtiat ison itaaaam Beetle, ciaibs: unprocessable en'\ty ) S bundle exec rails generate migtaGn—aatiaaaam RI pune exec fails server validate duc at isin — Fandom import rancrange Mis Sala a7 “<> 2130" cem install bundles goa See update atributes(params(:task)) format html { redirect_to @ tae a ———— PLE With the internet driving anew word of information exchange, business start-ups and online gaming, coders have suddenly become the gatekeepers to these new realms, Combine the huge interest in learning how to create and control these worlds wth the surge of cool devices, suchas the Raspberry Pad you've got head of technological steam the word hasn't Seen since the coding craze ofthe eatly 19805 So no mater fyou' looking torelive those heady’80s coding days or area newbie ooking to take your fist stops into the coding werd you holdin your hands theideal quideto Start coding. Thanks toa new generation of open fee software we allan access operating systems, development tools, compilers and the programming languages needed to create profesional programs, appsand tools. Wellshow you howto get up and running witha Linux system, then access everything you need frely online, Coding Is easy, exciting an fun ‘Well explain the basics, move onto more advanced topics explain how you ‘an use the Raspberry Pi and provide you wth fully updates exciting and £35 tofollow projects. So what are you walting for Get coding! 4 L FUTURE a c ODE ee ey \o} at ace ae eee codingmadesimple19 Contents Scratch Getting started with Scratch. Using variables in Scratch Learn about Loops. Using lists in Scratch. Build a game with Scratch. Scratch: Hack it Coding on Pi Welcome to Pi Coding in IDLE. Minecraft: Start hacking. Minecraft: Image walls. Sonic Pi: Make some noise! Ruby: Compose music. Sonic Pi hardware control. SEEKS Re BERRSRB Coding basics Get started with Linux Mint and Python. 8& 6 | Coding Made Simple Get started with IDEs. Python lists Functions & objects. Conditionals. Variables. Building proper programs. Recursion. 2 Sorting algorithms. Hidden secrets of numbers. Using loopsss is The magic of compilers. Common coding mistakes. Python ‘Types of Python data. More Python data types. Reliability by abstraction. Files and modules Neater code with modules. Storage and persistence. Data organisation BNSBRORBERER SBRERSa Coding projects Plot beautiful images. Functionality of find. Programming we in Python. MicroPython: Light glove. MicroPython: Robot wars... Python: Build an Enigma box... UPS: Power loss protection. Practical Python 3 modules. Tkinter: Build a money app... BREEESSee Coding Made Simple | 7 ee oe Sore game dieply. Se ae phon prreat = rand{60) E Ieee cere cstes st Scratch Learn the basics of coding with the visual programming language Getting started with Scratch..10 Using variables in Scratch 12 Learn about Loops..____14 Using lists in Scratch....16 Build a game with Scratch....18 Scratch: Hack it. 2D outing Made Simple | 9 Getting started with Scratch New to coding? Scratch is the ideal language to begin with, and in this guide we show you how to get started and learn some basic coding principles. >The Serateh Interface is designed for chien to just get going with their creations ‘The colour coded blocks and clear Intertace enable calren to focus fon bling thelr ‘eas. snow much easier to bull your own garmes and projects. Scratch was created by MIT in 2002 and iter rofeasedto the pubic 2005 Ithas since become the firs coding lnguage many children around the world learn nthe «Scratch was made popuia via Code Cubs, aftr school clubs for dren lea by volunteer inthe tech community t ‘soon enterethe school curneulum and chidran as young a6 ‘ixare taught how to construct simple sequences of code by sing metaphors such as making a sandwich or programing a simple robot toy know asa Bee Bot. This practical knowledge i then putinto practewusirg Scratch as ‘foundation Chidren Irn te basics of computer slence by bulting ther own gars, applications and animations sing this simple language made of blocs, Scratch uses a block interface to build sequences of code {or objects known as sprtes, that canbe controled in mary diferent ways using these blocks of code. These spies are sible upon a Stage" wher interactions withthe user happen. spite can be moved, rotated, made to change colour. oF resized. Spies are actors that we can tell tat to do onthe stage ad they doital using simp blocks of code, Cog with Scratch is really simple. Blocks are dragged ‘tom the palette are are placed into a large coding area on therightotthe screen. Thre are mary cifterent types ct blocks. Fr example there are hat Hock, commonly used for ‘events such as starting the programme or reacting to Inout L arrngto code canbe tough but thanks ta Soratchit suchas ake press. Hat blocks wll only accept blocks Underneath them as an event typical triggers a sequence of code, Other blocks are C blocks. used fr lope and conditional ests such a “fle blocks enable the coder to pacebiocks inside them. and these blocks wil un based Upon the type of Cock used So, ny cade contained na forever nap wil run forever, he any code na cantonal test lla the condition is true, Other ypes of loess Include the hexagonal Sensing blecks which are used o ve sites baie collion detection and respond to sensor inputs such as cameras and microphones ‘lol these give us the basic bulging blocks ot computer science, such as sequence, tration and selection ‘and we canbuild quite complex projects using them. Thanks to Scratch’ easy to use interface andthe ailty to deconstruct larger problems ito sal easy tormanage Portions we havea too prec or children who want just get on with making something fun. rather than explitly learn how ta code Inthis frst tutorial we shal get o gros with creating a sige project that enabes usta learn how to work with the ‘Scratch intertace ad understand how sere ofthe common blocks work to produce a project that greets the player based ‘on thelrname which can be used in future gamesto identity the payers ina mt payer game Sato begin open ave browser tohtp:/scratcn mit ects and click an Try i ut to besina new Scratch session 10 | Coding Made simple Building our project a Scripts 1 DLeaming the layout Scratch has three main cacons. Fst we se the tag, whichis thre ojo i coma te sour above a can Seo the default Ca sprite, Under te Stage we sea st of spies sichare the objects tha we can rogransme. Netto herewe an Seo cur paletes of blocks that makeup the language, Test canbe draagedt the re arey coding area. Building the code Our code isbared upon colored blocks that ar orzanisedinto a fra of sectors besad upon thar nce, To wrt a programe sor ooclhecorect lock ad rag tothe ge grey coor ae. MWecan than bulla sequance of code by attach the locks togeter-This sequence commony refered toss ansgorand isbeing taught tochtcrenas youre TT) Patty leg Para) ra} Cra ask (ESSE and wait B Building our first programme. Let's getusedto Scratchy cresting simple project that sks or cur nae and then reacts according to the name the person. Ou frst blocks oun inEvents ands caled When Green Flag Cicked “Tass aha block and ont allows blocks to attach underneath Our next Backs Conrland scaled forever, Thsis a block, otherwise know 28 2100p. inside the loop Ourforeveooprunste code contained win tun te end of {ime oroustop te prom Our net blocks in Sensaris Calesaak and watt Drag this nse he loop any the ester, Now;gfab ant bck fom Conv This tock checks Cerro. intis case th nar stored ia varaba cad arr wchisa blckinthe Sensing palette. B Conditionals Tocheck thatthe name ofthe person is known we need touse the =k fram Operators, This checks the name entered against a inawn name. Next wo go to the Looks palette an solect tho Say hello for 2 sees block and place inside the If condition We then use join trom Operators to greet the user by name. 1 More Conditions Teadd morenames to eur project we need to adé more conditions to test Here we use anf, £lee block from Control o check for another name. We use the Else condition to respond to any unknown names. (Once you have competed the code, cick on the Green fag. inthe top rightof the Stage, to launch the code. mt Coding Made Simple | 11 Using variables in Scratch Learning about variables and data storage is easy in Scratch, and it can help you build a simple number guessing game. > Comparing variables. one senerated by 8 ‘ser the other bya computer sa great way to demonstrate how they canbe used In games and thelrloie seth cure fcompite stay, dt trge Oo: conf tnte he pe Mage dol oC” DvD Gers atc rag doen jit nar dol sh esr the Gt Rate data strge rene slr tre a pesin trry tect ys nen cores coon cts pert prea erred ee ops sings tgs on fos Actegelectto wr can ar orton ruber with cancte et ry aera Cperton Sot vee cts connate wth thse real we en sk baer oust, ig arb thee cecal pce and Ftsrerumbors wih Gecrlpace Bitton to (arable yr eae npr erates redo Sorta a ype othe eobousin totic ean bce cso ov dt) Wether namethe boc, Tater ue eva) henanealte bc coters merwvned Ino oral we ut one ape ees tho vorables Paty we creator cd Rand Number ‘hissed osteo gererate tg between $n10.wottonae th ale toask ese ty deus tw urn Exchgusattordan ave anew whip lhe epee Treuangacoatoaltes we chectherte ne vorbis pater arte tears pen her tan te Rand Number ene rst ht tease 12 | Coding Made Simple BD tao a fy ooo ood > Seratch code can got tle complicate. but remember ‘that you can take your cde apart and examine each block \stoa high f ther answer flower than the Rand. Number then they ae tod tis teow. \arabes are a key silt eam in computer scence as ‘thay have fr reacing applications, We se variables all ‘around us timers, sores, layer names in video games, tener durations for dtl cameras and usernames when lowing Into websites, Variables can be used to replace hard valuesin projects. For example. athe than change the values of 10 oF ‘ore ines that repeat the same information we canjust eer toa variable that we change once and that change fs flected across a 10 (or more) ines of code. ‘Seratch nrocuces vaables using the Data palette and here wecan create varabes fr incvual sprites. For ‘example. nil scores fr each eam in ootbal game (Or we can create a variable for al pees such asa simple time fora game. We canter te contents of variable using tho set and change bios. Sets used to changoa value toa spec value such as going from to 9. Change is used to Inereate or decreate a variable bya numerical val, such a5 changing the vale ofa variable from to By subtracting | from he arabe Solets start our projec by opening http//seratchanit. ‘edu are clicking Try It Out to start anew Seratch window If you get anything wrong, ullthe code apart and try again Creating a number game D Starting the project Westart the code i When space key pressed block rom Events This wi tigger our code fo run Unger tis back ve ad say trom the Looks palette. Replace ello with te corect question, Net tre crete a variable inthe Bat pate caled Rand, Number and then drag the set Rand, Number leck and connect tothe bottom ofthe ast block B Random Number Generation (Our Rand, Number variable needs a random number generator ‘Thankfully Serateh has one of those in Operators. Drag pk random 1 fo 10 and placeitin the set Rand_Number biock and change the valuesto to 100, Next gto the Control palette and drag repeat 10 so that tconnects under our previous blocks. Change repeat 10 to ropeat 3. inside the loop. We nor need grab an askblok fom te Sensing palette and charge the questonto ack fora gues. Tis ilereste ape Gusts calc anaes tat esd Sonarg owned teElserom Gone and place insite repent loop Net ok the boc tom Operatorsand lc tin the hexagon shape Conditions for all Our fist contin to testis the answer given bythe user matches ‘our Rand. Number, itis correct then we move tothe oop inside, which sun if correct answers given. inthis caseit uses anather say block from Looks, total the user that they ve won, The next block stop all, trom Contra wil stop a ofthe code runing B More conditions We now need to ga back to Control and drag two M blocks and place them inside the elee concton. This wil ve us two more concions tolest We shall uso two new operators. one for ech condition The fist is >and the ather is < both from the operators palette We repeat the sare input test but check f the guess i higher or lower thon the Rand. Number. Final Steps For oui step wo aa say block to each if condition hich wilt the usr her guess stoi row. Wn the code comet press your spacebar and your Cade il now ran and Scratch tha cat ila youto guess number. Yu can also se the numer nthe toplett othe stgettarn sof goto Data and remove the tek next to Rand Number Coding Made Simple | 13 Learn about Loops Loops are a fundamental part of coding, and Scratch can show you how they work and why they are so important. >There are 20 ‘many blocks ‘of code in this tutorial tha even the tage has six secret sequences ‘of code that react to the player typing on the keyboard. programming. They enable ou projects to run autonomously, iterate anche the colton ofan object such as a variable. In ths tuloril we shall create our ‘own musical showcase using thee forms ofloops, and some secret heyoeard accompaniment rom the user usig the ‘Scratch coding language Our stage has aconcert backdrop ‘2nd vee instrument upon (Our fstinstuenent i acum which provides abeat fr our ‘music, Tsbeats controled using a forever loop. AS ts ‘ame empl, tise loop that wilrunits contents forever A {forever cop's primarily used to constant una sequence of blocks. suchas checking the value ofa sensor orto cri robot crwards Ths type of op isthe most bas yet {uncamental loop tolearn. I's use throughout industries to constantly repeat a sequence. For example a car production lines one giant forever oop: raw materia gon, they are processed ina sequence (consider ian algoritm),andthen atthe end anew ar comes out. The loop then repeats ise, producing more cas. Moving forward ths loop aso present ‘nanather programming language: Python. Python the top goes bythe name while true but works inthe samo ‘manner as forever. “There are other types ooops For example, ay we only ‘wanted four ears This where a iterative lo becomes Useful. These loops wil rate by running for a set ruber of times, before finaly ending, We use this typeof oop with our L” are one ofthe most basic pects ofigicn ‘Bass instrument to produce fur notes in rapid secession, Scratch calls this op a repeat loop anditcanbe exited so ‘that theleop only goes round certain numberof tines. tn Python thisloopis achived using afr lop. Cur last oop isknown as repeat until and this oop iterates in much the same way as repeat but itcan be used to check the status of an object suchas variable or ‘condition, Wie the conction Fal, the loop continues to repeat. But as soon asthe contin 5 Teue the op willed, \We ust to check the status of a variable called counter and vile the value of ths variable does nt equal the contents ofthe op willbe wxecuted, But one ofthe blocksinsce the loopadds Lt the vale ofthe counter variable, essentaly iterating the aap unt reaches This oop is also use \ahen we are working wth text, editing sprites Isa quick and casy way to add Interest to your project You can resize, recolour nd eat ary spite to it in with your project. he word full sts. In school we hada register . I Mien cry mori out ta we mere psn Atwork we use to do its to ensure we are wereng at peak oficieney. AL NASA thay use acheckst fo ensue that thelaunch goes sme. Lists are powertultoosin the hands ofacomputer -sclentst uth can we urderstanathem ana then introduce them nto cur cocirg projects without ther ‘becoming scary? Wel withthe Sorat coding largunge we cancreae ists and alter them at wil allwhile song their contents neal time. Tis wil help us gta better understanding of what ists 4, anc wy they canbe so important when we bul cur own programs and games, Alissa data storage too that can store multiple ters of data. Each data items given a postion nthe ik just he alien in a school register are sorted alphabetical by ther surname: This calles an index andeach tern ina ist can be refered toby ts index umber, starting at 220. Data ina st can be manfulated ina numberof ways Fist we can adits toast and typically we append those itoms tothe end of alist grawing te isteach time we 48 ‘another We can also insert or repacedatain particular ‘lace nthe ti by stating the index numer ‘So, we can adits to alist but we can alsa dite items ‘tomalist, ether invcualy or by dieting the entice contents of alsin one action Scratch nrouces ists na simple and easy-to understand manner, as we can ee the content ofthe list as ‘a raphicin the top let of the Stag, ting us see the data as 16 | Coding Made Simple Click here to read the list nent 7 oe A simple shopping lst is used to demonstrate the power ‘of lists and how they ean be harnessed to create data, tenors and eaves the ist Using Scratch to demonstrate lists a great primer for those ust starting with languages suchas Python. as they can see the ist and learn how to ‘manipulate ueng Scratch’ ccingbioeks anthen apy that knowledge witha more tradtiorl typed language For our tutorial we have created a simple shopping it that demonstrates how datas entered anddelted team alist (Our green button triggers question ote use:"What do we need?" This then savecas special variable caled answer which is then ade to our shopping ist. For bit of user feechack an fun we adda sound to cat thatthe button ha been pressed. Our blue buttons tie mare complex. It reacts toa use lick and creates avarisle calles We next ‘say to he user "So we need” before entering into repeat nti oop. This oop wil check the value oz azainst the lerath of shoppingist. Ores the value of zis areater than the length of shopping te loop wil ext. nse ofthe loop we Pay ‘sound to grad the attention ofthe user. Then we rad each Itemin the ist one by one Our lst stepintheloop sto itera, by adng to ou arabe so that ou loap erly iteratas a st umber of mes Curia button the red button, Thisieasimele sequence of cade that kicked off by liking the uton.We playa quick sound a= feedback to the user before deleting ll oftheitems inthe shopping. So ets begin our project open your web browser to tp: /scratehumitad and click on Ty t Out Writing our shopping list ne ee (lick here to read the lst Q~--—-« Ce meee) Te ned ask EERIE and wait Bren acme D Creating buttons \Weneed tee Buton fo cur projec. The green button canbe found asa spre ite Sore bar. Onceyou have ha uton ght Giccon the sprite and act Dupeate wice or each he dhpicates cick on Costumes and change their cour, We used Red Greenand Bue We lso created thre more spies that are simple tertbowes ten baton tncins Creating a list using the green button Our fst step sto crete ast Chk on Dataandthen Make a List. Calthe st Shopping Now wih the Gren button selected we need touse the when this sprite cickedcodebecirom Events, then use Play Sound irr Sounds and gheit sound o grab the user's tention Ad an ask block tom Sensing then se ating 0 Shopping from Data and replace thing with answer ory Sensing Ce oH say EERIE for @ secs cee eee Reading alist using the blue button We start wththen thi spite clicked om Everts Then we crete 2 vorablecaled us the DataSets Then wing. say blot ne {sic he ree Now vesnearepent ul block rem Conia. The condtonthat we waht testscorsructedvang> Tom Operators trathen checking tose the valu oi greater than felon cur shoppe ist Reading items in alist ith our bu Buton sllngihed we now wrt the code that its inode the repeat unt loop Ths code stars by plana s sound fom Sounds There um tay tom Locks org wittamet the Shoring lek tom Deta-Then we dag curs varable tthe space ‘ores daplayed Nort we ad change by otra te loop, {touts ofthe lop we add the step al sound playback ok DU eh aCe Eat Mca es delete @Y of shopping Deleting the list with the red button Deleting ists rather easy- Our redbutton's used to delete every itemina ist So we need when this sprite clicked from Events. We then play a sound trom Sounds t indicate thatthe button Is activated. Then we use delete al of shopping frm Data to remove ‘very tem rom our shopping ist com ac ne aD----— , (lick here to read the ist OY carr rere etn at Testing our list Wit our ist eomplated we now need to cick onthe green button to Zitams to or shopping at Be enables Toren he stand Ted dltes that toto we canst the contonts othe istin the tpl ofthe screen. Ths can be tumedon and off by srg te {Wk nxt shopping ackin the Dstt Coding Made Simple | 17 Build a game with Scratch We now combine what we've learnt in the previous tutorials and use Scratch to create a game that encompasses lots of computer science. Wares oming 8 insratn econ ‘ape cote doaserecsy roetagon ‘hema sretne ‘te ican ‘sey eocone ‘teosteonet aking gaesis something that Scratch exces at and we can karts about computer science rom eating one. inthis project we shalleam howto bla sc shooting game controled by the mouse. Our goal Isto seorelets of pants to defeat eel alens. While we bull the game we shalrevist the sls leamt over the rious tutorials We tart the projet by vst tp: /erateh ited incur web beer and cicking on Ty Out toload the Seratch ecto Coding our spaceship Cur pret bess by ackinga few nen spits, Youcan easly erty he New Ste ans tbo ne asa torn Chnartrstunoredn the Stage ME seo Spacer spite wich canbe unde Ste Ub unde be theme Spe Natray open foes pee i noaatorltecur scone) deroscocen To tonto the spteboencreate Sage Olek out Soucshpspte nd youvisee an" inte tpt ehe Spite Ckkents Tana ist teptns appears Me neestocrunge the dere he spocrsp so et aces TBdcegres hen cone clone ue aron conto ‘ete Spt or We now read torpor re rere Sts tye betters Button pea he pr proces bse sss and thnclekon Spas © rare that ware godess thou Soman srt soecte we can row tart tir nce at cnt ste Our Wt tsk sto Crater cae eae ese ara cick te Data at cls are ara Name re ora scoread cick Ok No Crag change sort orn te Catupdte ono rececrgore Now globes ander when ren lg ccd oripoceon pe! sat creo Sononyeur ees shou nk eta Wen Geen bg Cid Stwoewo oro tale pow sequnc of code bute st wegen he Spacstip Ths snc rerctonte the SSucestpbengicteg meter wes ne ae See at Vest then ts specie whchcne fre the rs pte Ne et wee 9 gt eee wren coe tat wit net tnt hppa Goo Catoa cio te change sare yen heck atach [underreathwhen th spite ed Vie redtudate 18 | Coding Made simple the value of change seore by 1so that it changes the value tyy10-Ou net bck scaled switch costume to. Acostume ‘con change the appearance ofa spi, tcan be used for animation, such 25a simple walking animation, cr itcan be Uusedto altera spite after an event has happened. nour project we shal use a diferent costume frou spaceship to represent an explosion. Click on the Costumes tabi the top ‘centre ofthe seroen, Next ck on the*Choose costume rom lorry and seoct the Holiday theme toreduce the number ‘of options Now ook forthe star sprit, select and cick Ok to close the library. The screen willnow shown ecto anda Ito thre castumesin the contre of the seren, We erty need costumes for spaceship-a and tara so ight-c on ‘theremaining costume and select delete to remove. Once ‘complete cckon Serpts to return tothe coding area. Now’ ‘ur code we need to elit seh costume to so that t suitches to star We then usea walt 1 sees bok rom Contra ta show the costume change, before weuse another ‘itch costume to anc revert back to spaceship So our code for this sequence should locks sfllows: ‘When this spate ike Change score by 10 Sate costume to sara ‘Wait seca Switch costume to spaceshi-a ‘Ou last section of code fo this spitehanckes the basic ‘movement of ou spaceship It tides across te screen at varius speeds and random coordinates, tii colldes > Our stage has tree blocks of code that handle ‘background music and control a timer for our game. with anater sprite this case a robot reduces insizo, ‘making itharder tot This section of codehas an urusual trgger. In ths sequence we use broadeast whichis ameans ingto mutipe sprites using one message Co tothe Events palette nd clek onthe dropdown ato forte ‘when | receive block and select Now Message. Cllthe new ‘message start and than cick Ok We now havea biog that reads When receive start crag this block tothe coding area to start ou thrd an final section of code, The net block that we need is ewiteh costume to from Looks, and we nee to change the costume using the cropdown option so tat t shows spaceship-a Drag this book sothat it connects tuncerneath our when receive block Ns raw dag a forever block rom Control and place it undemeath the other blocks. ur next blocks cle If and we can fnitinsie the Control palette Place his block inside the forever lop. ‘Wenaw havea sequence that once tggered by the broadeast wl check to see ia coeltion has been met. whats the concn? For this we goto Sensing ane rag ‘touching. and place itinsde the hexagon shaped space fn cour block For this ew block we need tochange the ropoun so that says touching robot. sce the st action, whichis what wi happen ithe spaceships touching the robot, we crag the set sla to_9% Block for Locks. (Change the value so that shrinks te spaceship to 10% of ltsnocmal size We now mow tothe Else partion ofthe condtionaltest Here we use a glide 1 sees to x._yz_biock from Moti, butrather than have fd vals forthe ay coorcnates, we use to plek random Docks trom Operators Drag these nto the spaces for our lide block ancenter the values x:-240 to 260 y: 180 to 180. This wilcover evry poston on the stage Now we adour last lok for his sequence ard far this spite. Ourlst blocks another sat size toe rom Looks busts te set itt 35%. Soria ow our til anlfinal sequence of code for the spaceship spite looks ike tis: ‘When [receive start ‘Sitch costume to spaceship Forever ‘touching obot 7 then Set sine to 10% Else Chie 1 sec ox: pik random 240 to 20 pik random-180 to 180 Set ize 035% Coding our robot Eater weienported a robot sprite into our gare and now the time has cometo give our rbot itligenco! Inthe Sprites bax, ersure that your robot sprite is selected Seratchhas come along way and now ttfers 2 rmetredtor“Sratchers (that's Scratch coders) nine The sence i feof charge are enabes teers acces thee work fam any compute asi ral handy fr schol where crn canbe set homework using Seratch which s then autosavedas the eid wes Soro more the dog ate my home” situations Byposting our workenne tothe erate ‘Seuelanlcontrnare yur projet But once the te ienht youcan lash you the wert by making them pub: Sorow players arcund the word can sare your game. fa they can aso se the code that makes your game ands isthe exctingbit Have you et ‘ward tomate your conversion oF “Ths sprite has two sections of code: one to react to being hota. andthe ther to cntrel where ana how the robot ‘moves, So let’ start wth the eaction code ‘Gur robet spite has a simiar when the sprite clicked sequence that reacts to being cicked (shot aby the player Son order to have this unctionaty forthe robot we need to recreate the blocks Butourseore bck wil ory change the value of our score variate ty 5 points, 2s our robot wllbe easier tft We also use costume star’-ato signify that the robot has boon destroyed. The et ofthe code fortis sequence matches our spaceship. Here's the code in ful ‘When this spt clicked Change score by 5 Sach costume to sara Wit secs Sitch costume to robot ‘Our secend andlast section of code forthe rabot canals its movement. This i essentially the same code as hat used on the spaceshi, bu there sno conditional test to check't ‘therobot has touched ary sprites. So we star the sequence by using when receive start from Events before we then Use the switch costume to block frm Looks, Weneed 0 ensure tat the costume change reverts the robot orebot (ur next block introduces forever loop under the other blocks inthe sequence, Inside ths lop we reuse the glide block that we used to animate the spaceship prevoush, This ince our random coordinate system to enable the robot to pide torandom point round the tage heepr your work Utimate we gare ‘Our Space War game sees us do battle vith evi space ‘len robots and ‘hee infernal spaceships inside 23 time tunnel (ross Road or Pac Man? Wal low Incorporate tint your ow prot. Ths ret tare means that we cana emi 2nd republish gare ad poets wih now and ‘Sonn you and your fiends can make cool Coding Made Simple | 19 rere ons ee > Our spaceship Her sth complet code for this sequence: hastotsofcode, hen eave tart cumbaotree SHAS RO sequences - (lide 2 ees toa pik andem 240 2409 pike ‘movement and "don-16010 180 reaction to hitting our robot, Tera Sprite another resets Our thd spies caled Tera anditis character unique to your score, tive Scratch nour game Tra provides the scare once the gare final reactsto has completed. Tera wih when we start the game, ard being fred upont ren iat torecsive a roadeast fic il rege” Tera to appear and reprt the score So Tera has two sequences of ‘code that we need to wie. Our fests tide Tera. Wie start by using when green flag licked from Events We then comect hide rom Looks to complete this sequence of code Here that code When green flag ccked Hide (ur second sequence of code for Tea sto stow the scoreboard once the game has ended. Fr ths we willneedto create another roadeast us willbe triage tthe enc che game So nthe Events lok or the when Ireceive block Cick onthe drepsown for this lock and select New Message to crete anew broadcast and cal it scoreboard ‘We can now cag when I receive scoreboard onto the ‘coding rea, Underneath this block we need toad show ‘ror Looks 2s Terais curently hidden, We now needto ‘enable Tera to communicate the score, for his we shal ‘use asay — for 2 ees beck from Looks Drag thisunder the ‘previous Baek Now to announce the score we needa ina Sprites, backgrounds and other inputs short piece of text to the variable score, ane this wil vous ‘mare refined way of presenting te score. So we need to use {in hello word rom Operators and place tins he tet of the say block. Change the st section of text so that treads “Your score was”. For the seccnd space wewil goto the Data palette and select the sere block and plac tint the space (ur last block for ths sequence and sprit isto goto Sounds ‘and use a play sound until done Remember tht we Canimport sounds using the Sounds ta inthe top centre of the screen, Choose an appropriate sound to play alter your scores read We chose to play an applause sound. Here's the complete code fortis Sequence. ‘When Ineceiveacreboard| Show ‘Say Join (Your score was) (sor) for 2 secs Play sound clapping unl done ‘Start Button (ur fra sprites the simplest ofall Our start buon is used totrieger the game so atthe star ofthe games isle, only disappearing once the user clk upenit ‘This spite has two sequences of code. The sts a simple reveal nce we start Seratch, To tage this code into action wersed to use when green flag clicked from Everts. Drag, this into the cocing area Next got Looks and dag.a show ‘code block ta connect to our previous cade block. Thisis the «end of ths sequence of code, which should lookke this when you've finshed editing ‘when green lag clicked Show ‘The fina sequence of cade fr this sprite is a trigger to hide the sorte when clicked, and to start he gameusing a broadcast. Soe use the when this spite elicked code block rom Events to igger the sequence and then we attach ade code Bock from the Looks menu, Fo our last block o code inthis section goto Evens ana crag > Ourrobot has the same basic code as our spaceship, but ‘doesnot react when crashing into our spaceship. Amar stop forward for Scratch 2 tho test version ofthe Seratch programming language) the aby odesgn andes vector graphics \ectors der rom imap s they are easly resized witout ary ppnlatonerdstrten Wears 89 ook sharper and motrin pels Soby using Scratch? we cannowedt and cea sre based on ‘ecto We can also load images rom ou computer and et he Ug Serateh Naw we ean add etom mages a= ste on backgrounds or our gemes ut Scratch set just about spite and backreunds Using ou microphones we can aso receriaur gu custom ai ae st hem 20 | Coding Made Simple sing the btn aus esti sito. Scratch 2can now work wth microphones a record aude, andas tase np device. er example Shout can tigsera spite torus your computer has a webeary ‘hen scan aoe used wh Sezateh 2 asa base rmotinput ean be programmed ta tigger a srt to dance or youand a Wenees ay ‘ral enn fotbalor hockey using your bodes! The blocks er workng with he mcrorhone and webcam can be found inthe Sersrgpalete and requre thatthe user enables access tothe ‘Sevces in rd for hem to worn school these featres ae Spc sable for safety. but they are qute ste for homes. encore: ee play sound copoing foe > Our Tar sprite ats as a scoreboard announcer. Ithides ‘nti the end of game and then jumps out to read our score broadcast start and place it under the previous block of code, you cana se broadeast start remember that you canuse the dropdown osslect i as we coated this broadcast right atthe start with our spaceship spite Heres the cod for ths sequence When this spi is cise Hide [Broadesst start Coding the stage (final section of code woh creating code that wilrunin the background conto timer that wl eauntsown in our tame. We iso respond to the start broadcast by laying ‘music ina loopas the game plays. So change our focus on the Stage by ckvrgon te Stage con tothe le of ou sprites and then we can str to create our fst of tree sequences of code, Our first sequence ses a countdown timer to 30 seconds ts tregered when the reen a is ced, ogo ahead and tl that back rom Events, Now we need todo goto Data ae create anew var called countdown. Drag st countdown to © unc the previous bck. Change the value O to 30 for eur 30 secon counown.Now we needto gto Control and use a forever loop Place this under the previous blocks, Now we shall add play sound until done bork rom Scuncs We used 3 oop that wi pla inthe background while the game's played. Feel ee touse ary msc for your ae. This sequence snow complete hers the code for reference When geo ag td Secunia 020 Rewer C Play sound ipo ut dene setae Osrsecondsequerce leode Stegeedby our strt een trondent stops payoackot other aco lope andthen ordi tors pljbackot anate musiloop reise freer op, Wai Sou tetUecswten cae tart whichcanbe tnd Sani ‘nthe fers plete Under ake ad tap a seem founds om the Sounds pale Wetimnepeathe ower Parton leopptyscundsequence tat we crated the prevous soir ‘sequence. For this second sequence, your cade should look —— (ike this: ae cesarean ‘When Ls tar ache Sup allnunde Soaen Forever a: lay sound dance ny tl dene Our tl oequnceot ede a spl coutown eer that ves nteratveloap change the vai of ou courts arable Levy coed, nce aoe has tne rund 30 ves thn roca a mesg bore Soppig te eave rfl ors sequence an esa tat tromthe Evers ate Net we ad teloop anduse a ‘epaat 0 rom Corl ardrerenber to conge he 1010 3Dtoeneie covet tring ne teloop ve we change countdown by rom Daa But weneedto change tee Cfto-Lothat toes amt ae oe court ‘ore eng ts va with every oop. We ned add rat Laas from Corl tur lop others the op i Complete far oo acy Now csi of he oop wea boadeatt scorboantand wa wich stunt nthe Conoiplte Mes tlocl rats! the mesg that vate our cerca srt, Tora pop upat tend tithe gare One fs hapoens we se sop lho Gonta tostopa seqienes feos ar sop tego ‘When eee sa Rept 30 Change cousidown by Watt men > Rota ‘Broadcast soreboard and wait Lpaclses — by altering thelr ‘Weatoctargndthetackraindinthesameranner stein tha ‘note chrgeathe costumes aoe cores, Cano secred Wh our codeconplted nots neo dens Sistema rumniyromtwealersandtherrtotesokersim@ foreach spe Sprites = @, Stage } 3 backdrops INew backdrop: heal / sa oo New sprite: Sad / _ x:-14 y: 140 — directior 1 rotation style: () -> @ can drag in player: I ow: BM Coding Made Simple | 21 Scratch: Hack it We seek to capture the Space Dragon, but first we need to build and code a rocket using the visual programming tool, Scratch. eptember 2015 saw the release of Raspbian Jesse, and wthit the Raspberry P Foundation eased its oun version of Seratch. In this projct we'llear mare about Scratch and seit to hack together a space game which we wil control using our very own contr Fortis project youl nee any modelof Pte test Raspian three mementary swsches, Male to Female per ables, thee 220-ohm resistors, breadboard and three LEDS Weil stat by bung our controll. We'll connect our buttons tothe breadboard andthen use thejumper cables to attach one comer ofthe button toa GPIO pi, and anther ‘omer to. Ground (GND) pn. Similarly, we connect our LED's anode the longer leg afan LED, 0 GPIO pin and connect the shorter leg, the cathode to GND via a220-com resistor For a detaled agra see tt://bltly/LXF207- Serate-Diagram. The preferred layout ofthe GPIO pins Broadcorn (ee http://pinout.xy2 For the GPO pis we se forthe buttons. please see the able on tis page right) Lat’ power up ou and start buleing our game Raspbin wl automatically log you into the desktop. Navigate tothe main menu and open Scratch n the Programing ‘menu. Scratch te ef-hand column contains a palette of bocks, separated nto groups cording othe function, ‘Te blocks can be draeged into the centre column, which is where we bul our code Inthe tina columns te Stage, where al the output for ou gare wi take place. tthe bottom right yu can see all the sprites used in the game, Total's make the Stage lok more spacey. Click the ‘Stage'icon. atthe bottom ght ofthe screen. This changes the focus of any code tothe Stagen the centre column find the tab labelled Backgrounds: Cick this. then Import arew Extension activities (ur game's good but what wil make it seats seorng anda ime mt Fsty ur scoreis variable, Select the Rocket pris cick onthe Varabe pete ae ‘choose Wake ane variable allt coreandet tora epites Weluse a ‘When receive stat Grondast to tran the scoring ystrn tif. Every ound inthe Vriabe palette Nom ada Forever lop frm the Contral paste ard ten usetiresit Statements stckad ontop of ach other inthe bop. The est if cenatonl uses the'toucig spite block in Sensing to _ranco cur score by 10 ports te touen ne Space Dragon beore wating forlsecand Weve the change score aftr 30 seconds 22 | Coding Made Simple by block to do this. Theta wo sStotamante work nthe same ay but deal wits touching the obstacles. and points re euctedusne mrusviies (Our timers Inkedto te Stage 50 change aus to tes. Again wel usa a ‘When rece start Bradeast to trigger the ier Create anew variable time he game stars we set he score to cals ter andusngthe'set_t00 oc, set the ter to 30 Now se a repeat 10'lop fom the Cotl pat butenange he 10t0 30 Next use ‘Change by tochange the ter by everytime the loop erates. To conta the speed puta Wit secon from the Contolpaeteinplace Outside fhe loop. we pice’Stop Alt stop the ame store anything wth handy names. Sener Gamestart [GPO2 | Red GROW? Lett cpio —_|vetow | croz7 Rit cpi02s _[areen | eroze backgrounel We chose Stars foun in the Nature folder Now clickon te ca sorte, and change is rama the top of the screen to something appropriate ike Rockat (ck on‘Costumes and yu wl soe tha this spit has two, used for animation To change our cat into something ‘more space related, wecan pant anew costume We used a “mal ocket. hic included inthe cece downland fortis project. Cick'OK tolead the new costume, al then select that costume as the default by cicking ont Keeping your focus onthe Rocket soit cick'Scrits Welinov creat ou fst script forthe Rocket. From the Contra palette crag lek on Green Flag to the coding 0, {so trom the Contre palate crag the Broadcast bck to the cong area and aftacht to the Green Fag lec. Inthe Broadeast block cick onthe crop-dow select New Eat and type gploserveron This wil star the Scratch GPIO server when our game starts, enabling acess tothe GPIO in Seraten, Now we need to configure our buttons as inputs. Ada another Broadeast, nd ints op-cown select New Ect andype configain to set GPIO2 as an input Add two more Broadeasts and renea using configl4in ard eonfig23in respectively for GPIO pins 14 and23, cure andright buttons. Te ensure thatthe pins are confguredcckon the ‘Green Flag ust above the Stage Newt rab another Green Flag block from the Control palette. and ad a Walt Unt block tot Inside the bank for ‘the Wait Untibcck place _ = _ block rom the Operators palette. Now move to Sensing palette and look for Slider ‘Sensor valve. Cick the crop-doun and changeit to gp? “Tothelet youl se a tetas tick it and the sensor value {fo GPIO2 sprinted tthe top let ofthe Stage. Currently the sensor i reading1 or high Press the button arlthe sensor vale changes to 0 or low Test complete, uric the Sensor Value tickbox Now that we know it works, dag the pio sensor value block tothe frst barkinthe_= _bleck then ‘ype 0 (zero) nthe remaining box. Our last Block for this section's another Broadeastcaled Start Interaction with sprites Now let's ereate more sprites for our game. Draw a planet by cichrg the’New Sprt'icon. The planets no code attached it Now we'll orate two sprites to act as ebstates {or our ship to avo. Add anew spite ty cicking the Add ‘Spite icon = the mid tcon nthe ow baw the Stage Welt ‘choose robot. but atts default size ita itelarge, so right cick on the spite ane choose Resize! Ester we crested Broadcast callec Start, and inthe Control palette we can see that block now ests. Drag when | recelve stat tothe cong re, folowed by 2 Forever oop. Inthe Motion palette drag Turn clockwise 15 degrees ond ‘Move 10 steps. lace bot o these blocks inside the oop. (ur last section of code forthe robot starts withanather when I receive start bcck, Under that we ald 2 Forever loop. 2nd inside the lop we add an statement. This willcnstanty check to se i we are touching the Rocket spite the touching block isthe tp blockin the ‘Sensing palette. Ithisis Tue, then ou game will playa sound ‘fect, found inthe Sound palette, then say"Ouch’ for 5 seconds. The Say blocks found inthe Looks pate you want to add more obstacles right-click on the abot sprite ‘and cupicate untl youhave the requred number (Our net sprit fs an enemy to hunt. 2 Space Dragon, ‘choose anew spite and then drag a when I receive start Broadcast rom the Command palette, and also grab a Forever lop, Drag the Space Dragon to apart cl the sree. Goto the Motion palette arc ock for Glide 1 Sees to xy ‘This willbe pre-populated with coordinates, but they be ‘wrong Tofixths, change te another plete and then back to Motion. and itll update. Drath lide bockto the loon Repeat this action four or more times to create apattem for ‘ur enemy to fellow Remember tat e hada sound ploy ‘hen anobstacle shit. Wel, the same can happen wth our ‘Space Drago: ust add the same code from aur Robot srt Return tothe Rocka sprite ae createarother section of code that starts When I receive star, usin 2 Forever nc Now tum on our LEDs by using a Broadeasttoturn apn on andoff for sample gpiot7an and gpiot of Our LEDs ‘son 17,27 and 22,20 construct aight sequence, remembering to use Walt blocks to cot! the LEDS’ speed “To creste convo forthe rocket dag another When receive start bck into the codingarea. long vith a Forever loop and to if statements. Both statements wil be inside the loop, ontop of each other Grab two _=__blocks om the Operators pete and place ane in each statement Next grab a gplol4 sensor value rom Sensing an place it inthefirst blank of _=_and type inthe other. Repeat for the second If statement but charge apiol4 to epi023, “finish our Rocket code, cd one more When I receive start block Us ‘Goto y"to set a starting poston forthe rocket, ay the bottom ef ofthe seen (0, y0)-Net. we se aForeverloop to play laser sound then ave the sip {forward 10 stops before walng for 0. seconds We ad on ‘edge, bounce'tostop the Rocket gettinglost With of the code complete as shown below save your ‘wore an blast oor an adventure! ‘es rnb sonata esi Mareeba, leap inbtseanstectt ‘ocenby ton, ‘ovens dpleteccety ‘ah chinge te Goede Dota Our project is ‘crany space same where fur rocket must attack the mysterious ‘Space Dragan while alco ‘voiding a deadly ‘Space Robot and Comet. Coding Made Simple | 23

You might also like