Download PDF Jump start coffeescript get up to speed with coffeescript in a weekend 1st edition cast

Page 1


Jump Start CoffeeScript Get Up to Speed With CoffeeScript in a Weekend 1st Edition Castledine Earle

Visit to download the full and correct content document: https://textbookfull.com/product/jump-start-coffeescript-get-up-to-speed-with-coffeescr ipt-in-a-weekend-1st-edition-castledine-earle/

More products digital (pdf, epub, mobi) instant download maybe you interests ...

Jump Start Node js Get Up to Speed With Node js in a Weekend 1st Edition Nguyen Don

https://textbookfull.com/product/jump-start-node-js-get-up-tospeed-with-node-js-in-a-weekend-1st-edition-nguyen-don/

Jump Start Git 2nd Edition Shaumik Daityari

https://textbookfull.com/product/jump-start-git-2nd-editionshaumik-daityari/

Shut Up and Run How to Get Up Lace Up and Sweat with Swagger Robin Arzon

https://textbookfull.com/product/shut-up-and-run-how-to-get-uplace-up-and-sweat-with-swagger-robin-arzon/

Best jobs for ex offenders 101 opportunities to jump start your new life Second Edition Krannich

https://textbookfull.com/product/best-jobs-for-exoffenders-101-opportunities-to-jump-start-your-new-life-secondedition-krannich/

Boosting Your Energy How to jump start your natural energy and fight fatigue 1st Edition Anthony L. Komaroff

https://textbookfull.com/product/boosting-your-energy-how-tojump-start-your-natural-energy-and-fight-fatigue-1st-editionanthony-l-komaroff/

Leading with Noble Purpose How to Create a Tribe of True Believers 1st Edition Lisa Earle Mcleod

https://textbookfull.com/product/leading-with-noble-purpose-howto-create-a-tribe-of-true-believers-1st-edition-lisa-earlemcleod/

Level Up Press Start 1st Edition Simon Archer Archer

Simon

https://textbookfull.com/product/level-up-press-start-1stedition-simon-archer-archer-simon/

Selenium Fundamentals Speed up your internal testing by automating user interaction with browsers and web applications 1st Edition Diego Molina

https://textbookfull.com/product/selenium-fundamentals-speed-upyour-internal-testing-by-automating-user-interaction-withbrowsers-and-web-applications-1st-edition-diego-molina/

Popup republic : how to start your own successful popup space, shop, or restaurant 1st Edition Baras

https://textbookfull.com/product/popup-republic-how-to-startyour-own-successful-pop-up-space-shop-or-restaurant-1st-editionbaras/

GE T U P TO SP EE D W IT H COFFEESCRIP T IN A WEEKEND

JUMPSTART COFFEESCRIPT

BY EARLECASTLEDINE

Jump Start CoffeeScript

Copyright © 2012SitePointPty.Ltd.

Product Manager:SimonMackie

Technical Editor:DianaMacDonald

Assistant Technical Editor:BenAxnick

Indexer:GlendaBrowne

Notice of Rights

Expert Reviewer:CraigSharkie

English Editor:KellySteele

Cover Designer:AlexWalker

Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystemortransmitted inanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecase ofbriefquotationsembodiedincriticalarticlesorreviews.

Notice of Liability

Theauthorandpublisherhavemadeeveryefforttoensuretheaccuracyoftheinformationherein. However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied. NeithertheauthorsandSitePointPty.Ltd.,noritsdealersordistributorswillbeheldliableforany damagestobecausedeitherdirectlyorindirectlybytheinstructionscontainedinthisbook,orbythe softwareorhardwareproductsdescribedherein.

Trademark Notice

Ratherthanindicatingeveryoccurrenceofatrademarkednameassuch,thisbookusesthenamesonly inaneditorialfashionandtothebenefitofthetrademarkownerwithnointentionofinfringementof thetrademark.

PublishedbySitePointPty.Ltd.

48CambridgeStreetCollingwood VICAustralia3066

Web:www.sitepoint.com

Email:business@sitepoint.com

ISBN978-0-9872478-2-7(print)

ISBN978-0-9872478-3-4(ebook)

PrintedandboundintheUnitedStatesofAmerica

Dedication

ToAmelia:IfIcouldwrite,I’dwriteabookforyou.

About the Author

SportingaMastersinInformationTechnologyandalifetimeofexperienceontheWebof HardKnocks,EarleCastledine(akaMrSpeaker)holdsaninterestineverythingcomputery. Raisedinthewildbyvarious8-bithomecomputers,hesettledintheInternetduringthe mid-ninetiesandhasbeenlivingandworkingthereeversince.

AseniorsystemsanalystandJavaScriptflâneur,heisequallyhappyinthemuddypitsof .NETcode,thedensefoliageofmobileappsandgames,andthefluffycloudsofclient-side interactiondevelopment.

Asco-creatorofclient-sideopushttp://www.turntubelist.com/,aswellasmanyweb-based experiments,EarlerecognizestheInternetnotasalubricantforsocialchange,butasavehicle forunleashingfrivolousECMAScriptgadgetsandinterestingtime-wastingtechnologies.

About the Expert Reviewer

Craigwasoncehappytocallhimselfadeveloper,speaker,author,andadvocate.Sincethen, he’saddedJSmeetfounderandJSConforganizertothelist andexpertreviewer.Should youaddhusbandandfather,andyou’dbegettingclosertoworkingoutwhyhe’softenunreasonablyhappy.In2000,hewasaskedbyshort-sightedbosseswherehewantedtobein fiveyears’ time,andtwelveyearsonhe’sstilldoingthesamething workingwithlanguages helovesinacommunitythatexpandsonpossibilitiesasfastasitcreatesthem.

