100% found this document useful (4 votes)
54 views

Full Learn JavaScript With p5.js: Coding For Visual Learners Arslan Ebook All Chapters

Visual

Uploaded by

eldeebguenos
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
54 views

Full Learn JavaScript With p5.js: Coding For Visual Learners Arslan Ebook All Chapters

Visual

Uploaded by

eldeebguenos
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Download the full version of the textbook now at textbookfull.

com

Learn JavaScript with p5.js: Coding for


Visual Learners Arslan

https://textbookfull.com/product/learn-javascript-
with-p5-js-coding-for-visual-learners-arslan/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Getting Started with p5 js Making Interactive Graphics in


JavaScript and Processing 1st Edition Lauren Mccarthy

https://textbookfull.com/product/getting-started-with-p5-js-making-
interactive-graphics-in-javascript-and-processing-1st-edition-lauren-
mccarthy/
textbookfull.com

Full Stack JavaScript Learn Backbone js Node js and


MongoDB Mardan Azat

https://textbookfull.com/product/full-stack-javascript-learn-backbone-
js-node-js-and-mongodb-mardan-azat/

textbookfull.com

Coding Art A Guide to Unlocking Your Creativity with the


Processing Language and p5 js in Four Simple Steps 2nd
Edition Mathias Funk
https://textbookfull.com/product/coding-art-a-guide-to-unlocking-your-
creativity-with-the-processing-language-and-p5-js-in-four-simple-
steps-2nd-edition-mathias-funk/
textbookfull.com

The Handbook of Media Education Research 1st Edition


Stuart R. Poyntz

https://textbookfull.com/product/the-handbook-of-media-education-
research-1st-edition-stuart-r-poyntz/

textbookfull.com
The Primitivist Theory of Truth Jamin Asay

https://textbookfull.com/product/the-primitivist-theory-of-truth-
jamin-asay/

textbookfull.com

His Scarred Woman 1st Edition Sam Crescent

https://textbookfull.com/product/his-scarred-woman-1st-edition-sam-
crescent/

textbookfull.com

Professions And Metaphors Understanding Professions In


Society Andreas Liljegren

https://textbookfull.com/product/professions-and-metaphors-
understanding-professions-in-society-andreas-liljegren/

textbookfull.com

Chinese History and Culture Sixth Century B C E to


Seventeenth Century Volume 1 Yingshi Yu

https://textbookfull.com/product/chinese-history-and-culture-sixth-
century-b-c-e-to-seventeenth-century-volume-1-yingshi-yu/

textbookfull.com

Articulations of Capital: Global Production Networks and


Regional Transformations 1st Edition John Pickles

https://textbookfull.com/product/articulations-of-capital-global-
production-networks-and-regional-transformations-1st-edition-john-
pickles/
textbookfull.com
Adaptive Sports Medicine A Clinical Guide Arthur Jason De
Luigi (Ed.)

https://textbookfull.com/product/adaptive-sports-medicine-a-clinical-
guide-arthur-jason-de-luigi-ed/

textbookfull.com
Learn JavaScript
with p5.js
Coding for Visual Learners

Engin Arslan
Learn JavaScript
with p5.js
Coding for Visual Learners

Engin Arslan
Learn JavaScript with p5.js: Coding for Visual Learners
Engin Arslan
Toronto, Ontario, Canada

ISBN-13 (pbk): 978-1-4842-3425-9 ISBN-13 (electronic): 978-1-4842-3426-6


https://doi.org/10.1007/978-1-4842-3426-6
Library of Congress Control Number: 2018935139

Copyright © 2018 by Engin Arslan


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Natalie Pao
Development Editor: James Markham
Coordinating Editor: Jessica Vakili
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505,
e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a
California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc
(SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected], or visit http://www.apress.
com/rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is
available to readers on GitHub via the book’s product page, located at www.apress.com/
978-1-4842-3425-9. For more detailed information, please visit http://www.apress.com/
source-code.
Printed on acid-free paper
Table of Contents
About the Author��������������������������������������������������������������������������������vii
About This Book����������������������������������������������������������������������������������ix

Chapter 1: Introduction������������������������������������������������������������������������1
Why Learn Coding?�����������������������������������������������������������������������������������������������1
Coding vs. Programming���������������������������������������������������������������������������������������2
On HTML and CSS�������������������������������������������������������������������������������������������������3
Why Learn JavaScript?�����������������������������������������������������������������������������������������4
Why Do We Have Different Languages?����������������������������������������������������������������6
Learning JavaScript with p5.js�����������������������������������������������������������������������������8

Chapter 2: Getting Started������������������������������������������������������������������13


Installing p5.js�����������������������������������������������������������������������������������������������������13
Gentle Introduction to JavaScript������������������������������������������������������������������������16
Getting Started with p5.js�����������������������������������������������������������������������������������24
More About Functions�����������������������������������������������������������������������������������������26
Coordinates in p5.js��������������������������������������������������������������������������������������������31
Summary������������������������������������������������������������������������������������������������������������35
Practice���������������������������������������������������������������������������������������������������������������36

Chapter 3: Colors in p5.js�������������������������������������������������������������������37


Color Functions in p5.js��������������������������������������������������������������������������������������37
Changing Shape Colors���������������������������������������������������������������������������������������39

iii
Table of Contents

Summary������������������������������������������������������������������������������������������������������������42
Practice���������������������������������������������������������������������������������������������������������������42

Chapter 4: Operators and Variables����������������������������������������������������45


Setup�������������������������������������������������������������������������������������������������������������������45
Variables�������������������������������������������������������������������������������������������������������������47
Variables Continued��������������������������������������������������������������������������������������������49
Predefined Variables in p5.js�������������������������������������������������������������������������������55
Summary������������������������������������������������������������������������������������������������������������58
Practice���������������������������������������������������������������������������������������������������������������59

Chapter 5: Conditional Statements and Comparison Operators���������61


frameCount, frameRate, and frame���������������������������������������������������������������������61
Conditionals��������������������������������������������������������������������������������������������������������66
Summary������������������������������������������������������������������������������������������������������������75
Practice���������������������������������������������������������������������������������������������������������������76

Chapter 6: More p5.js Variables���������������������������������������������������������77


mouseIsPressed��������������������������������������������������������������������������������������������������77
mouseX and mouseY������������������������������������������������������������������������������������������80
Summary������������������������������������������������������������������������������������������������������������83
Practice���������������������������������������������������������������������������������������������������������������84

Chapter 7: Loops���������������������������������������������������������������������������������85
For Loop��������������������������������������������������������������������������������������������������������������85
Random and Noise Functions�����������������������������������������������������������������������������92
Summary������������������������������������������������������������������������������������������������������������99
Practice�������������������������������������������������������������������������������������������������������������100

iv
Table of Contents

Chapter 8: Functions������������������������������������������������������������������������101
Creating Functions��������������������������������������������������������������������������������������������101
Revisiting Setup and Draw Functions���������������������������������������������������������������107
Summary����������������������������������������������������������������������������������������������������������108
Practice�������������������������������������������������������������������������������������������������������������108

Chapter 9: Objects����������������������������������������������������������������������������109
Using Object Initializer��������������������������������������������������������������������������������������109
Using the Constructor Function������������������������������������������������������������������������117
Summary����������������������������������������������������������������������������������������������������������123

Chapter 10: Arrays����������������������������������������������������������������������������125


Using the push Method�������������������������������������������������������������������������������������125
Using Arrays������������������������������������������������������������������������������������������������������133
Using the remainder Operator���������������������������������������������������������������������������136
Summary����������������������������������������������������������������������������������������������������������141
Practice�������������������������������������������������������������������������������������������������������������141

Chapter 11: Events���������������������������������������������������������������������������143


Using mousePressed����������������������������������������������������������������������������������������143
Using keyPressed ���������������������������������������������������������������������������������������������145
Summary����������������������������������������������������������������������������������������������������������151
Practice�������������������������������������������������������������������������������������������������������������151

Chapter 12: More on p5.js����������������������������������������������������������������153


Rotate and Translate�����������������������������������������������������������������������������������������153
Push and Pop����������������������������������������������������������������������������������������������������159
Summary����������������������������������������������������������������������������������������������������������164
Practice�������������������������������������������������������������������������������������������������������������165

v
Table of Contents

Chapter 13: Final Project������������������������������������������������������������������167


Getting Started��������������������������������������������������������������������������������������������������168
User Interaction�������������������������������������������������������������������������������������������������176
Keeping the User Score������������������������������������������������������������������������������������181
Final Code���������������������������������������������������������������������������������������������������������198
Summary����������������������������������������������������������������������������������������������������������208

Appendix: Final Words����������������������������������������������������������������������209


W
 here to Go Next����������������������������������������������������������������������������������������������210
Additional Resources����������������������������������������������������������������������������������������212

Index�������������������������������������������������������������������������������������������������213

vi
About the Author
Engin Arslan is a Software Developer with a Bachelor of Science in
Materials Engineering and a Postgraduate Degree in Visual Effects. Before
becoming a Developer, he worked as a Visual Effects Artist / Technical
Director on films and TV shows including Resident Evil, Tron, Mama,
Pompeii, Vikings, and Strain. He received an Emmy nomination and won a
Canadian Screen Award for his achievements in Visual Effects. During his
time in VFX, he fell in love with Python and with programming in general.
As a result, he changed careers to be able to immerse himself completely
in software development. Engin currently works at a Toronto-based digital
services company, where he helps develop solutions in strategic problem
spaces using emerging technologies. He also works at Seneca College as
a part-time professor and creates online courses for Lynda/LinkedIn and
Pluralsight.

vii
About This Book
The emphasis of this book will be primarily on learning programming
using JavaScript and p5.js and secondarily in creating visuals. The main
focus is to teach you how to program so that you can choose to pursue
whatever field that you would like with your newly established skill set.
The skills that you will acquire from this book are highly transferrable and
can be used with whatever you choose to build: whether web applications,
programmable robots, or generative art. This means that I will provide
you with enough context so that you can build a strong foundation for
programming. But I also won’t hinder your momentum with irrelevant
technical or theoretical points. The aim is to build a strong but a minimum
viable knowledge to get you running with coding. This is the book that I
wished I had available when I was learning coding myself.
If you are an artist or a visual designer, this book is perfect for you as
you might find the examples we will be building to be directly relevant
to your work. If not, this is still a great book for learning programming as
the visual nature of the exercises will help you grasp the fundamentals
of programming more easily and let you build a strong foundation in a
shorter amount of time.
This book will present various JavaScript and p5.js features and
concepts in the following chapters. The knowledge will be reinforced
by building several useful examples like an animation and a data
visualization; and as a final project, we will be building a game that can be
deployed online using what we learned in this book!

ix
About This Book

Here is a rundown of the topics that we will be covering:


Chapter 1 - Introduction: Provides an overview of coding versus
programming.
Chapter 2 - Getting Started: We will learn some very basic JavaScript
commands and operations to get started with using p5.js.
Chapter 3 - Colors in p5.js: This will be a p5.js-specific chapter where
we learn about how colors are defined and used in p5.js. This doesn't
pertain to JavaScript but needs to be explored regardless to be able to use
p5.js in a comfortable manner.
Chapter 4 - Operations and Variables: We will make use of the
JavaScript knowledge we acquired in the second chapter in p5.js context.
Chapter 5 - Conditional Statements and Comparison Operators:
This chapter will allow us to write programs that can respond to different
conditions by using conditionals and comparison operators.
Chapter 6 - More p5.js Variables: This will be another p5.js-specific
chapter where we will learn about several library-specific variables.
Chapter 7 - Loops: Here we will learn about loops, which will allow us
to build programs that handle enormous amounts of calculations.
Chapter 8 - Functions: Functions are the building blocks of JavaScript
and we will learn more about them in order to build more scalable,
modular, and robust programs.
Chapter 9 - Objects and Chapter 10 - Arrays: Objects and Arrays
are JavaScript data structures that will allow us to organize our code and
handle complexity in more intelligent ways.
Chapter 11 - Events: Event handling will allow us to write programs
that handles user interaction.
Chapter 12 - More on p5.js: Another p5.js-only chapter where we
learn more about library-specific features before diving into our final
project.
Chapter 13 - Final Project: We will build a game using everything we
have learned up to this chapter!

x
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
CHAPTER 1

Introduction
At this age and time that we live in, coding is simply invaluable. It has
the power to uplift your career, your future prospects, and even your
intellectual capacity. Computation is driving one of the largest capital
expansions in history, and there has never been a better time to learn
coding than now.

Why Learn Coding?


My first serious interaction with coding was at college. We had to take a
course on a programming language called C Sharp. I failed the course the
first time I had to take it and barely passed it the second time when I had
to take it again. With that defeat in mind, I stayed away from coding for
the longest time. I considered it to be a talent that I simply didn’t possess.
Later, I went on to change my career from engineering to visual effects as
I wanted to work in a field that had more room for creative expression.
But working in visual effects, I came to realize that the entire operation is
actually enabled by the power of computation. From the software that is
used to the pipeline management that facilitates the production… Coding
is everywhere. It allows studios to deliver mind-blowing effects for movies
that make hundreds of millions of dollars in the box office.
Upon realizing the power of coding in my field, I decided to embark
on a journey to learn more about it. I ended up teaching myself Python,
a programming language that is widely used in visual effects. And doing

© Engin Arslan 2018 1


E. Arslan, Learn JavaScript with p5.js, https://doi.org/10.1007/978-1-4842-3426-6_1
Chapter 1 Introduction

so has been immensely gratifying. Not only has it allowed me to become


more accomplished in my work in visual effects and create award-winning
effects, but it has also empowered me to transition to an even more
rewarding career in software development.

Coding vs. Programming


You must be hearing the terms coding and programming in similar
contexts and might be wondering what the difference between them
is. In the past few years, coding has become the term of choice to make
programming more approachable to the general population. Basically the
premise is that you could be coding and still be contributing to the digital
economy without actually doing programming.
Let me give you an example of that: you could be using web languages
such as HTML and CSS, which are not programming languages. So when
coding in those languages you are not really programming but styling
or structuring websites (more on their usage in the next section). But
you could also be coding in JavaScript, which is an actual programming
language. Programming languages allow you to make a computer “do”
things. Every time you are programming something, you are also coding.
But when you are coding, you might not be programming. Coding is a
more general term that is used for describing all cases where you are
communicating intent to the computer.
Basically you can think of programming as a subset of coding. But if
truth be told, these two terms are used almost interchangeably nowadays.
The main purpose of this book is to teach you how to program. We will be
coding for programming purposes by using the programming language
JavaScript.

2
Chapter 1 Introduction

On HTML and CSS