About SitePoint

SitePointspecializesinpublishingfun,practical,andeasy-to-understandcontentforweb professionals.Visithttp://www.sitepoint.com/toaccessourblogs,books,newsletters,articles, andcommunityforums.You’llfindastackofinformationonJavaScript,PHP,Ruby,Mobile, design,andmore.

About Jump Start

JumpStartbooksprovideyouwitharapidandpracticalintroductiontowebdevelopment languagesandtechnologies.Around150pagesinlength,theycanbereadinaweekend, givingyouasolidgroundinginthetopicandtheconfidencetoexperimentonyourown.

Preface

Destructured Assignment 2: Objects

Adding the AI Rules into the Code

Power to the Professor

Digging Holes

Building

Chapter 6 CoffeeScript and

Chapter 7

Preface

CoffeeScriptis “alittlelanguagethatcompilesintoJavaScript.”1 Itaimstosmooth oversomeofJavaScript’srougheredgeswhilehighlightingandaugmentingthe impressiveflexibilityatthecoreoftheJavaScriptlanguage.It’sclean,concise,and maintainable,andmakeswritingclient-sidecodereally, really fun.

JumpStartCoffeeScript isabookaboutCoffeeScript.Itsgoalistohelpyoubecome productivewithCoffeeScriptasquicklyaspossible.Fromthefirstlineinthebook, you’llbewritingcodethatshowsjusthoweasyitistotaketheplungeintothis delightfullyaddictiveworld.

Alongtheway,we’llmakeagame.Notjusttheouterhuskofaboringspace-based shoot ’emup,butacomplete,extensibleHTML5gamewithtilemaps,particleeffects, AI,and(ofcourse)ninjas.You’llseehowCoffeeScript’ssuccinctnessandelegance istheperfectpartnerforeffectivelyprototypingandrefiningyourideas.

That’sit.Bytheendofthisbook,you’llknowhowtomakeHTML5games,and proficientlycode(andthink)inCoffeeScript,aswellashaveadeeperunderstanding ofthepowerandbeautyofJavaScriptitself.

Who Should Read This Book

Ifyouhavesomeknowledgeofwebprogrammingconceptsandwanttostreamline writingJavaScript,thisbookisforyou.

Conventions Used

You’llnoticethatwe’veusedcertaintypographicandlayoutstylesthroughoutthis booktosignifydifferenttypesofinformation.Lookoutforthefollowingitems.

Code Samples

Codeinthisbookwillbedisplayedusingafixed-widthfont,likeso:

1 http://coffeescript.org/

<h1>A Perfect Summer's Day</h1>

<p>It was a lovely day for a walk in the park. The birds were singing and the kids were all back at school.</p>

Ifthecodeistobefoundinthebook’scodearchive,thenameofthefilewillappear atthetopoftheprogramlisting,likethis:

example.css

.footer { background-color: #CCC; border-top: 1px solid #333; }

Ifonlypartofthefileisdisplayed,thisisindicatedbytheword excerpt: example.css (excerpt) border-top: 1px solid #333;

Ifadditionalcodeistobeinsertedintoanexistingexample,thenewcodewillbe displayedinbold:

function animate() { new_variable = "Hello"; }

Also, where existing code is required for context, rather than repeat all the code, a ⋮ will be displayed:

function animate() { ⋮ return new_variable; }

Some lines of code are intended to be entered on one line, but we’ve had to wrap them because of page constraints. A ➥ indicates a line break that exists for formatting purposes only, and should be ignored.

URL.open("http://jspro.com/raw-javascript/how-to-create-custom-even ➥ts-in-javascript/");

Tips, Notes, and Warnings

Hey, You!

Tipswillgiveyouhelpfullittlepointers.

Ahem, Excuse Me …

Notesareusefulasidesthatarerelated butnotcritical tothetopicathand. Thinkofthemasextratidbitsofinformation.

Make Sure You Always … payattentiontotheseimportantpoints.

Watch Out!

Warningswillhighlightanygotchasthatarelikelytotripyouupalongtheway.

Supplementary Materials

http://www.sitepoint.com/books/coffeescript1/ Thebook’swebsite,containinglinks,updates,resources,andmore.

http://www.sitepoint.com/books/coffeescript1/code.php Thedownloadablecodearchiveforthisbook.

http://www.sitepoint.com/forums/forumdisplay.php?15-JavaScript-amp-jQuery SitePoint’sJavaScriptforum,forhelponanytrickyCoffeeScriptproblems. books@sitepoint.com

Ouremailaddress,shouldyouneedtocontactusforsupport,toreportaproblem,orforanyotherreason.

Challenge Yourself

Once you’ve mastered CoffeeScript, test yourself with our online quiz. With questions based on the book’s content, only true CoffeeScript champions can achieve a perfect score. Head on over to http://quizpoint.com/#categories/COFFEESCRIPT.

Friends of SitePoint

Thanks for buying this book. We really appreciate your support! We now think of you as a “Friend of SitePoint,” and so would like to invite you to our special page: http://sitepoint.com/friends. Here you can SAVE up to 43% on a range of other super-cool SitePoint products, just by using the password: friends.

Chapter1

Getting Started

CoffeeScriptisaprogramminglanguagethatlookslikethis:

hello = (name) -> alert "Hello, #{name}!"

hello "World"

Here,we’redefiningandthencallingafunction, hello,whichacceptsasingle parameter, name,andisdisplayedinanannoyingfashiononthescreen(via alert).

Ifyou’reacoder,you’veprobablyidentifiedafewinterestingelementsinthispiece ofcode.Indeed,oneofthisbook’sgoalsistothoroughlyexplorethesyntacticand pragmaticchoicesthatmakeCoffeeScriptaninterestingprogramminglanguage.

CoffeeScriptoccupiesaweirdspaceintheprogramminglanguagelandscape:itwas designedfromthebeginningtopiggybackontopofJavaScript,thedefactolanguage oftheWeb.CoffeeScriptcodeistranspiled(ortranscompiled)directlyintoJavaScript code,acunningtricktoleveragetheubiquityofthewebbrowserasanexecution environment.ThismeansthatCoffeeScriptrunswhereverJavaScriptruns,andcan dowhateverJavaScriptcando.AndwiththeriseoftechnologieslikeNode.jsand HTML5,that’salotofplacesandalotoffunctionality.

Whywritealanguagethat’ssimplyacopyofanotherlanguage?Becausetheprimary purposeofCoffeeScriptistobeasimplerversionofJavaScript.CoffeeScriptaims tohighlightandstreamlinethefantasticallypowerfulpartsofitsprogenitorwhile concealingandrepairingitsroughspots.Itaimstobemoreexpressive,yetmore succinct.Itaimstobefun.

How?Withoutgoingintodetails(andnevermindifsomeofthefollowingsounds likegibberish),CoffeeScriptprovidesuswithabunchoffeaturesthatwecurrently lack:nicersyntax,functionbinding(tohelpwithscopingissues),multilinestrings, splats(forneatlyhandlingvariableparameterlengths),lambdafunctionswithimplicitreturns,listcomprehensions,destructuring,ranges,simpleclasseswithinheritance,stringinterpolation,afunkyexistentialoperator...andsomuchmore.

AsideeffectoflearningCoffeeScriptisthatyouwillimproveatJavaScript.Ifyou’re herebecauseyouhateJavaScriptandneverwanttoseeanotherlineofit,Ihave badnews:CoffeeScriptisnotanattempttokillJavaScript(unlikesomenewer transpiledlanguages I’mlookingatyou,Dart),buttoco-existandultimatelyhelp improveJavaScriptitself.That’showgooditis!

HTML5 Game Jam Challenge

It’s9.00a.m.onMondaymorning.You’resittinginacoffeeshop,eagerlyawaiting thearrivalofyourfellowteammemberstocommenceyourentryinthe “7-day HTML5GameJam-a-ThonChallenge(TM),” asadvertisedinFigure1.1.Therules aresimple:YouhavesevendaystocreateanHTML5videogamefromscratch.

Figure 1.1. Game Jam-a-Thon

Ourgamewillbeatraditional2Dplatform-typeaffair,withbadguysandplatforms andladdersandsuch andyou’vedecidedthatit’stheperfectprojecttolearnsome CoffeeScript.Ofcourse,you’vefailedtomentiontoyourteammatesthat,despite theincrediblytighttimeframeforthecompetition,you’regoingtowritethegame

inalanguagethatyouhavenoexperiencein.We’dbettertakeafewminutesto learnsomeofthebasicsbeforetheyarrive …

The Basics

Firstup,howcanwerunsomecode?ItturnsoutthattheoptionsavailableforexecutingCoffeeScriptarelegion.Asweonlyhaveafewminutestogetuptospeed, we’llchoosethesimplest:

■ HeadtotheCoffeeScriptwebsite[http://www.coffeescript.org].

■ Selectthe Try CoffeeScript tab.

■ Activatethe Run button,asshowninFigure1.2.

Ebbs and Flows

TheInternetebbsandflowslikethetides,andbythetimeyoureadthistext,the “click-to-run” functionalitymayhavemoved,morphed,ordisappearedfromthe CoffeeScriptwebsite.Ifthat’sthecase,don’tfear:we’recoveringmoreoptionsin thesectioncalled “StartingtheGameProject”.

Thedefaultcodeisasimplealertboxthatshowsthetext, “Hello,CoffeeScript!” AnyCoffeeScriptcodeintheleftpanelwillbetranspiledtoitsJavaScriptoutput, shownintheright-handpanel,andexecuted.Theactualpop-upboximplementation isnotfromCoffeeScript,butfromthenativebrowsercodethat’scalledfromthe JavaScriptoutput.Whenwe’reusingCoffeeScriptinthebrowser,wehaveaccess totheDOMaswedoinJavaScript.

Figure 1.2. Hello CoffeeScript

Let’sremovethedefaultCoffeeScriptcodeandaddsomeofourown.We’llcreate asmallfunctiontoreverseastring.There’snoneedtofullyunderstandityet(try tofigureitout,though!),butifyou’retypingalongathome,youmightwanttoindent usingspacesbecausehitting tab willchangethefocusedarea:

# Simple string reversal function reverse = (sentence) -> sentence .split("") .reverse() .join("")

# Now use our new reversing powers! text = "rats live on" backwards = reverse text alert "#{text} #{backwards}"

Runningthiswillrewardyouwithapopupcontainingtheforwardandreversed text.

Running Directly in the Browser

Howisourcode whichisn’tJavaScript runningdirectlyinthebrowserlike this?Perhapsyou’dguessit’ssendingitofftotheserverforcompilation?Nope. Thetrickis, CoffeeScriptiswritteninCoffeeScript.And,asyouknow,CoffeeScript outputstoJavaScript.Therefore,theCoffeeScriptcompilercanbeincludedina webpageandcompiledonthefly.

Let’scontrastthatblockofcodewithhowwe’dwriteitusingplainJavaScript:

var text, backwards;

// Simple string reversal function function reverse(sentence) { return sentence .split("") .reverse() .join(""); }

// Now use our new reversing powers!

text = "rats live on"; backwards = reverse(text); alert(text + " " + backwards);

You’llprobablynoticethattheCoffeeScriptandJavaScriptversionsarefairlysimilar.That’snotsurprisinginthiscasebecausewe’reusingonlyafewofCoffeeScript’s fancyfeatures,andthegutsofthealgorithm(thesplit/reverse/joinmanipulation) issimplyusingJavaScript’snativemethods.Thetruthis especiallywhenyou’re beginning youcanmostlygetawaywithwritingCoffeeScriptjustlikeJavaScript. Soit’seasytobeginwritingcodeandaddinthecooltricksasyoulearnthem.

Here’ssomemoresimpleCoffeeScriptanditscorrespondingJavaScriptoutput. Nothingwillhappenwhenyourunthis(because collided isnever true);it’smerely tohighlightmoredifferences.Ifyou’rejuststartingoutwithCoffeeScript,comparing thebeforeandaftercodeis invaluable forlearninghowitworks:

lives = 3 collided = false

# ...after some game logic... if collided lives = lives - 1 alert "Game Over" if lives is 0

Oncecompiled,thiswillspitoutthefollowing: var collided, lives; lives = 3; collided = false; if (collided) { lives = lives - 1; if (lives === 0) { alert("Game Over"); } }

JavaScript under the Hood

ThisistheactualJavaScriptthattheCoffeeScripttranspilesitselfinto.Itmaynot beexactlyhowyou’dwriteyourownJavaScript,butitisfunctionallyequivalent.

InCoffeeScript,wedon’tusea var declaration;it’sdoneforus,andwe’reusing somekindofweirdinvertedsyntaxtotest if lives is 0.Eveninthesetwobrief snippets,thereareabunchofsmallandimportantdifferencesbetweenthelanguages. I’mwarningyounow:ifyou’realong-timeJavaScripter,someofthemmightrub youthewrongwayatfirst,sohangtight …

Missing Cruft

CoffeeScriptdoesawaywithabundleoftheboilerplateelementsofJavaScriptcode: semicolonsandcurlybracesaregone,thereareno var keywordsforvariable definitions,parenthesesareoftenomittedwhencallingfunctions,andfunctionand returnstatementsarenowheretobeseen.

ThisisaconsideredattemptonCoffeeScript’sparttoremoveasmuchaspossible that’snotdirectlyrelatedtotheproblemyou’retryingtosolve.Forthoseofuswho havespentourwholeliveswiththefunction/returnconstruct,itseemsaminor point;likepeoplewhosweartheydon’tevennoticeadvertisementsanymore,we’re surethatthecrufthasnoeffectonus.Butjustaswithadvertising,thecruftisstill there,doingitsbesttobeconfusedwithcontent makingithardertoparse(visually), andeasierforbugstostayhidden.

ApleasantsideeffectofthiscruftremovalisthatCoffeeScriptprogramsarenoticeablyshorterthantheirJavaScriptcounterparts.

Whitespace

Superficially,JavaScriptlooksalotlikeCorJava that’swhywehavecurlybraces todelimitcodeblocks.CoffeeScriptdecidedtogotheRuby/Pythonrouteanduse significantwhitespace tabsandspaces todefineastatementblock.Nestedblocks areachievedbynestingindentationlevels.Besuretokeepindentationconsistent withineachsourcefile(andforyoursanity,acrosstheentireproject!).Soifyou’re usingtwospaces,alwaysusetwospaces;otherwise,thecompilercanbecomelost.

Historically,programmerswillferventlyfightfororagainst “spacesorbraces” in thesamewaythey’dargue “tabsversusspaces.” CoffeeScriptavoidssomeofthe problemsofsignificantwhitespacebyvirtueofitstranspilednature;forexample, peopledislikethatwhitespaceisunabletobeminimized,unlikecurly-braceprogramminglanguages.However,asouroutputisJavaScript,it’sthisoutputthatwill bethetargetofourminimizationefforts.

Comments

Commentsaren’texecuted:

# Commencing a line with a # indicates a comment

What’smore,they’reexcludedfromtheJavaScriptoutput: So,thisisacasewhereCoffeeScriptis,infact,moreverbosethanJavaScript!Ifyou wantamultilinecommentblock,youusethetriplehashes:

###

Everything you put here will be ignored. Unlike single-line comments - these show up in the output.

###

Thiswillproducethefollowing:

/*

Everything you put here will be ignored. Unlike single-line comments - these show up in the output.

*/

Multilinecommentsareincludedinthecompiledoutput;thismakesthemuseful foraddingblockheaderstoeachfile,forexample.

Types, Variables, and Scope

CoffeeScripttypesareJavaScripttypes:numbersarenumbers,stringsarestrings, BooleansareBooleans.Butthewayvariablesarehandledisquitedifferent.As you’veseenfromtheexamplessofar,thereisno var statementinCoffeeScript it’s

handledautomatically.So,ifyouhadthefollowingvariabledeclarationsinJavaScript:

var result = [], count = 0, $el;

… theequivalentinCoffeeScriptwouldbesimply:

result = [] count = 0

Wewouldn’tdefine $el becausewe’reyettouseit!Whenyoudefineavariablein CoffeeScript,the var declarationispusheduptotheclosestscopethatthevariable isin(similartoRuby’slocalscope).ThisavoidsthecommonpitfallinJavaScript ofaccidentallycreatingglobalvariables thoughitdoesmeanyouneedtotakecare toavoidreusingvariablenameswhenyounestfunctions,becausetheinnervariable willjustbeareferencetotheoutervariable.

CoffeeScriptalsohelpsoutwithsomeoftheotherfunpartsofJavaScriptscope, whichwe’lldelveintolater.

Functions

FunctionsareoneofthemostpowerfulaspectsofJavaScript.Theyarefirst-class citizensofthelanguage,becauseyoucanpassafunctionasaparameterorreturn afunctionastheresultfromanotherfunction.Youcancomposethem justasyou caninotherfunctionalprogramminglanguages,suchasLisp.Infact,asJavaScript’s residentguru,DouglasCrockford,oncesaid,JavaScripthasmoreincommonwith functionallanguageslikeLisporSchemethanwithCorJava.1

Youmightnotbesoldonfunctionalprogramming(cough justyet cough),butit’s aparadigmthatisverypowerfulandalotoffun.Asanexample,partofjQuery’s successisduetothejoyofbeingabletochainabunchoffunctionstogetherto manipulateandprocesslistsofDOMnodes.EachstepofthejQuerychainreturns anewlist,andthelistscanbefilteredortransformedasneeded.

1 http://javascript.crockford.com/javascript

Ifyouutilizeafunctionalstyle ordoalotofasynchronouswork youwouldhave noticedanissuewithJavaScript:alargechunkofyourcodeconsistsofthe function and return keywords.ConsiderthefollowingJavaScriptsnippetthattakesanarray ofanglesindegrees,convertsthemtoradians,andthenreturnsonlyvaluesthat appearinthefirsttwoquadrants(the “tophalf” ofthecircle),asseeninFigure1.3.

Figure 1.3. Danger ahead

Wemightdothisinagametofetchdirectionstoenemiesinourfieldofview:

[45, 135, 225, 315].map(function(degrees) { return degrees * (Math.PI / 180); }).filter(function(radians) { return radians % (2 * Math.PI) < Math.PI; });

Firstweuse map toconvertdegreestoradians,then filter toonlykeepthevalues we’reinterestedin.Here’sthesamecodeinCoffeeScript(pleasenotethatthereare moreidiomaticwaystodomappingandfilteringinCoffeeScript,butthisisjustto highlightthedifferencebetweenfunctiondeclarations):

[45, 135, 225, 315].map (degrees) -> degrees * (Math.PI / 180)

.filter (radians) -> radians % (2 * Math.PI) < Math.PI

Evenforthistiny(albeitconvoluted)demonstration,that’s158JavaScriptbytes versus128CoffeeScriptbytes.Again,typingafewextracharactersisnottheissue; thepointisthatourCoffeeScriptcodecontainsjustthebareessentialstodefine

ourproblem.Inthiscase,itdoesitbyreplacingthe function keywordwiththe symbol ->,andbyhaving implicitreturns.

TheCoffeeScriptcompilertriestomakesurethatallstatementsinthelanguagecan beusedasexpressions,sonearlyeverythingwillhaveareturnvalue.Thelastexpressioninsideafunctionwillgivethevaluethat’sreturned.Consider:

square = (x) -> x * x

Short Syntax

Thisshortfunctionsyntaxisout-and-outagoodidea;sogoodthatit’sbeenacceptedintothenextversionofJavaScript.I’mtrustingthatbythetimeyoureadthis book,itwillbepartofthestandardandalreadyimplementedinyourbrowser and thiswholesectionwillseemobvioustoyou.Ifthat’sthecase,justremember:you haveCoffeeScripttothankforit!

Starting the Game Project

Hmmm,thisisabadsign.It’sthekick-offmeetingondayoneandyourteamis alreadyhalfanhourlate.Afterorderinganothercupofcoffee,2 youdecideyou mightaswellstartonthegame.Thefirststepistocreatethebaseprojectandset upyourenvironmentfordevelopment.

Installing: an Overview

Aswementionedrightatthebeginning,CoffeeScriptsitsinabitofaweirdspace foralanguage.Formostprogramminglanguages, “installing” meansdownloading apackagefromtheauthor’swebsiteandrunningit.ButCoffeeScriptisabitdifferent: thecorecompilerisavailableasacommandlinetoolthatcanberuninanyJavaScriptenvironment,andatthepresenttimethismeansrunningunderNode.js.

Node.jsisapopularplatformforrunningJavaScriptapplications.It’softenusedas awebserverforservingappsthatuseJavaScriptasboththeclient-andserver-side language.However,CoffeeScriptusesitforrunningitscommandlinetoolthat compilesoursources.WeneedtoinstallbothNode.jsandthenthe coffee tool.

2 Pleasenote,thisisnotacoffeepun.We’vestrivedtoeliminateallcoffee-basedpunsfromthebook.

Client-side Compilation on the Fly

“Myteammateswillbehere anyminute,andyouexpectmetoinstallandconfigure thewhole internetintenseconds?Theremustbeanotherway … , ” yougrumble toyourself.Well,thereisanotherway.Butyouhaveto promise afteryouhavetried itandwrittensomecodetoreadthenextsectiononinstallingthingsproperly.

OntheCoffeeScript.orgwebsite,wewererunningcodeandexecutingitlive.This workedbecauseCoffeeScriptiswritteninCoffeeScript,sothecompileritselfcan beoutputasplain-oldJavaScript.Youcandownloadaspecialversionofthis JavaScriptthat,whenincludedinyourwebpage,automaticallycompilesanyCoffeeScriptcodesnippetsonthepage.Magic!

Not for General Consumption

ThistechniqueoffindingandcompilingpiecesofCoffeeScriptinthepageisa novelandinterestingidea,butit’sinefficient.Everypageviewrequiresthecompilertobeloadedunnecessarily(itshouldbecachedafterthefirstview),and everychunkofcodemustberecompiled which,dependingonthecomplexity andsizeofthecode,canbeveryslow.It’sausefultoolfortesting,butifyou’re servingpagestothegrandpublic,youshouldbeusingprecompiledJavaScript.

Thefirststepistograbthecompiler.Theofficialsourcerepositoryfortheentire projectisonJeremyAshkenas’s(thecreatorofCoffeeScript committhatnameto memory!)GitHubrepositoryathttps://github.com/jashkenas/coffee-script.Atthe moment,we’reonlyinterestedintheJavaScriptfileforthebrowser.Thislivesin the extras/ directoryoftherepository,oryoucangrabitfromthedirectlinkviathe websiteathttp://coffeescript.org/extras/coffee-script.js.

Savethefiletoyourproject whereveryou’dnormallyputyourthird-partyscripts (I'mputtingitinthe /vendor directory) andincludeitinthepage:

chapter01/01jsandcs/index.html (excerpt)

<script src="vendor/coffee-script.js"></script>

TodefineasnippetofCoffeeScript,youhavetowrapitina script tagandgiveit thecustom typetext/coffeescript (ratherthantheusual text/javascript).This

preventsthebrowserfromtryingtoexecuteitasregularJavaScript,andgivesthe CoffeeScriptlibraryawaytofindallthecodeitneedstocompile:

<script type="text/coffeescript"> alert "Look ma! no braces!"

</script>

Thesesnippetscanbesprinkledanywhereinthecode,thoughyoushouldprobably followgoodpracticesandplaceyourscriptsatthebottomofthepage.Here’safull example,includingbothourfavoritelanguagestogether:

chapter01/01jsandcs/index.html

<!DOCTYPE html>

<html> <head>

<meta charset="utf-8">

<title>HTML5 Game Jam Entry</title> </head>

<body>

<h1>Ready to RUMBLE!</h1>

<script src="vendor/coffee-script.js" type="text/javascript"></script>

<!-- Run some JavaScript --> <script type="text/javascript"> alert("JavaScript is here."); </script>

<!-- Run some CoffeeScript --> <script type="text/coffeescript"> alert "CoffeeScript is here, too!"

</script>

</body> </html>

CoffeeScriptrunningdirectlyinthebrowser … weird!Ifyoudidn’tgetthealert dialog,double-checkthepathtothelibrary,andbesureyousetthescript type correctly.Youshouldmakesurethefunctionswewroteaboveworkheretoo.

Installing CoffeeScript Properly

It’stimetogetserious.Ourrealgoalsetupistocreateanenvironmentthatletsus runthe coffee utility,whichisacommand-linetoolforturningCoffeeScriptfiles intoJavaScriptfilesthatwethenincludeinourwebpageslikeanyordinaryresource.

No Installation Required

SomewebframeworkssuchasRubyonRails3 andthePlay!framework4 support CoffeeScriptbydefault.Ifyou’reusingsuchaframework,noneofthisinstallation isnecessary;justplaceyour .coffee filesinthecorrectplaceandtheframework willcompilethemforyou.IfCoffeeScriptisnotsupportedbyyourframeworkof choice,writethecreatorsapersuasiveemailtoday!

Installing Node.js

Firstup,you’llneedthelateststableversionoftheNode.jsplatform.Handyinstallers areavailableforWindowsandMacfromthedownloadpageat http://nodejs.org/download/.Ifyou’reinaUnixenvironment,youcanalsograb thesourcesfromthedownloadpageorinstallviayourdistro’spackagemanager.5

Oncetheinstalliscomplete,youshouldbeabletorunNode.jsfromyourterminal via node,asshowninFigure1.4.Iftheinstallcompletedcorrectlybutthenode commandwasnotfound,besuretorestartyourshellsession,andcheckthatthe Nodepathexistsinyourshellenvironmentpath.

3 http://www.rubyonrails.org

4 http://www.playframework.org

5 https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager

Installing Coffee

Thenextstepistoinstall coffee.Theeasiestwaytodothisisvianpm,Node’s packagemanagerforinstallingmodules.ThisisinstalledwhenyouinstallNode, soitshouldalreadybeavailabletoyou.Tryitoutwiththefollowingcommand(if you’restillontheNodecommandline,you’llneedtoexitbypressing Ctrl-d):

npm --version

Wewanttouse npm tograbthe coffee-script module6 (notethehyphen).Toactuallyinstallthemodule,use npm’s install command:

npm install -g coffee-script

Global versus Local

OntheofficialNode.jsblog,sparinguseofglobalinstallsisrecommended.7 The guidelineistouseaglobalinstallifthepackageneedstobeaccessedonthe commandline,asinourcase.

ThiswillfetchthemoduleandmakeitavailableviaNode.js.Youcanmakesure everythinghasgonetoplanbyopeningupanewconsolesessionandaskingfor somehelponournewmodule:

6 https://npmjs.org/package/coffee-script

7 http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/

Figure 1.4. Running Node.js from your terminal

coffee --help

ThisshouldshowoutputintheveinofFigure1.5.

Coffee Options

That’sitforinstalling oursystemisnowfullyoperational.Thelaststepistofigure outhowtointegrate coffee intoourworkflow.Bydefault,the coffee utilitywill run .coffee files.Totestitout,createablankdocumentinyourtexteditorandsave itas friday.coffee;thenaddthefollowing:

chapter01/02isitfriday/script.coffee (excerpt) day = new Date().getDay() isFriday = if day == 5 then "YES!" else "no."

console.log "Is it Friday? #{isFriday}"

Finally,atooltotellusifit’sFridayornot!Again,don’tworrytoomuchaboutthe syntaxfornow,butthefinallineisusedtologtothescreenoutput(becausean alertisonlyforthebrowser).Torunit,typethefollowingatyourprompt(making sureyouareinthesamedirectoryasthefile):

coffee friday.coffee

Figure 1.5. Outputting CoffeeScript help

Theoutput,ofcourse,willdependonthedayyourunit!Nowweknowhowto makecommandlinetools,butthat’snogoodforanHTML5game weneed JavaScriptfiles.First,modifythe console.log tobeanalert(we’lllookmoreat console.log inthesectioncalled “alert versus console.log” inChapter2):

chapter01/02isitfriday/script.coffee (excerpt)

alert "Is it Friday? #{isFriday}"

Nowit’stimetocompiletheCoffeeScriptcodeusingthe --compile (or -c)flag: coffee -c script.coffee

ThisgeneratesaJavaScriptfileofthesamenameinthesamedirectory,butwith the .js extension.Openupthisfilenowandhavealookatwhat coffee hasdone. It’splainol’ JavaScript,whichwecanlinktoinawebsiteasusual:

chapter01/02isitfriday/index.html (excerpt)

<!DOCTYPE html> <html> <head>

<title>Is it Friday?</title> </head> <body>

<script src="script.js" type="text/javascript"></script> </body> </html>

The coffee toolhasastackoffeaturesthatwe’lluseaswegoalong.Atthemoment, you’llnoticethateverytimeyoumakeachangeinyour .coffee sourcefile,youneed torerunthe coffee command.We’lllookathowtobypassthis,andcreateanefficientcodingworkflowinChapter2.

Choosing Our Tech

We’vecomesofar,butstillonlyhaveanalertdialogtoshowforourefforts.It’s timetomakesomeexecutivedecisionsonhowthisgameisgoingtowork,andput someactionuponthescreen.

Another random document with no related content on Scribd:

The Project Gutenberg eBook of Jogging round the world

This ebook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this ebook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook.

Title: Jogging round the world

Riders and drivers, with curious steeds or vehicles, in strange lands and at home

Author: Edith Dunham

Release date: March 1, 2024 [eBook #73081]

Language: English

Original publication: United States: Frederick A. Stokes Company, 1905

Credits: Fiona Holmes and the Online Distributed Proofreading Team at https://www.pgdp.net (This file was produced from images generously made available by The Internet Archive)

JOGGING ROUND THE WORLD

Play-fellows of the frozen Arctic. Eskimo Children and their tame Bear

From Stereograph, Copyright by Underwood & Underwood, New York

JOGGING ROUND THE WORLD

RIDERS AND DRIVERS, WITH CURIOUS STEEDS OR VEHICLES, IN STRANGE LANDS AND AT HOME WITH STORIES AND DESCRIPTIONS

WITH NUMEROUS ILLUSTRATIONS FROM COPYRIGHTED STEREOGRAPHS BY UNDERWOOD & UNDERWOOD, NEW YORK, PUBLISHED BY SPECIAL ARRANGEMENT

NEW YORK - FREDERICK A. STOKES COMPANYPUBLISHERS

Copyright, 1905, by

Published in October, 1905

IN THE LAND OF THE ESKIMOS

I’ this a strange playmate? Would you like to have a bear to play with?

The little Eskimo children on the sledge are having a very happy time. They are merry little children, always smiling and happy, even in the long winter nights when the sun does not shine for months at a time. Wouldn’t you think it queer to have such a long night as that?

When winter is coming their father builds a low, dome-shaped house of ice and snow, with a funny little door, through which one goes into a passageway, then into a big room where the whole family lives. A lamp burns in there, filled with whale blubber or fat, and having a wick of dried turf. This makes a smoky light, but it warms the house, and the Eskimos think their winter home very comfortable.

In the long, cold season the father sometimes makes a sledge like the one in the picture. It is made of pieces of wood, with runners of ivory from the tusks of walrus, and sometimes with pieces of reindeer horn. The whole is fastened together with straps made of skin either from the reindeer or seal. It takes a long time to make a sledge, for the Eskimos do not have very good tools to work with, and have to work slowly. Usually the sledges are drawn by dogs. You have seen pictures of them, haven’t you? As many as twelve often draw a sledge, and they run very rapidly over the ice and snow, while their master keeps them in order with his long-lashed whip.

IN THE OLD PARK AT NARA

S these happy Japanese girls enjoying their ride through the park, in ’rickshaws. They look very comfortable and cool in their kimonos, don’t they?

The park they are riding in is at Nara and is such a beautiful place! It is there that a very tame herd of sacred deer is kept. Nara is on the island of Hondo, Japan, and is a very old city, famous for its carvings, cutlery and toys. You would enjoy seeing the toys that are made there, wouldn’t you?

India ink and fans come from there, too; perhaps your little fan, or your sister’s, was made in Nara. Did you know that all the figures on a Japanese fan mean something, and sometimes a whole story is connected with them? The parasols, too, are interesting, and the designs on them are not arranged simply to look pretty, but each has its meaning to the Japanese people.

In Nara, as in most of the Japanese cities, there are some noted temples, and the carving in a few of them is said to be the finest in Japan. In one of the temples is a huge bell over thirteen feet high. Would you like to hear it? In another is a statue of Buddha more than ten times as tall as you are, the biggest one in Japan. In Nara, too, are storehouses in which there are specimens of articles used in the Imperial household hundreds of years before our grandfathers lived.

A Ride in the old Park at Nara, Japan. Pretty Japanese Maidens in ’Rickshaws

From Stereograph, copyright by Underwood & Underwood, New York

A JAPANESE LADY IN A YAMA-KAGO

T does not look like a very safe way of travelling, does it? The bridge is so narrow and the water rushes by so rapidly that we should not enjoy crossing in a yama-kago (mountain chair).

The Japanese people are used to going this way over mountain roads and rough places, so they do not mind. This little bridge is near Nikko (“Sunny Splendour”), a very beautiful city at the foot of a great mountain range in Japan.

A long avenue lined with cryptomerias, a kind of cypress tree, leads to the city, making a picture worth seeing, with the tall, pinkish trunks and masses of green against the blue sky. Often one gets a glimpse of some temple wonderfully carved and coloured, or a waterfall rushing down.

The temples and waterfalls are famous, and also the mausoleum of Iyeyasee, the most wonderful man in Japanese history. A long flight of stone steps leads to a marvellously carved gate, inside of which is a court with storehouses full of ancient treasures, and a stable with a wonderful frieze of monkeys. In the stable is the sacred steed said to bear away the spirit of Iyeyasee. Through a bronze gate, then through another gate of white and gold, one passes through court after court until the shrine is reached.

Another interesting thing in Nikko is the red lacquered bridge over the river Daiya. Only the Emperor is allowed to cross this bridge.

Japanese Lady in a Yama-kago (Mountain Chair) crossing the Daiya River near Nikko, Japan

From Stereograph, copyright 1904, by Underwood & Underwood, New York

THE UNICYCLE OF KOREA

W very often see bicycles and tricycles, but did you ever before see a unicycle like this? The uncomfortable looking vehicle can only be used by very high officials in Korea, and it is a mark of great distinction to have four coolies instead of two. See the very elaborate robes of the high general. I should think he would have to sit very still on his high seat. A coolie marches ahead of him carrying his robe of state when he goes to the royal palace.

Korea is a strange country; the people look like the Japanese; the customs are somewhat like those of the Chinese; and yet the Koreans are quite different from either. The country is hilly, and when walking one no sooner gets to the bottom of one hill than he begins to go up another. Korea is famous for its paper, which is very strong and does not tear easily The houses have partitions and windows of oiled paper. Glass is quite uncommon.

Looking down into Seoul, the chief city, from the wall one is reminded of a bed of mushrooms. The houses are one-storied, with sloping roofs tiled or covered with turf, and very close together. The wall has eight gates, each with a name, as, “Gate of Amiability,” “Gate of Everlasting Ceremony.” The Northern Gate is up on a high hill, from which at night signal lights shine out to let the people know if all is well with Korea.

One of the most curious Vehicles of the World: the Unicycle of Korea. Used for High Generals

From Stereograph, copyright by Underwood & Underwood, New York

A KOREAN LADY IN HER PALANQUIN

I we were in Seoul, we could not see this lady in the palanquin, because the curtains would be closely shut.

The Korean ladies of the higher classes are seldom seen by anyone outside of their households, and the middle-class women, if they have to walk on the street, have a peculiar garment, with long, loose sleeves, which they put over their heads. The sleeves hang down, looking like a curious kind of ears, and the cloak is held closely before the face so that it cannot be seen.

Would you like to take a walk through the streets of Seoul, and see the crowds of strangely dressed people, the many one-storied houses and the booths? Perhaps we should meet the water-coolie who goes about all day carrying water to anyone who wants it. He has a queer way of carrying it, too: a long pole is fastened crosswise on his shoulders by straps going under and around his arms. From this pole hang two buckets or pails.

There are many beautiful palaces in Seoul, with pretty little lakes and ponds in the gardens. Some of these lakes are covered with lotus flowers, and there is usually a tiny island in the centre with a tree on it, under which one can sit and enjoy the pretty garden. One of the very interesting things to see in Seoul is an old, old marble pagoda which has been built so long that the people cannot remember who built it.

Korean Lady and Maid, in the Streets of Seoul, Korea. (The Curtain is seldom raised.)

From Stereograph, copyright 1904, by Underwood & Underwood, New York

A KOREAN GENERAL IN THE STREETS OF SEOUL

T Korean general in this palanquin must be a very important person indeed. See the large number of attendants he has. An ordinary palanquin is carried by two coolies. Only high officials, foreign consuls, or legal advisers of the emperor are supposed to have four, and in the pictures we see at least eight men taking this general through the streets of Seoul. Only four seem to be really carrying the chair, so the men at the side are probably not coolies. See, their hats and clothing are different from those of the coolies.

The streets of Seoul are very wide, but look narrow because the shopkeepers put up booths in front of their houses, and spread out their wares before them, on mats or trays, so that there is not much room left. One very wide street has two rows of houses or booths down the middle; so it seems as though there were three narrow streets instead of one wide one.

When the emperor passes through in procession all these booths are taken down, and the street is swept and decorated in his honour. The next day the booths are put up again and affairs go on in quite the usual way.

There is an interesting old bronze bell in Seoul, which used to be rung in the morning and at sunset. The gates of the city were closed at dark, and all the men had to stay at home and could not be out on the street, except at festival times.

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.