Looking at my path for learning programming, I find some of the efforts to
teach coding to beginners to be a bit lacking. One of the primary problems
in the area is using HTML and CSS as introductory languages.
The problem with these languages is that they are not even
programming languages! HTML is a markup language that is used to
define the structure of a document in a way that a web browser would
understand. For example, HTML teaches you how to write text for a
browser so that the browser would know what parts of it is a document
header vs. a paragraph, etc…
Likewise, CSS is not a programming language either. It is a styling
language that allows us to style HTML documents to have them look
aesthetically pleasing and ideally make them more user friendly than
before. Furthermore, even though CSS can be used to create incredibly
good looking results, it is usually very unintuitive to work with and can be
hard to reason about even for a programmer. Learning CSS, you are not
only not learning programming, you are very likely engaging in an activity
that might not be fun as a beginner if styling websites is not your sole
intention.
This push to teach coding using these languages is understandable.
After all, given the large dominance of web applications and their
immense profitability in certain cases, people found themselves wanting
to build their own projects for the Web. And if you are to build a website,
you need to use these languages to a certain degree. But having these
languages as a starting point could create a misconception about what
coding is. Coding can be an immensely rewarding and engaging activity
when you are building programs or applications as the domain of
possibilities is substantially bigger. As discussed previously, we need to be
using programming languages to build programs so the apparent question
is: “What makes a language a programming language?”

3
Chapter 1 Introduction

You can always check Wikipedia for a semi-formal definition. But to


me, for a language to be considered a programming language, it needs to
have certain control structures available to it that would allow us to express
some basic operations. Even this definition probably makes little sense
to a beginner. What is meant is that there are structures in programming
languages that allow the computer to perform logical operations. Some of
the examples of such structures, which we will see more about later, are the
following: conditionals that allow the program to output different results
based on given conditions and variables that store values or loops that
allow a program to repeat operations for a desired amount of time. Don’t
worry if none of this makes any sense right now; the purpose of this book is
for us to learn about all these fundamental programming concepts.
Almost all programming languages have these kinds of basic structures
that enable us to construct immensely more complicated applications.
Think of English, or any other language you might know. You have verbs,
nouns, and adjectives. And using these building blocks, people can say
the simplest things or go on to write amazing novels. And these are the
building blocks that are missing from HTML and CSS that make people
miss out on what could be achieved when using programming languages.
In this book we will learn all these basic structures that would allow
us to communicate our intent to the computer using the programming
language JavaScript.

Why Learn JavaScript?


There are many programming languages out there. This book will be
teaching you how to code, by using the immensely popular programming
language JavaScript.
JavaScript is one of the most widely used programming languages out
there as it is built into every web browser. Due to this, almost all the web
pages and applications out there use JavaScript to some degree. In recent

4
Chapter 1 Introduction

years JavaScript started to be used not only to program user interaction in


web pages but also server side - back-end - applications, Internet of Things
(IOT) devices or mobile apps for platforms such as Android or iPhone.
Even though it has its roots in web development, JavaScript knowledge is
now applicable to a vast number of other domains.
Given the popularity and ubiquity of JavaScript, it is really easy to find
resources and information about it if you are to ever get stuck. It has a big,
vibrant community behind it. In the popular Q&A website, StackOverflow,
there are more than a million questions that are related to JavaScript. If you
end up coding in this language and get stuck in a problem, the chances are
that someone else also had the same problem, posted a question on this
website, and got an answer that you can learn from.
I won’t go into details of what makes a programming language
dynamic or static, but being a dynamic programming language, JavaScript
code is more concise and easier to write compared to static languages.
Listings 1-1 and 1-2 are some examples where a simple statement that
displays the words ‘hello world’ to the screen are written by using different
languages. Notice how much shorter it is to write the same code using
JavaScript.

Listing 1-1. Displaying Hello World to the screen in C++ (Source:


http://helloworldcollection.de/)
// Hello World in C++ (pre-ISO)
#include <iostream.h>

main()
{
        cout << "Hello World!" << endl;
        return 0;
}

5
Chapter 1 Introduction

Listing 1-2. Displaying Hello World to the screen in Java (Source:


http://helloworldcollection.de/)
// Hello World in Java

class HelloWorld {
        static public void main( String args[] ) {
                System.out.println( "Hello World!" );
        }
}

Displaying Hello World to the screen in JavaScript:

console.log('Hello World');

One other advantage of learning JavaScript is that, since it is the


language of the Web, you would be able to share your creations with other
people in a really easy manner. I think to be able to do so and receive
feedback is an important consideration when learning a new skill set.
To summarize, there are lots of reasons to learn programming and
JavaScript stands to be a great choice since it:

• is easier to write;

• is popular and ubiquitous;

• has a vast application domain.

Why Do We Have Different Languages?


You must be wondering why there are different languages if they are all
share similar features.
That’s a great question. Different languages exist because they are
designed with different principles in mind. Some of them can be harder
to type out, but they give you more control over the stability and speed of

6
Chapter 1 Introduction

your programs. Others can be much more concise but could be slower to
execute. Some languages are better suited for certain tasks. JavaScript is
perfect for full stack web development, Matlab is great for mathematical
calculations, C++ has dominance in game programming, and Julia is used
for data science. This doesn’t mean you can’t be using other languages
in these domains, though. Unity Game Engine offers C# for game
development. Python can be preferred for data science. And GoLang or
many other languages could be used for back-end web development. It
sometimes boils down to what the developers prefer to use and what they
already know. And sometimes it comes down to the constraints of a given
project.
I used to work in the visual effects industry and the software packages
that we would be using in the field could be automated using Python or
C++. So those were great language choices for that domain given that’s
what the tools that we were using were supporting. Knowing Java in visual
effects would have been largely useless except for the fact that knowing a
programming language actually makes it more likely that you will be able to
pick up another language as they share similar principles among each other.
Choosing which language to learn as your first can sometimes be a
tough choice as there are lots of viable options out there. Sometimes the
choice is dictated by the application domain. If you are seeking to build
a game using the Unreal Engine maybe you should just learn C++. But
then again if it’s your first time interfacing with a programming language,
you might be faced with such a steep learning curve that it might be
discouraging.
JavaScript stands to be a great choice to learn as your first
programming language. As mentioned earlier, it is widely used and has a
vast application domain that would allow you to experiment with lots of
different applications. It has a big and active community behind it and also
has a very concise syntax that makes it closer to human languages.

7
Chapter 1 Introduction

Learning JavaScript with p5.js


One of the most challenging aspects of learning programming is to
find engaging examples that are not only fun and impressive but also
illustrative of the subject matter at hand. Once you get the hang of
it, programming is a highly rewarding and engaging activity, but to a
beginner most of the problems that a professional programmer has to
tackle might seem uninteresting or straight up boring. That’s why this
book uses a JavaScript library, an add-on, called p5.js in teaching this
introduction to programming book. p5.js will allow you to create engaging
interactive and visual pieces that you will have fun while creating, and
it will also let you build a strong foundation for software development.
The visual nature of this library will allow us to actually see the results
from our scripts as graphics and develop an intimate understanding of
programming structures.
p5.js is a programming library. A programming library can be thought
as a collection of code that is built for a specific purpose, so that whenever
you need to perform an action that relates to that purpose you can use
a library instead of building that functionality yourself. Libraries build
on and extend the core capabilities of a language. For JavaScript, there
are more than a hundred thousand libraries out there that allow you to
perform a large variety of operations. So it is always a good idea to check
if someone already created an open source or even a paid library for your
needs before trying to implement your own functionality. The idea is that
a library would be a battle-tested solution for a particular problem that
you can utilize with confidence, instead of devising your own solution,
which might introduce unforeseen problems into the program you are
developing. This is particularly true for JavaScript as the core language
doesn’t have any built-in, standard, library; and hence development efforts

8
Chapter 1 Introduction

rely heavily on external libraries to tackle common problems. Here are


examples for a couple of interesting libraries to give you a taste of what is
available out there:

• Faker.js (https://github.com/Marak/Faker.js):
Generate massive amounts of fake data.

• franc (https://github.com/wooorm/franc): Detect the


language of a given text.

• jimp (https://github.com/oliver-moran/jimp): An
image processing library.

• cylon.js (https://cylonjs.com/): A robotics


framework for robotics, physical computing and the
Internet of Things.

p5.js is a creative coding library that is based on the idea of sketching.


Just like how sketching can be thought of as a minimal approach to
drawing to quickly prototype an idea, p5.js is built on the concept of
writing the minimal amount of code to translate your visual, interaction, or
animation ideas to the screen. p5.js is a JavaScript implementation of the
popular library called Processing, which is based on the Java programming
language.
It is worth mentioning that Java and JavaScript are completely
unrelated languages. The reason why JavaScript is named after Java is an
unfortunate branding and marketing decision made back in the day.
The concise nature of p5.js makes it a very easy library to learn. But
don’t let this simplicity trick you into believing that p5.js has limited
capabilities. p5.js has an impressive amount of functionality, history,
and community behind it to make it a valuable learning investment
if you ever wanted to create art, design, motion, or interactive pieces
using code. A p5.js program can be anywhere from a few lines of code to

9
Chapter 1 Introduction

thousands. Since p5.js was built with simplicity in mind, sometimes small
p5.js programs are referred to as sketches. Even though that’s a clever
way to describe it, I am personally not a huge fan of that wording since it
obfuscates the fact that what you are doing is programming after all.
You can find pragmatic applications of p5.js such as creating data
visualizations (Figure 1-1).

Figure 1-1. Data visualization with p5.js

10
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Chapter 1 Introduction

Or you can use it to create abstract generative art (Figure 1-2).

Figure 1-2. Abstract generative art with p5.js

You can even create animated or interactive visuals. We will be


building an interactive game by the end of this book using p5.js!

11
CHAPTER 2

Getting Started
I nstalling p5.js
There are a couple of ways you can start using p5.js and JavaScript. One
option is to visit the p5.js website (https://p5js.org/download) and
download the p5.js source code on to your system (see Figure 2-1).
At the time of the writing of this walkthrough, the download page has a
link called ‘p5.js complete’ that includes the p5.js library and an example
project. Download this archive file and find the folder named empty-
example inside it. In this folder, you will find two files: the sketch.js
file where you can write JavaScript code and an index.html file that can
be launched with a web browser such as Chrome and would execute and
display the result of the JavaScript code inside sketch.js file. You can also
find a copy of these files on my GitHub repository: https://github.com/
hibernationTheory/p5js-complete.
Even though you can change the contents of sketch.js JavaScript file
with a plain text editor like NotePad, you might instead want to use a code
editor such as `Sublime Text` to do so.
A code editor is pretty similar to a text editor, like Notepad or Word, but
it has special features that make coding much easier such as highlighting
of special words for a given programming language, which in this case
that language is JavaScript. Sublime Text is a code editor that you can use,
which can be downloaded and evaluated for free.

© Engin Arslan 2018 13


E. Arslan, Learn JavaScript with p5.js, https://doi.org/10.1007/978-1-4842-3426-6_2
Chapter 2 Getting Started

Perhaps the easiest way to get started with p5.js is to use an online
editor. An online code editor can be used inside the web browser and
doesn’t require you to install anything on your system. It is my preferred
way of working when I am learning as it makes it really easy to get started.
An easy-to-use Online Code Editor that is available at the time of the
preparation of this book can be found at this link:
[p5.js online editor - alpha](https://alpha.editor.p5js.org/)
If the above link is not accessible for any reason, you can also try the
p5.js template that is hosted on my Codepen account:
[Codepen - p5.js simple template](https://codepen.io/
enginarslan/pen/qpBBXz?editors=0011). CodePen (https://codepen.
io) is a social development platform that allows you to write code in
the browser and share your work with other developers. It is a great
environment for development and experimentation. The difference
between Codepen and the p5.js editor that is mentioned above is that the
p5.js editor only allows you to run p5.js related code inside itself whereas
Codepen can execute any front-end code.

14
Chapter 2 Getting Started

Figure 2-1. Web page to download p5.js source code

Figure 2-2. p5.js online editor


15
Chapter 2 Getting Started

How the online editor works is that, whenever we have some code
ready to be executed, we will press the play button at the top of the page.
This play button will show the results of our code on the right-hand
side panel. The online editor of Codepen is slightly different in that it
automatically executes the code any time you change it. Pressing the Play
button at this point wouldn’t do much as we didn’t write any code that
draws shapes to the screen. We will just see an empty screen get generated.
But as we can see, this editor has some code already written into it. This
code that we see is needed for almost all the p5.js programs that we will be
writing so it is included here for our convenience (Listing 2-1).

Listing 2-1. Default p5.js code

function setup() {
        createCanvas(400, 400);
}

function draw() {
        background(220);
}

Let’s just delete this code for now. Before we start using p5.js to learn
JavaScript, we will see a couple of things on the fundamentals of JavaScript.
You can find the code examples that we will be using throughout this
book at the GitHub repository: https://github.com/hibernationTheory/
coding-for-visual-learners.

Gentle Introduction to JavaScript


We can write something as simple as 1 + 1 to the screen. This is a valid
JavaScript code that adds these two numbers together. If we are to execute
this code by pressing the Play button, we still won’t see anything. This is

16
Random documents with unrelated
content Scribd suggests to you:
CHAPTER XVII

IN THE BRÛLÊ

That was a very beautiful camp and a merry night, that last night with the
cowboys from Rosebud. The fire they had made was what they called a nor'-
wester. Timber was plentiful—to be had, indeed, for the felling—and the
men left in camp had found it better fun to swing an axe than to do nothing.
So whole trees lay across the fire, and huge tongues of flame kept leaping
out and shooting into the darkness. Every now and then a log broke, and the
ends fell in with a crash, the flames roared more fiercely than ever, and a
shower of red sparks went away on the wind.

The men left in camp, being in a luxurious mood and having lots of time
on their hands, had run up a shelter of boughs—two great props and a
crosspiece, with a lot of underbrush sloping from this ridge-pole to the
ground. Under this, with their feet to the fire, lay the men smoking.

'Wal, Dick,' said the Judge, 'I reckon I don't owe you no grudge. You've
been a good pal to us, and I hope, mate, you'll strike it rich where you're a-
goin'.'

'Them's my sentiments to a dot,' said Texan, 'and if those boys of yourn


don't get their har raised by grizzly or Injun before they're six months older, I
shouldn't be much surprised if you made cowboys of them.'

'Thank you, Texan, old chap,' laughed Snap. 'If you don't do any more
mining amongst those gopher-holes before I come back, I'll bet you my best
saddle that the Cradle and I lick your head off at any distance you like on old
"Springheels."

The laugh, for a moment, went against Texan, for in the round-up just
over it was commonly stated as a fact that, whilst riding at full pace down a
hill after cattle, his pony had put its foot in one gopher-hole and shot its
owner into another, from which, five minutes later, he was extracted by a
comrade, who said that he had found Texan 'growing anyhow, just planted
root up'ards in a gopher-hole!'
'There's one thing agin you, Dick, and that's the weather,' remarked the
Judge; 'for all it's so fine now, I don't half like that fringe round the moon.'

'No, it does look watery, doesn't it?' said old Dick, looking up; 'but, hang
it all, don't let us croak. Hand me another of those fish, Snap, if you can
spare one. Bust me! if you don't eat half-pound trout as if they was shrimps,'
he added.

'There's summat I'm thinking,' said Texan after a pause, 'that's worse nor
weather. I don't want to croak, Dick, but air you sure about them Injuns? I
kem acrost their fishing-camp to-day, and there isn't a soul in it. Do you
calculate as they're on the war-path?'

'Not they!' replied Dick; 'a Crow won't face a Blackfoot nowadays, and,
unless they're stealing horses or killing cattle, they aren't doing any harm,
you bet.'

'How!'

It was a sound between a human voice and a dog's bark, sharp, hoarse,
and guttural, and it appeared to proceed from the ground under Snap's seat.
Snap was round as if a wasp had stung him. There had been no sound behind
the camp-fire; no dry twig had cracked, no leaf rustled; and yet there was
this sudden 'How!' and behind Snap stood, stiff and silent, a tall, grim-
looking Redskin.

A sort of pointed hat of rush was on his head, through the band of which
an eagle's plume had been stuck; round his shoulders was a bright-coloured
blanket, and wide trousers of deer-skin, with long fringes of the same down
the seams, reached to his ankles.

'Not a beauty,' Snap thought, and he moved a little uneasily away from
the stranger, who stood quietly staring at the group.

The Indian was certainly not a beauty, even for an Indian. His hair was
sleek and black—'snaky' Towzer called it. His eyes were small and set close
together in a big bull-like head, and he was hare-lipped. His face, too, was
full of lines and wrinkles. He was as old as the hills apparently, but old as the
oaks grow old—strong and rugged, and nowhere near being worn out.
'How!' said Dick, and he rose and gave the chief his hand, and offered
him a seat on his blanket, which he took.

'Do you speak English?' asked Snap as the Indian sat beside him, but the
only answer he got was a stony stare.

'I guess he does, for all that,' whispered Texan; 'these beggars never let on
how much they know. Say, Dick, you talk their lingo; ask him where he
comes from.'

So adjured, old Dick Wharton supplied his guest with fish, bread, and tea,
all of which he took without a word, and then Dick began to question him.

The Indians had broken up their fishing-camp, the Redskin said; their
medicine-man had advised them to. Oh, yes, it was a good season, and there
were lots of fish there yet, but the medicine-man had seen a bird, and the
tribe could not stay any longer.

'Seen a bird!' cried old Wharton; 'well, I reckon he sees a good many
birds in a day; but what kind of a bird was this to frighten the whole tribe
from fishing and gambling?'

'The tribe was not frightened, O white-skin,' replied the Indian with
dignity; 'but they knew that the bird which Teeveevex saw was the bird of
doom, which preys on the tribes of men, and the Crows have hidden until the
danger is passed.'

'But what sort of a bird is the bird of doom?' persisted Wharton.

'Only Teeveevex has seen it,' replied the chief, 'but its white wings are as
the clouds which contain the rain-storms, and it rushes through the sky like a
star falling from its throne.'

'Bunkum!' muttered Texan, and, low as he muttered it, a spark seemed


suddenly to kindle and as suddenly to die out in the watchful eye of the
savage. 'I'll bet the Blackfeet are going to have a lively time of it, unless
they're going to do a bit of horse-stealing at Rosebud.'

'What is the name by which the braves call you?' asked Wharton.
'The men call me the Great White Rabbit,' replied the chief proudly.

'Not a bad name either for a hare-lipped one,' muttered Frank.

The Indian could not have understood what was meant, but he saw the
smile, and gave Frank one of his ugly looks.

That sturdy young Englishman stared coolly at him, remarking to Snap,


'It's an engaging young thing when it's pleased, isn't it, Snap? And, oh Lord,
what a mouth for a fish dinner!' he added as the savage filled up the vacuum
between his jaws with about half a pound of trout.

'Ask him how old he is,' said Snap, and Wharton repeated the question.

The chief thought for a moment, and then held up five fingers solemnly.

'Oh, you be hanged!' cried Towzer. 'Why, the beggar's laughing at us. A
nice, tender, five-year-old you are, aren't you, my beauty?' And the boys
laughed in concert.

'He is right enough, though,' said Wharton; 'with these chaps each finger
stands for ten, and I don't suppose that he is more than fifty.'

After eating everything which the whites had left, and begging for a
charge or two of powder, the cowboys' visitor got up and left without a word
either of thanks or adieu.

'Well,' said Towzer, 'that twopence which I presume our friend's mamma,
Mrs. Doe Rabbit, spent on her son's manners doesn't appear to have been a
good investment.'

'Lord bless you, you don't expect thanks from an Injun, do you?'
remarked Wharton; 'like enough that chap will put a ball in you if he gets a
chance, and I should be very much surprised if either of your grizzlies has its
hide on to-morrow. If it has, old Buck Rabbit, or whatever he calls himself,
won't be to blame, you bet!'

And sure enough, when Snap and Texan went up next morn (rather late, it
is true), both bear-skins had gone, and the place, so Texan said, 'stunk of
Injuns.'

When Snap and Texan got back without their bear-skins old Wharton had
the ponies packed, and 'the Judge' had made all preparations for a start.

'So Buck Rabbit got those skins, did he?' asked Wharton. 'Well, I'll
forgive him, whatever Snap says, if that's all the hair he raises this fall.'

'Yes, you may say that,' Texan added grimly. 'I've been here some while
now, but I never knowed those Crows give up their summer gamble, and
bust me if I think they'll feel inclined to lie idle now that they have been
skeered out of their fishing-camp.'

'That being so,' said Dick, 'it seems to me you mout as well lead them off
our trail a bit. Don't let them sight you between this and Rosebud, and
maybe, if Buck Rabbit didn't count the horses, he'll think, when he sees the
trail of all them ponies, that we've all gone back to Rosebud.'

'And how about Rosebud, Dick?' asked Texan.

'Oh, I reckon Rosebud can look after itself, leastways it could when I was
theer,' replied the old foreman; and Texan and the Judge nodded approvingly,
and murmured with emphasis 'You bet!'

'Then you'll be back in spring for the cows?' asked Texan.

'Well, we'll do our possible,' replied Wharton, busy with the Cradle's lash-
rope; 'if we don't turn up you'll understand that we're wiped out, and "the
boys" can divide my band amongst 'em.'

'The boys won't none of 'em hanker after their share of that band, Dick,'
replied Texan, shaking the old man's hand. 'Good luck to you!'

'So long!' cried the Judge. 'Keep your eyes skinned at night, pard!'

And with the bell of the leading pack-animal tinkling merrily the two
boys, and all the ponies save the Cradle and another, disappeared among the
trees on the back track.
Dick and the boys stood looking along the trail for some time after their
friends were out of sight. Now and again they could hear the bell or a cry
from Texan or the Judge to one of the self-willed ponies, but by degrees they
passed out of earshot as out of sight.

'I guess we'd better tramp,' said Dick, turning to the three young
Englishmen, over whom a certain sense of loneliness had been stealing.

For the first time they realised what this adventure meant. They saw now
that for the next four months at any rate they were entirely dependent upon
their own efforts for all the necessaries of life. They were only four men,
armed and strong, it is true, isolated among the great things of Nature—
mountains and forests, and by-and-by ice and snow and tempest—and cut
off from railways and the civilised world, and bound to die if they could not
find food and make shelter for themselves. Old Dick, used all his life to
depend on his own right hand for everything he wanted, probably only felt a
bit of a wrench at parting from his old comrades and saying good-bye to his
old position of foreman.

The boys felt a good deal more than that. Those two rough-riders, driving
their string of pack ponies before them, were to them the world, or at any
rate their last glimpse of it.

'You had better lead "the Cradle," Snap,' cried Wharton, 'but I reckon
we'll all have to swim at the ford. Your friends can swim, I suppose?'

'Like fish, Dick,' replied Frank for himself and brother.

'Come on, then,' said the old man, and with a long, swinging stride the
four started on their hundred-mile walk.

All four were in mocassins, flannel shirts, and pants of blue jean. On their
heads they wore the usual cowboy hat, a wide light-coloured sombrero. Snap
carried his rifle, as the best shot of the party, but the others had tied their
rifles with their coats and blankets on the pack-animals' backs.

The river when they reached it was not as full as Wharton had expected,
still for a few paces in the middle horses and men had to swim.
As they stood shaking themselves on the further bank, Towzer looked
ruefully at his own draggled appearance and remarked:

'I believe I've got my stockings wet! Don't you think, Frank, mother
would like us to change them?'

There was a laugh among the boys, and then as they tramped through the
grimy, burnt forest, with its charred stumps and black, leafless branches,
their thoughts went back to Fairbury.

The thought acted on the different natures differently. Towzer felt


inclined to sit down and cry, and, as that would not do at any price, he began
to whistle an old nigger-minstrel melody. A hard, dogged expression came
into Frank's face. He would rather have been squire of Fairbury, but he
meant to do his duty here all the same. And Snap! well, Snap's eyes lit up,
and his head was very high in the air. He didn't know that he was leading a
pack pony, and that old Wharton was wondering why the boy's eyes looked
so bright and moist. Snap didn't see the grey old forest, or think of the years
of daily labour, but he saw a bright picture with two sides to it: on the one a
wide stretch of country dotted everywhere with cattle which bore his brand,
and on the other the steps of the old hall at Fairbury, and the Winthrops, dear
old Admiral Chris, and the little mother; Fairbury had been bought back, and
that sweet, grey-haired woman had her hand in his, and was saying, 'I trusted
you, Snap, all along; I knew my brown boy would go straight.'

Well, it was a dream, and Snap an optimist and a bit of a poet, and
perhaps in nine cases out of ten such dreams only lead to disappointment;
but if you are prepared to meet with disappointment, a beautiful dream is no
bad thing to beguile a long march.

The country through which the boys were now travelling was as desolate
and uncanny as anything which the world can show. They were crossing a
belt of forest between the forks of a great stream, one arm of which they
crossed in the morning. Between the two streams a great fire had raged some
years ago, and range after range of rolling hills lay before them covered with
tall trees charred to a cinder, yet standing upright still—grey, unburied
skeletons of the past. In some places a tree which had once been nearly two
hundred feet in height still reared a great grey spire towards heaven, and yet
a few yards from the ground you could see that fire and weather between
them had eaten the trunk almost through, so that its balance alone seemed to
keep it upright. All through the brûlé, as this burnt forest is called, the trails
are blocked by fallen timber. At every breeze a score of them come crashing
down, and hardly a minute goes by without a snap like a rifle-shot to remind
you that it is merely by an interposition of Providence that each of the great
pines along your path has not fallen upon you as you passed. The difficulty
of getting pack animals through a forest of this kind is considerable,
although they will jump and crawl like cats; and the walking is weary work
even for the strongest man, where at one moment you have to balance along
the stem of a fallen pine, or climb over a log ten feet high, and the next have
your pants caught by the point of a sharp rampike which tears them to shreds
and perhaps takes a foot or two of skin with it.

'I am afraid Texan was right,' said Dick as they plodded along, while the
sun was setting slowly in the west, 'those clouds are coming up uncommon
fast, and it's main dark for three o'clock.'

Winthrop was leading 'the Cradle,' and Towzer was walking alongside of
him, and when Dick spoke he spoke to Snap, who had fallen a bit behind.

'Don't you agree, Snap?' he said after a pause, and as no answer came he
looked round.

'Hulloh! Why, where in thunder have you got to?' he cried. 'Here! hold on
there in front. Where's Snap?'

The boys pulled up and looked round. Not five minutes before they had
seen him; now, though they could see plainly amongst the grey, bare poles,
there was no sign of him.

'Snap! hi, Snap!' they cried; and faint and far away an echo seemed to say
'halloa.'

'Was that an answer?' said Dick; 'here, dang your skin, hold up there,' he
added, giving 'the Cradle' an angry dig in the ribs, to induce that animal to
stop pawing the ground and snorting.
'Now shout agin, Frank, and mebbe this brute will let us hear if he
answers.'

'Snap! halloa, halloa there, Snap!' cried Frank, and again from far away
came an answering halloa, very feeble and faint, but still recognisable as
Snap's voice.

'Why, he's underground,' said Towzer.

'Yes, I reckon he is,' said Dick; 'I hope he ain't much hurt.'

'Why, do you know where he is?' asked both boys.

'Not exactly, but if you'll give me thet lash-rope we'll, maybe, find him
pretty soon. It's lucky we missed him so soon,' he added.

Turning back, the old man walked along the trail, calling Snap by name
from time to time, the answer getting plainer as he advanced, but still
proceeding apparently from somewhere under their feet.

'Here he is,' remarked Wharton at last, 'and a pretty dark hole it is, too.
Are you hurt any, Snap?' he inquired, leaning over a log and looking down
on the other side.

'No, I'm all right,' said the voice, 'but I can't get out.'

'Lay hold of that,' replied Wharton, lowering the rope, 'and we'll pretty
soon haul you out.'

When the Winthrops came up this was what met their gaze. The whole
floor of the forest was composed of fallen trees and dead logs, in most cases
overgrown with moss and bushes, which in their turn had been burnt or
scorched. For centuries the trees had grown and fallen, rotted or refused to
rot, and over them the fresh forest had grown, until in many cases they
formed a solid soil of rotted wood and debris. Here and there, however,
where a few great trees had fallen and had not yet rotted, a thin crust, as it
were, of boughs and soil and debris had formed above, and through such a
crust as this Snap had tumbled into what Towzer called the basement of the
forest, a dark, damp, underground hollow, in which in places you could
travel upright for thirty or forty yards under a bridge of fallen timber. Out of
a place of this kind Snap was hauled, very black and grimy, and as hoarse as
a crow with shouting, but otherwise unhurt.

'We had better push on at once,' said Wharton as soon as he was sure that
his friend was unhurt. 'I don't like the look of the evening a bit, and should
be thankful if we could get under the lee of some big boulders I know of, a
few miles further on, before the storm breaks.'

'It does look bad, doesn't it?' said Frank; 'however, a little rain would do
no harm, as we shall not strike water to-night, and we all want a wash badly,
specially Snap.'

'If this storm catches us in the brûlé, we shan't want washing any more,'
was Dick's gloomy reply; and, though the sky—covered with long fleecy
storm-clouds, and full of an angry yellow light—did not look reassuring, the
boys all thought that for once Dick was taking an unnecessarily black view
of their chances.

The boys were still digesting Dick's last speech when there came a tiny
whisper through the trees. It was not anything more. Just a faint little wind
like a sigh; and yet three or four great trees, which had kept their balance for
years, came down before it with a crash which made even Dick's cheek
blanch.

'Caught, by thunder!' cried he. 'Boys, we've only one chance; leave them
ponies and follow me.'
IN THE BRÛLÊ
Not understanding the danger, the boys could not help seeing that it was
real, by the old man's manner, and the speed with which he darted back
along the trail. As he passed 'Cradle,' Snap noticed that that intelligent beast
turned of his own accord and followed his human companions. As they ran,
another faint wind came, and another half-dozen great trees thundered down,
and one of them right across the path between Dick and his friends. One of
its boughs flew up and struck Frank across the face, leaving a long black
mark and drawing a bright stream of blood.

For a moment the boys recoiled aghast; but Wharton's voice woke them
to a fresh effort.

'Run, run, tear and ages! will you run?' he shrieked, and one after another
the boys scrambled over the carcase of the great tree and reached Dick's
side.

Dick was on his knees beside the hole from which he had extricated
Snap. The good old fellow, though he knew the danger, meant to see
everyone else safe before he thought of himself.

'Here, young 'un,' he cried to Towzer, 'get hold of my fist. Now then,
down you go,' and he lowered the boy as far as he could into the hole.

'Let go and drop,' he cried. 'Are you all right?' he added.

'All right,' said Towzer's voice from somewhere beneath their feet.

'Now then, Frank,' said Dick; and one after another he let the boys down,
and a moment after dropped down amongst them.

'Great Scott! how it shakes the wind out of you,' he muttered, picking
himself up, 'I didn't know it was so far.'

Just then a peal of thunder drowned their voices, and after it came the rain
in torrents, driven by a perfect gale of wind. Even where the boys were the
rain came in bucketfuls, and the red lightning lit up their subterranean shelter
until they could see the black logs above their heads, like the gigantic beams
in some old English hall. But the loud thunder echoing amongst the cliffs
beyond the river, and the hissing rain, and every other sound was drowned
when the wind arose, for after the first rush of the wind it seemed as if the
end of the world had come, or as if, at the very least, some great battle like
Hohenlinden was being fought right over their heads. Tree after tree came
crashing to the ground and, as it fell, dragged down others with it. Now they
would fall one after another with loud reports as if a regiment of giants were
file-firing, and again a great wave of sound, a very volley of the heaviest
artillery, would make the ground rock with its awful roar.

'Thank God, we got here in time,' said old Dick reverently; 'I guess there
won't be a tree standing when this storm stops, and those poor wretched
ponies will be pounded small enough for sausage meat!'

'Do you think they can't escape, Dick?' asked Frank; 'our rifles won't be
good for much, then.'

'No,' replied Wharton, 'except, maybe, for old iron or chips to light a fire
with. By the way, who has the matches?'

'They are on the packs,' said Towzer.

'What, haven't any of you a match about you?' asked Dick.

'No, I haven't,' said Frank.

'Nor I,' added Towzer.

'Haven't you, Snap?' asked Dick. 'What are you thinking of, boy?' Dick
added.

'No, I haven't a match, Dick. I was thinking what a cur I was to leave
poor old Cradle, and how piteous he looked as I passed him; but I had no
notion what I was leaving him to,' replied Snap sadly.

'Yes, it is a pity. He was a good horse, but there are plenty better, and,
besides, we hadn't a rope strong enough to lower him into this hole, even if
we had had time to try it; and then I'm not sure as he'd have let us do it,' said
Wharton; adding, after a while, 'I guess the storm is stopping, but it's a poor
camp we shall have to-night, without a fire.'
Before long the storm stopped; our friends down below could feel that the
air was fresh and sweet, and that the evening sun was shining brightly over
everything. By tying a little log on to the lash-rope and throwing it over one
of the beams which formed the roof of their shelter, our friends made
themselves a ladder, and one by one climbed up from the darkness to
daylight again.

CHAPTER XVIII

THE LOSS OF 'THE CRADLE'

When they did so, what a change had taken place! An hour and a half ago
thousands of burnt trees, stretched upon all sides, blocked the view and
formed a forest of skeletons. Now every high head was levelled, every tall
grey spire laid low. Like a wheatfield beaten down in autumn lay the burnt
forest, but, unlike that, no sun could ever raise it up again. When years
should have passed and the dead trees returned to earth, another forest would
spring up where the pines had stood—not a forest of bright larch and tall
pines, but, oddly enough, a forest utterly alien to the one which had so long
covered the ground. Beech and birch, and maple or poplar, would grow
green in spring and shed their leaves in autumn where the winds once
whistled and the snows lay amongst the great evergreens.

As Snap looked at the levelled forest the words came somehow to his
lips, 'This is the Lord's doing; and it is marvellous in our eyes.' Lifting his
hat, he looked up to the bright sun, and even the grim old cowboy was not
ashamed to follow his example.

Picking their way with difficulty among the chaos of fallen trees, the
boys' ears were greeted by a low whinny.

'It's the Cradle, poor old chap!' cried Snap. 'Can it possibly be that he is
alive?'
'It's a pity if he is, my lad,' said old Wharton, 'for he'll only be calling you
to shoot him out of his pain. He's most sure to have a leg broke or his back
smashed.'

'But he hasn't, though, have you, old chap?' shouted Snap, who had
scrambled breathlessly over the logs to the spot from which his old horse
had called to him.

'But, Dick,' the boy added, 'how on earth are we ever going to get him out
of this?'

And he well might ask. 'The Cradle' couldn't stir, and no wonder. He had
seen the danger as well as his masters, and with that wonderful instinct
which sometimes serves a beast better than our reason serves us had taken
the best means he could to escape it. Finding himself deserted, he crouched
down on the lee-side of the great pine which had fallen across Snap's path,
and by tucking his knees under him had managed to crawl almost under its
projecting side like a rabbit. Tree after tree had crashed over him, but the
great butt against which he crouched was solid, and now when Snap found
him he was absolutely untouched, but shut in as if in a cage by the great
fragments of trees which had broken just over his head. By taking off his
pack (which contained two out of the three rifles), and by the free use of an
axe, which was also attached to his pack, our friends at last set the old pony
free, and they all laughed heartily as they watched him crawling almost on
his belly amongst the timber, even lying down and pushing himself under a
log on his side, until the cunning old rascal was rubbing his head on his
master's sleeve again.

The other pony they found later on, but, as Dick said, no one but Snap
could have had such luck as not to lose his horse in the late storm. The
second pony was crushed to pieces. The first tree that struck the poor brute
had broken its spine as if it had been a dry twig, and crushed it as a cart-
wheel would crush a rat. The pack, too, was crushed and buried under the
trees, the only thing which had escaped being Towzer's rifle, which had got
torn away from its lashings before the pony was killed.

'Well, we might have done a lot worse,' said Wharton; 'there are all the
rifles safe, and old Cradle has the flour and a frying-pan, the axe and the
kettle. We shall do very well.'

'Much good the kettle will be,' said Towzer; 'the tea is somewhere under
that dead horse, and so are the beans and bacon.'

'Yes,' added Frank, who had been hunting about amongst the packs, 'and
there isn't a match that will strike amongst us.'

'Never mind that,' said Wharton. 'You have the only muzzle-loader
amongst us, haven't you, Frank? Hand it here. We'll camp just where we are.'

Frank obeyed, and the old man chose a spot where some fallen trees
formed a kind of square, the centre of which he cleared from debris, and
then, taking an axe, he just trimmed off the wet outside of one of the great
trunks, and made a big hollow in the dry, half-burnt tinder. This done, he
greased a piece of rag, and, having 'salted it over,' as he expressed it, with
grains of gunpowder, he rammed it loosely into one of the barrels of Frank's
muzzle-loader, and then fired it into the hollow he had prepared. After one or
two tries he succeeded; the rag caught fire, and set fire to the dry wood, and
it kept the boys very hard at work with their axes and a rope to cut off and
separate the huge log which formed their camp-fire from the logs around it.

Whilst they were thus employed old Wharton had produced his knife and
skinned part of the pony's quarters, which were still protruding from under
the tree which had killed him.

'What are you at, Dick?' asked Towzer.

'Just cutting you a steak, my boy,' was the reply; 'it's a pity, though, that
this pony was born so long ago.'

No one fancied his supper much that night, but, after all, the poor old
Cradle was the only one of the party who did not share in it. He went
supperless to bed; but all the boys confessed that Dick was not a bad cook,
and that pony-steak was very good eating when you had nothing better.

It took our friends two whole days to get out of that ruined forest, and
two days of such hard work that Dick, toughened by years of hardship, was
the only one who had strength or courage to attempt to light a fire or cook at
night. Indeed, if it had not been for Dick, I doubt if even hunger would have
induced the boys to make the effort necessary to get themselves some food;
and without a good meal at night none of them would have had strength to
escape from that interminable tangle of twisted boughs and fallen trunks.

All this time 'the Cradle' had no food. There was nothing to give him,
and, except for the rain-puddles, black and thick with charcoal, the party had
no water. The men drew their belts and old Cradle's girth tighter every
evening, and a more slender-looking or famished party, black and wearied
and ragged, never came out of a burnt forest than the wanderers from
Rosebud when on the morning of the third day they issued from among the
timber and plunged into the welcome stream which made the north-west
boundary of this land of desolation.

On the far side were green forests and a stretch of yellow grass, which
seemed to revive all 'the Cradle's' worn-out energies. He needed no
persuasion to make him plunge into the stream, no hobbles to keep him safe
when he reached the further shore.

A bundle of matches, some of which had escaped the rain, had been
found, so the men sat down, lit a fire, and as they baked themselves cakes
upon the coals they watched with pleasure the steady, business-like way in
which the old pony made up for lost time.

When they had all washed and fed they made another march of about
fifteen miles, which brought them to the edge of that country in which Dick
hoped to feed his cattle.

'Of course,' said he, 'we shall have to come a long way round; you
couldn't drive cattle through that wilderness,' pointing back to the brûlé; 'but
it is a good country, isn't it?'

And it was! A few miles from where they were camped was a range of
high, rocky peaks, with little or no timber upon them. These peaks were
quite bare, and one in particular rose like a great pulpit high above the rest,
the centre of the highest group of peaks. Up to the foot of this little group of
mountains ran Dick's range, a succession of rolling swells of grass-land,
studded over with groves and bunches of the red bull pines. It was a
splendid, park-like country, and many a group of deer cantered away from
them as they rode through it.

'You might as well shoot us something for supper, Snap,' remarked


Wharton; 'I guess you're tired like the rest, but you won't have any trouble to
speak of in getting a haunch of venison in this here Bull Pine Park of mine.'

'Of ours, Dick!' corrected Towzer, grinning.

'Right you are,' replied the old man; 'but I'm not a-goin' to have any
sleeping partners in our firm, so just you get up off of your back, young man,
and get some bread made while I cut wood for the night-fire.'

Towzer made a grimace and rolled over on to his face with a yawn, but
eventually shook himself and began to make preparations for baking.

'Snap ought to make the bread, by rights,' he grumbled, 'he is such a


stunner at the use of baking-powder.'

'Had you there, Snap,' said Frank; 'the young 'un has got "a rise" out of
you this time.'

'Quite fair, too,' said Dick. 'I guess Snap got a pretty considerable rise out
of the boys at Rosebud with that tarnation Borwick of his.'

But Snap pretended to be out of hearing, and was soon lost among the
timber.

There was a good deal to do about the camp that afternoon. All the pack
wanted overhauling and cleaning. Charcoal and wood-ash took too
prominent a place in the composition of everything in the Cradle's load, from
tea to tobacco. The frying-pans had lost their handles, and these had to be
replaced by others extemporised from a split stick; the spoons had been lost,
so others had to be made from birch-bark; the soup-kettle was lying as flat as
a pancake under the dead pony in the brûlé, so another had to be made, and
this, too, was of birch-bark.

'How are you going to boil that, Dick, without burning a hole in the
bottom?' asked Frank.
'By putting the fire inside instead of out, my lad,' replied he.

'Oh yes, old boy, I twig, and the soup outside instead of in!' cried Towzer.
'Quite simple, isn't it, Frank?'

Dick laughed. Towzer's cheek amused him.

'Here is my heating apparatus, anyway,' he said, raking some red-hot


pebbles out of the ashes. 'Now you fill the bark-kettle with cold water.'

Towzer obeyed.

'Now, you see,' said Dick, suiting the action to the word, 'in go the
pebbles and the water begins to sing; as soon as the first lot get dark and
cool, out they come, and in goes another lot. If you pour the water over your
toes by accident, you'll find it piping hot, I promise you; and when you've
done doing that and can spare time to look at the bottom of the kettle, you'll
find that it ain't got no hole in it.'

'Bully for you, Dick,' assented Towzer, 'your youth doesn't appear to have
been as much wasted as I thought it had been.'

'Why don't you give the brat a taste of the lash-rope, Dick? it would do
him a world of good.'

'I make a practice never to squash a 'skeeter as long as it only buzzes,'


replied Wharton, laughing; 'when it stings, I'm theer, you bet.'

'Snap doesn't seem to be having any luck with the deer,' Frank remarked
after a while.

'No,' replied the other; 'I've not heard his rifle myself, but I reckon he's
got a bluff between us and him, and then, like enough, we wouldn't hear with
that chatterin' young jay-bird anywheres near.'

As the sun was setting, Snap was seen coming down a long glade towards
the camp.
'Don't carry his tail in the air, does he?' remarked Towzer. 'I don't believe
he has got a thing.'

'He can't have been out three hours here without getting a shot, I'll lay a
wager,' said Wharton.

'He's all right, I can see something hanging on his shoulders,' said Frank.

'So can I now,' added Wharton, 'but it's not venison, it's only fool-hens,
I'm thinking.'

'A jolly sight better too,' remarked Towzer, smacking his lips greedily.

'What sport, Snap?' they asked as he came up.

'Well,' replied the hunter, throwing down three big blue grouse by the fire,
and leaning on his rifle, 'that's the bag.'

'Wal! but you don't mean to say you didn't see any deer?' exclaimed
Wharton. 'Why, man, the park is full of them. Couldn't you hit 'ein?'

Snap put his finger in the muzzle of his Winchester, and held it up
unsoiled.

'Never fired a shot, Dick,' he said. 'I stoned those fool-hens coming home,
and my arm regularly aches with shying at them; but I can't understand about
the deer.'

'Why, how do you mean?' someone asked.

'Well, going from here towards what you call the "Lone Mountain," the
wind would be right for me, wouldn't it?'

'Slap in your teeth; couldn't be better, what there is of it,' replied Dick.

'Well, and yet every deer I saw had its head up; almost every one was
going at a canter; and, though, I dare say, at one time and another, I must
have seen forty, I never got what I should call a fair shot. You see, we've no

You might also like