100% нашли этот документ полезным (1 голос)
11 просмотров

Programming 101: Learn to Code Using the Processing Programming Language, 2nd Edition Jeanine Meyer - Quickly download the ebook to explore the full content

Документ представляет собой информацию о книге 'Programming 101: Learn to Code Using the Processing Programming Language, 2nd Edition' авторства Жанин Мейер, доступной для скачивания на сайте ebookmeta.com. В книге рассматриваются основы программирования с использованием языка Processing, включая концепции, функции и взаимодействия. Также представлены ссылки на другие рекомендуемые электронные книги по программированию и смежным темам.

Загружено:

bjeldebawule
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
100% нашли этот документ полезным (1 голос)
11 просмотров

Programming 101: Learn to Code Using the Processing Programming Language, 2nd Edition Jeanine Meyer - Quickly download the ebook to explore the full content

Документ представляет собой информацию о книге 'Programming 101: Learn to Code Using the Processing Programming Language, 2nd Edition' авторства Жанин Мейер, доступной для скачивания на сайте ebookmeta.com. В книге рассматриваются основы программирования с использованием языка Processing, включая концепции, функции и взаимодействия. Также представлены ссылки на другие рекомендуемые электронные книги по программированию и смежным темам.

Загружено:

bjeldebawule
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
Вы находитесь на странице: 1/ 58

Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.

com

Programming 101: Learn to Code Using the


Processing Programming Language, 2nd Edition
Jeanine Meyer

https://ebookmeta.com/product/programming-101-learn-to-code-
using-the-processing-programming-language-2nd-edition-
jeanine-meyer/

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com


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

The Essential Guide to HTML5: Using Games to Learn HTML5


and JavaScript 3rd Edition Jeanine Meyer

https://ebookmeta.com/product/the-essential-guide-to-html5-using-
games-to-learn-html5-and-javascript-3rd-edition-jeanine-meyer/

ebookmeta.com

C Programming Learn to Code 1st Edition Sisir Kumar Jena

https://ebookmeta.com/product/c-programming-learn-to-code-1st-edition-
sisir-kumar-jena/

ebookmeta.com

Programming for Absolute Beginners: Using the JavaScript


Programming Language 1st Edition Jonathan Bartlett

https://ebookmeta.com/product/programming-for-absolute-beginners-
using-the-javascript-programming-language-1st-edition-jonathan-
bartlett/
ebookmeta.com

Remember Me Ravenswood book 2 1st Edition Mary Balogh

https://ebookmeta.com/product/remember-me-ravenswood-book-2-1st-
edition-mary-balogh/

ebookmeta.com
Plant MicroRNAs and Stress Response 1st Edition Deepu
Pandita Anu Pandita

https://ebookmeta.com/product/plant-micrornas-and-stress-response-1st-
edition-deepu-pandita-anu-pandita/

ebookmeta.com

Pathfinder RPG Advanced Player s Guide P2 2nd Edition


Paizo Inc

https://ebookmeta.com/product/pathfinder-rpg-advanced-player-s-
guide-p2-2nd-edition-paizo-inc/

ebookmeta.com

Sharpening Mathematical Analysis Skills (Problem Books in


Mathematics) Sînt■m■rian

https://ebookmeta.com/product/sharpening-mathematical-analysis-skills-
problem-books-in-mathematics-sintamarian/

ebookmeta.com

Team Roles at Work 3rd Edition R. Meredith Belbin

https://ebookmeta.com/product/team-roles-at-work-3rd-edition-r-
meredith-belbin/

ebookmeta.com

English Folk Poetry Structure and Meaning Roger Dev.


Renwick

https://ebookmeta.com/product/english-folk-poetry-structure-and-
meaning-roger-dev-renwick/

ebookmeta.com
Good Good Father Chris Tomlin

https://ebookmeta.com/product/good-good-father-chris-tomlin/

ebookmeta.com
Programming 101
Learn to Code with the Processing
Language Using a Visual Approach
Second Edition

Jeanine Meyer
Programming 101: Learn to Code with the Processing Language Using a Visual
Approach
Jeanine Meyer
Mt Kisco, NY, USA

ISBN-13 (pbk): 978-1-4842-8193-2 ISBN-13 (electronic): 978-1-4842-8194-9


https://doi.org/10.1007/978-1-4842-8194-9

Copyright © 2022 by Jeanine Meyer


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: James Robinson-Prior
Development Editor: James Markham
Coordinating Editor: Jessica Vakili
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 NY Plaza,
New York, NY 10004. 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]; for reprint,
paperback, or audio rights, please e-mail [email protected].
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 the Github repository: https://github.com/Apress/Programming-101. For more detailed information,
please visit http://www.apress.com/source-­code.
Printed on acid-free paper
To my family, who inspire and teach me.
Table of Contents
About the Author�����������������������������������������������������������������������������������������������������xv

About the Technical Reviewer�������������������������������������������������������������������������������xvii


Acknowledgments��������������������������������������������������������������������������������������������������xix

Introduction������������������������������������������������������������������������������������������������������������xxi

Chapter 1: Basics����������������������������������������������������������������������������������������������������� 1
Abstract����������������������������������������������������������������������������������������������������������������������������������������� 1
Programming Concepts���������������������������������������������������������������������������������������������������������������� 3
Programming Languages and Natural Languages������������������������������������������������������������������ 3
Values and Variables��������������������������������������������������������������������������������������������������������������� 3
Functions��������������������������������������������������������������������������������������������������������������������������������� 5
Specifying Positions and Angles���������������������������������������������������������������������������������������������� 6
Colors�������������������������������������������������������������������������������������������������������������������������������������� 7
Development Environment������������������������������������������������������������������������������������������������������ 7
Role of Planning���������������������������������������������������������������������������������������������������������������������� 8
Under the Covers�������������������������������������������������������������������������������������������������������������������������� 8
Processing Programming Features����������������������������������������������������������������������������������������������� 9
Processing Development Environment������������������������������������������������������������������������������������ 9
Functions������������������������������������������������������������������������������������������������������������������������������� 11
Angles������������������������������������������������������������������������������������������������������������������������������������ 12
Implementing Hello, World���������������������������������������������������������������������������������������������������������� 14
Implementing the Daddy Logo���������������������������������������������������������������������������������������������������� 22
Planning��������������������������������������������������������������������������������������������������������������������������������� 22
Daddy Logo Program������������������������������������������������������������������������������������������������������������� 25

v
Table of Contents

Things to Look Up����������������������������������������������������������������������������������������������������������������������� 29


How to Make This Your Own������������������������������������������������������������������������������������������������������� 29
What You Learned����������������������������������������������������������������������������������������������������������������������� 30
What’s Next��������������������������������������������������������������������������������������������������������������������������������� 31

Chapter 2: Interactions������������������������������������������������������������������������������������������� 33
Abstract��������������������������������������������������������������������������������������������������������������������������������������� 33
Note��������������������������������������������������������������������������������������������������������������������������������������� 33
Programming Concepts�������������������������������������������������������������������������������������������������������������� 35
Events������������������������������������������������������������������������������������������������������������������������������������ 35
Randomness�������������������������������������������������������������������������������������������������������������������������� 36
Displaying Images from Files������������������������������������������������������������������������������������������������ 36
Calculations, Including Built-in Functions����������������������������������������������������������������������������� 36
Looping���������������������������������������������������������������������������������������������������������������������������������� 37
Processing Programming Features��������������������������������������������������������������������������������������������� 37
Note��������������������������������������������������������������������������������������������������������������������������������������� 38
Under the Covers������������������������������������������������������������������������������������������������������������������������ 41
Polygon Sketch Operation Overview������������������������������������������������������������������������������������������� 42
Implementing the Polygon Sketch���������������������������������������������������������������������������������������������� 44
Planning��������������������������������������������������������������������������������������������������������������������������������� 44
Polygon Sketch Program������������������������������������������������������������������������������������������������������� 47
Coin-Toss Sketch Operation Overview���������������������������������������������������������������������������������������� 49
Implementing the Coin-Toss Sketch������������������������������������������������������������������������������������������� 52
Planning��������������������������������������������������������������������������������������������������������������������������������� 52
Things to Look Up����������������������������������������������������������������������������������������������������������������������� 56
How to Make This Your Own������������������������������������������������������������������������������������������������������� 56
What You Learned����������������������������������������������������������������������������������������������������������������������� 57
What’s Next��������������������������������������������������������������������������������������������������������������������������������� 58

vi
Table of Contents

Chapter 3: Animation Using Arrays and Parallel Structures����������������������������������� 59


Abstract��������������������������������������������������������������������������������������������������������������������������������������� 59
More on the Sketches����������������������������������������������������������������������������������������������������������������� 59
Programming Concepts�������������������������������������������������������������������������������������������������������������� 64
Animation������������������������������������������������������������������������������������������������������������������������������ 65
Logical Operations����������������������������������������������������������������������������������������������������������������� 65
Arrays������������������������������������������������������������������������������������������������������������������������������������ 65
Parallel Structures����������������������������������������������������������������������������������������������������������������� 66
Compound Statements���������������������������������������������������������������������������������������������������������� 66
Pseudorandom Processing���������������������������������������������������������������������������������������������������� 66
Processing Programming Features��������������������������������������������������������������������������������������������� 67
Caution���������������������������������������������������������������������������������������������������������������������������������������� 67
Implementing a Bouncing Ball���������������������������������������������������������������������������������������������������� 71
Planning��������������������������������������������������������������������������������������������������������������������������������� 71
Program��������������������������������������������������������������������������������������������������������������������������������� 72
Implementing a Set of Three Bouncing Balls������������������������������������������������������������������������������ 74
Planning��������������������������������������������������������������������������������������������������������������������������������� 74
Program��������������������������������������������������������������������������������������������������������������������������������� 74
Implementing Pentagon Bouncing���������������������������������������������������������������������������������������������� 76
Planning��������������������������������������������������������������������������������������������������������������������������������� 76
Implementing Bouncing Polygons����������������������������������������������������������������������������������������������� 78
Planning��������������������������������������������������������������������������������������������������������������������������������� 79
Program��������������������������������������������������������������������������������������������������������������������������������� 79
Under the Covers������������������������������������������������������������������������������������������������������������������������ 82
Things to Look Up����������������������������������������������������������������������������������������������������������������������� 82
How to Make This Your Own������������������������������������������������������������������������������������������������������� 83
What You Learned����������������������������������������������������������������������������������������������������������������������� 83
What’s Next��������������������������������������������������������������������������������������������������������������������������������� 84

vii
Table of Contents

Chapter 4: Classes�������������������������������������������������������������������������������������������������� 85
Abstract��������������������������������������������������������������������������������������������������������������������������������������� 85
Programming Concepts�������������������������������������������������������������������������������������������������������������� 86
Classes���������������������������������������������������������������������������������������������������������������������������������������� 86
Phases of Operations������������������������������������������������������������������������������������������������������������� 87
Tolerance or Margin��������������������������������������������������������������������������������������������������������������� 88
Processing Programming Features��������������������������������������������������������������������������������������������� 88
Classes���������������������������������������������������������������������������������������������������������������������������������� 88
Definition of Images, Rectangles, and Ellipses���������������������������������������������������������������������� 90
Dynamic Arrays��������������������������������������������������������������������������������������������������������������������� 90
Tolerance and OK-So-Far Coding������������������������������������������������������������������������������������������ 92
Bouncing Objects Overview�������������������������������������������������������������������������������������������������������� 92
Implementing the Bouncing Objects������������������������������������������������������������������������������������������� 94
Planning��������������������������������������������������������������������������������������������������������������������������������� 94
Program��������������������������������������������������������������������������������������������������������������������������������� 96
Make Path and Travel Path Overview���������������������������������������������������������������������������������������� 100
Implementing the Make Path and Travel Path�������������������������������������������������������������������������� 103
Planning������������������������������������������������������������������������������������������������������������������������������� 104
Program������������������������������������������������������������������������������������������������������������������������������� 105
Jigsaw Overview����������������������������������������������������������������������������������������������������������������������� 109
Implementing the Jigsaw��������������������������������������������������������������������������������������������������������� 111
Planning������������������������������������������������������������������������������������������������������������������������������� 111
Program������������������������������������������������������������������������������������������������������������������������������� 114
Under the Covers���������������������������������������������������������������������������������������������������������������������� 125
Things to Look Up��������������������������������������������������������������������������������������������������������������������� 126
How to Make This Your Own����������������������������������������������������������������������������������������������������� 126
What You Learned��������������������������������������������������������������������������������������������������������������������� 127
What’s Next������������������������������������������������������������������������������������������������������������������������������� 127

viii
Table of Contents

Chapter 5: More Interactions�������������������������������������������������������������������������������� 129


Abstract������������������������������������������������������������������������������������������������������������������������������������� 129
More on the Sketches��������������������������������������������������������������������������������������������������������������� 129
Programming Concepts������������������������������������������������������������������������������������������������������������ 130
Ballistic Motion�������������������������������������������������������������������������������������������������������������������� 130
Character (char) Data Type vs. String Data Type����������������������������������������������������������������� 131
Use of Files�������������������������������������������������������������������������������������������������������������������������� 131
Case Statement������������������������������������������������������������������������������������������������������������������� 131
Elapsed Time����������������������������������������������������������������������������������������������������������������������� 131
Regular Expressions������������������������������������������������������������������������������������������������������������ 132
Processing Programming Features������������������������������������������������������������������������������������������� 132
The char Data Type�������������������������������������������������������������������������������������������������������������� 132
The keyPressed Function, key, and keyCode����������������������������������������������������������������������� 133
Table Files���������������������������������������������������������������������������������������������������������������������������� 133
The Switch Statement��������������������������������������������������������������������������������������������������������� 133
The millis and Other Time Functions����������������������������������������������������������������������������������� 135
The match Function for Regular Expressions���������������������������������������������������������������������� 136
ArrayList������������������������������������������������������������������������������������������������������������������������������ 136
Under the Covers���������������������������������������������������������������������������������������������������������������������� 136
Slingshot Operation Overview��������������������������������������������������������������������������������������������������� 138
Implementing the Slingshot Sketch������������������������������������������������������������������������������������������ 139
Planning������������������������������������������������������������������������������������������������������������������������������� 139
Programming the Slingshot Sketch������������������������������������������������������������������������������������� 142
Snake Operation Overview�������������������������������������������������������������������������������������������������������� 151
Implementing the Snake Sketch����������������������������������������������������������������������������������������������� 153
Planning������������������������������������������������������������������������������������������������������������������������������� 154
Programming the Snake Sketch������������������������������������������������������������������������������������������ 155
Image Test Operation Overview������������������������������������������������������������������������������������������� 163
Implementing the Image Test���������������������������������������������������������������������������������������������� 166

ix
Table of Contents

Things to Look Up��������������������������������������������������������������������������������������������������������������������� 171


How to Make This Your Own����������������������������������������������������������������������������������������������������� 171
What You Learned��������������������������������������������������������������������������������������������������������������������� 172
What’s Next������������������������������������������������������������������������������������������������������������������������������� 172

Chapter 6: Images and Graphics�������������������������������������������������������������������������� 173


Abstract������������������������������������������������������������������������������������������������������������������������������������� 173
More on the Sketches��������������������������������������������������������������������������������������������������������������� 174
Programming Concepts������������������������������������������������������������������������������������������������������������ 176
Images As Arrays of Pixels�������������������������������������������������������������������������������������������������� 177
Case Statement������������������������������������������������������������������������������������������������������������������� 177
Pixel Processing������������������������������������������������������������������������������������������������������������������ 177
The beginShape and endShape Vertex Functions��������������������������������������������������������������� 178
Changing the Coordinate System���������������������������������������������������������������������������������������� 178
Hue-Saturation-Brightness Color Mode������������������������������������������������������������������������������ 179
Changing Image Sketch Overview��������������������������������������������������������������������������������������� 179
Implementing the Image Transformations�������������������������������������������������������������������������������� 187
Planning������������������������������������������������������������������������������������������������������������������������������� 187
Programming the Image Sketch����������������������������������������������������������������������������������������������� 188
Origami Flower Graphic Overview�������������������������������������������������������������������������������������������� 191
Planning������������������������������������������������������������������������������������������������������������������������������� 191
Implementing the Origami Flower Sketch�������������������������������������������������������������������������������� 192
Programming the Origami Flower��������������������������������������������������������������������������������������������� 194
Programming the Hexagon with HSB Color Mode�������������������������������������������������������������������� 197
Under the Covers���������������������������������������������������������������������������������������������������������������������� 203
Things to Look Up��������������������������������������������������������������������������������������������������������������������� 204
How to Make This Your Own����������������������������������������������������������������������������������������������������� 205
What You Learned��������������������������������������������������������������������������������������������������������������������� 206
What’s Next������������������������������������������������������������������������������������������������������������������������������� 206

x
Table of Contents

Chapter 7: Using Files for Making a Holiday Card������������������������������������������������ 207


Abstract������������������������������������������������������������������������������������������������������������������������������������� 207
Programming Concepts������������������������������������������������������������������������������������������������������������ 208
Files������������������������������������������������������������������������������������������������������������������������������������� 208
Libraries������������������������������������������������������������������������������������������������������������������������������ 209
Fonts������������������������������������������������������������������������������������������������������������������������������������ 209
Callbacks����������������������������������������������������������������������������������������������������������������������������� 210
Feedback to Users��������������������������������������������������������������������������������������������������������������� 210
Processing Programming Features������������������������������������������������������������������������������������������� 210
Use of the Sound Library����������������������������������������������������������������������������������������������������� 210
Making and Saving an Image of the Current Window��������������������������������������������������������� 211
Use of Java Input/Output Library����������������������������������������������������������������������������������������� 212
Subclasses�������������������������������������������������������������������������������������������������������������������������� 213
Show Fonts Sketch Operation Overview����������������������������������������������������������������������������������� 214
Implementing the Show Fonts Sketch�������������������������������������������������������������������������������������� 216
Programming the Show Fonts Sketch��������������������������������������������������������������������������������� 217
Make Card Sketch Operation Overview������������������������������������������������������������������������������������ 218
Implementing the Make Card Sketch���������������������������������������������������������������������������������������� 223
Planning������������������������������������������������������������������������������������������������������������������������������� 223
Programming the Make Card Sketch����������������������������������������������������������������������������������� 225
Under the Covers���������������������������������������������������������������������������������������������������������������������� 231
Things to Look Up��������������������������������������������������������������������������������������������������������������������� 232
How to Make This Your Own����������������������������������������������������������������������������������������������������� 232
What You Learned��������������������������������������������������������������������������������������������������������������������� 232
What’s Next������������������������������������������������������������������������������������������������������������������������������� 233

Chapter 8: Combining Videos, Images, and Graphics������������������������������������������� 235


Abstract������������������������������������������������������������������������������������������������������������������������������������� 235
Programming Concepts������������������������������������������������������������������������������������������������������������ 235
Video������������������������������������������������������������������������������������������������������������������������������������ 236
Copying a Video������������������������������������������������������������������������������������������������������������������� 236

xi
Table of Contents

Processing Programming Features������������������������������������������������������������������������������������������� 236


Video������������������������������������������������������������������������������������������������������������������������������������ 237
Classes and Subclasses������������������������������������������������������������������������������������������������������ 238
Under the Covers���������������������������������������������������������������������������������������������������������������������� 238
Family Collage Operation Overview������������������������������������������������������������������������������������������ 239
Implementing the Family Collage Sketch��������������������������������������������������������������������������������� 242
Planning������������������������������������������������������������������������������������������������������������������������������� 242
Programming the Family Collage Sketch���������������������������������������������������������������������������� 243
Things to Look Up��������������������������������������������������������������������������������������������������������������������� 252
How to Make This Your Own����������������������������������������������������������������������������������������������������� 252
What You Learned��������������������������������������������������������������������������������������������������������������������� 257
What’s Next������������������������������������������������������������������������������������������������������������������������������� 257

Chapter 9: Word Guessing Game�������������������������������������������������������������������������� 259


Abstract������������������������������������������������������������������������������������������������������������������������������������� 259
More on the Sketches��������������������������������������������������������������������������������������������������������������� 259
Programming Concepts������������������������������������������������������������������������������������������������������������ 262
Implementing an Existing Application��������������������������������������������������������������������������������� 262
Testing and Scaling Up�������������������������������������������������������������������������������������������������������� 262
Displaying the State of the Game���������������������������������������������������������������������������������������������� 263
Displaying Text�������������������������������������������������������������������������������������������������������������������������� 264
Processing Programming Features������������������������������������������������������������������������������������������� 264
Note������������������������������������������������������������������������������������������������������������������������������������� 265
Operation Overview������������������������������������������������������������������������������������������������������������������� 266
Implementing the Word Game Sketches����������������������������������������������������������������������������������� 270
Planning������������������������������������������������������������������������������������������������������������������������������� 270
Programming the Word Game Sketches������������������������������������������������������������������������������ 272
Things to Look Up��������������������������������������������������������������������������������������������������������������������� 286
How to Make This Your Own����������������������������������������������������������������������������������������������������� 287
What You Learned��������������������������������������������������������������������������������������������������������������������� 287
What’s Next������������������������������������������������������������������������������������������������������������������������������� 288

xii
Table of Contents

Chapter 10: 3D������������������������������������������������������������������������������������������������������ 289


Abstract������������������������������������������������������������������������������������������������������������������������������������� 289
Programming Concepts������������������������������������������������������������������������������������������������������������ 292
Processing Programming Features������������������������������������������������������������������������������������������� 293
Under the Covers���������������������������������������������������������������������������������������������������������������������� 303
Rolling Ball at Alhambra Operation Overview��������������������������������������������������������������������������� 303
Implementing the Rolling Ball at Alhambra������������������������������������������������������������������������������� 304
Planning������������������������������������������������������������������������������������������������������������������������������� 304
Programming the Rolling Ball at Alhambra������������������������������������������������������������������������� 305
Rotating Cube Operation Overview������������������������������������������������������������������������������������������� 310
Implementing the Rotating Cube���������������������������������������������������������������������������������������������� 310
Planning������������������������������������������������������������������������������������������������������������������������������� 310
Programming the Rotating Cube����������������������������������������������������������������������������������������� 312
Things to Look Up��������������������������������������������������������������������������������������������������������������������� 318
How to Make This Your Own����������������������������������������������������������������������������������������������������� 319
What You Learned��������������������������������������������������������������������������������������������������������������������� 321
What’s Next������������������������������������������������������������������������������������������������������������������������������� 321

Appendix A: Introduction to p5.js������������������������������������������������������������������������� 323


Getting Started Using p5.js������������������������������������������������������������������������������������������������������� 323
Overview of Examples�������������������������������������������������������������������������������������������������������������� 325
Implementing Daddy Logo�������������������������������������������������������������������������������������������������������� 327
Implementing Fearless Girls vs. the Bull����������������������������������������������������������������������������������� 331
Implementing Rainbow Helix���������������������������������������������������������������������������������������������������� 336
W
 hat’s Next������������������������������������������������������������������������������������������������������������������������������� 341

Index��������������������������������������������������������������������������������������������������������������������� 343

xiii
About the Author
Jeanine Meyer is Professor Emerita at Purchase College/
SUNY. Before Purchase, she taught at Pace University and
prior to that was a manager and research staff member
at IBM Research in robotics and manufacturing. She also
worked as a research consultant at IBM for educational grant
programs.
She was moved to create this book because of a general
wish to make programming less mysterious and more
appealing while featuring the challenges. She enjoys
spending time with favorite pictures and video clips as well as producing programs. The
chance for a new edition provided a reason to explore p5.js, tools for using JavaScript
with features from Processing.
She is the author of five books and coauthor of five more on topics ranging from
educational uses of multimedia, programming, databases, number theory, and origami.
She earned a PhD in computer science at the Courant Institute at New York University,
an MA in mathematics at Columbia, and an SB (the college used the Latin form) in
mathematics from the University of Chicago. Recently, she has given lectures, in-­person
and remotely, connecting origami, mathematics, and computer science as well as the
use and misuse of math in the news. She is a member of Phi Beta Kappa, Sigma Xi, the
Association for Women in Science, and the Association for Computing Machinery.
Jeanine is trying but remains a beginner at Spanish and piano.

xv
About the Technical Reviewer
Joseph McKay is an associate professor of new media. He primarily teaches new
directions in virtual space, programming for visual artists, intro to physical computing,
hacking the everyday, senior seminar, and web development.
Joe’s work is focused on interactive art games. He makes games that have their roots
in fine art but are also fun and easy to play. He is currently working on a VR art game
with innovative locomotion.

xvii
Acknowledgments
Much appreciation to the subjects of the illustrations in this book, starting with my father
(Joseph) and including my mother (Esther), Aviva, Grant, Liam, and especially Annika.
Thanks to my children, Aviva and Daniel, for the photography, video, and computer
graphics work.
My students, teaching assistants, and colleagues always provide ideas, stimulation,
feedback, and advice. Thanks especially to Irina Shablinsky for her efforts in teaching me
Processing and how to teach Processing and introducing me to Takashi Mukoda. Thanks
to David Jameson, whose comments and concerns made me produce the “Under the
Covers” section for each chapter.
Thanks to the crew at Apress/Springer Nature, including for the second edition
James Robinson-Prior, Jessica Vakili, Dulcy Nirmala, Krishnan Sathyamurthy, and others
I do not know by name. Much appreciation to the past technical reviewers, Massimo
Nardone and Takashi Mukoda, and the technical reviewer for this edition, Joe McKay,
who brought his considerable talent and experience to the task.

xix
Introduction
Processing is a programming language built on top of another programming language
called Java. To quote from the https://processing.org page, “Processing is a flexible
software sketchbook and a language for learning how to code within the context of the
visual arts.” The term for a program in Processing is sketch. However, Processing can be
used to create applications that are far more than static sketches. You can use Processing
to create dynamic, interactive programs. It is a great tool for learning programming.
Though Processing was created for visual artists, it serves a broad population of
people. In particular, at Purchase College/SUNY, Processing has been an excellent first
computer programming language for our computer science/mathematics majors and
minors. It also serves students across the college, who take our CS I course to satisfy
one of the general education requirements. This experience has been reported in other
places. Processing and this text also are appropriate for self-study.
The ten chapters in this book share a common design and structure. My goal is to
introduce you to programming, focusing on the Processing language. In each chapter, I
explain general programming concepts and specific Processing features through the use
of one or more specific examples. The code and files such as image files are combined
as zip files and available at https://github.com/Apress/Programming-­101. I hope the
examples are entertaining; the goal, however, is not for you to learn the specific examples
but instead understand the concepts and features. The way to learn programming is to
make these examples “your own” and to go on to do a lot of programming.
The introduction to each chapter starts with a brief description of the concepts
and programming features used and the examples; then you need to be patient while
I provide background. Each chapter includes a discussion of general “Programming
Concepts” prior to plunging into the details. These are not limited to the Processing
language but are present in most programming languages. Presenting the concepts in a
general way might help you if you are coming to this book knowing another language or
you hope to move on to another language someday.
Next, I describe the “Processing Programming Features” that are used to realize
those concepts and produce the examples. This section will have actual code in it and
maybe short examples. This is a spiral approach, going from the general to the specific.

xxi
Introduction

A section called “Under the Covers” describes what Processing is doing for us behind
the scenes and the relationship between Processing and Java. This section appears
in different places in each chapter. It might be of more interest for readers who know
something or want to know something about Java, but I urge everyone to give it at least a
quick scan.
I then provide an overview of each example, with screenshots showing the operation
of the program. Please note that in some cases, I have modified the programs to obtain
the screenshots. I then go on to describe the implementation of the example, which
contains a “Planning” and a “Program” section. The “Planning” section is where I
describe my thought process. Programs do not spring into existence—at least for me—
not like Mozart composing a symphony, which was said to emerge all at once from his
mind. It is an iterative process for most of us. This section contains a table indicating the
relationship of the functions. The “Program” section includes a table with one column
for code and another column with an explanation of that line of code. These tables are
long and are not meant to be read as poetry or fine literature. Instead, skip around. Use
the function relationship table. If you download the code and try it out, you can use this
section to improve your understanding of the program. The most critical step is to make
changes, and I provide suggestions in the “How to Make This Your Own” section. This
set of sections is repeated for each example.
A section titled “Things to Look Up” will contain a list of Processing features related to
the ones described in the chapter. Processing is a large language, and it is growing. I can
show you only a small subset of the features, and each feature is used in one way, perhaps
using default values. You can and should consult other references to learn more. You
can look things up in multiple ways. For example, you can go to the website at https://
processing.org/reference/ and just keep that open. Alternatively, if you want to look up
how to draw a rectangle in Processing, it can be efficient to enter “processing.org rectangle”
into Google (or another search engine) or the address field of browsers such as Chrome to
retrieve a list of possible sites. It is best to use “processing.org” because “processing” is a
common English word. You can try “Processing rectangle,” but you will need to skip over
some sites that have nothing to do with the Processing language.
Remember that the goal of this book is not to teach you how to make my examples,
from peanut-shaped bald men to my versions of certain games to rotating 3D cubes with
photos of my grandchild, but to help you understand how to make your own programs!
Make small changes and then large changes. Make your own programs! Chapters will
close with two more sections: a brief review, “What You Learned,” and “What’s Next.”

xxii
Introduction

The book also has an Appendix describing what is called p5.js. This is a way to
produce programs for the Web by providing a Processing Library to use with JavaScript.
The Processing organization also supplies an online editor.
You are welcome to look at the chapters in any order, but later examples do depend
on an understanding of concepts introduced earlier. Moreover, because one of the
main techniques of programming is to reuse code, there are many instances of later
examples copying parts of earlier examples. Do not be concerned: the tables in the
“Implementation” section contain complete programs. It is beneficial for your learning
process to recognize the repetition.
Please do take a pause in reading to explore, experiment, and, I repeat, make your
own programs. Learning how to program is critical for understanding how we function
in today’s world and the requirements and challenges of devising algorithms using logic
and data. Learning to program might help you get a job. However, the main thing that
drives me, and I hope will drive you, is that it is fun.

Enjoy,
Jeanine

xxiii
CHAPTER 1

Basics
Abstract
The goal of this chapter is to get you started. The programming example will be a static
drawing of two cartoonish figures, as shown in Figure 1-1. Be aware that the examples
in subsequent chapters will increase in complexity, as we will be producing programs
that are highly interactive and, possibly, involving random effects, reading files, and
exhibiting behavior based on various conditions.

1
© Jeanine Meyer 2022
J. Meyer, Programming 101, https://doi.org/10.1007/978-1-4842-8194-9_1
Chapter 1 Basics

Figure 1-1. Fat and skinny Daddy logos

The Daddy logo is a version of a drawing my father would make, often as his
signature on a letter or note or artwork. I hope that you will design or recall a drawing
or symbol that has meaning to you and makes you happy the same way this cartoonish
peanut-shaped, bald guy makes me.
We will need to do some work to start us off and get to the point that the coding
is clear, but it is not too difficult. The traditional first task in using any programming
language is to get the program to display the phrase “Hello, world.” This works well in
demonstrating several important concepts, including what happens if the programmer
makes certain types of errors. Because of the features built into Processing, you can
produce a pretty fancy version of “Hello, world.”
Be patient with me and with yourself. At the end of the chapter, you will be able to
implement your own Daddy logo.

2
Chapter 1 Basics

Programming Concepts
This section, included in each chapter, is to provide a general introduction to concepts.
I begin with comparing and contrasting programming languages with natural languages.

Programming Languages and Natural Languages


Programming languages have some similarities with natural languages, but they
also have significant differences. Programming languages are defined by rules just
as a natural language’s grammar defines what is proper English, Spanish, or other
language. A program contains statements of different types just as we find in English
(or Spanish, etc.), and there also are ways to construct compound statements.
Statements in programming languages contain terms and expressions involving terms.
In programming languages, programmers often come up with our own names for
things. The names must follow certain rules, but these are not unduly restrictive. This
is a difference from natural languages, in which we mainly use the official words of the
language, whereas in programming, we are extending the language all the time.
A more significant difference between programming languages and natural
languages is that the rules must be obeyed at all times when using programming
languages! Consider that we all frequently utter grammatically incorrect statements
when we speak and yet generally are understood. This is not the situation in
programming. The good news in the case of Processing, and certain other languages, is
that the Processing system generally indicates where an error occurs. The development
environments for Processing and other computer languages are themselves computer
programs, and they do not exhibit any impatience while we fix errors and try the
program again. I will give some examples of statements, right after I introduce the
concept of values and variables.

Values and Variables


Programming involves containers or buckets where we can store specific types of things
(values). These kinds (types) of things are called data types. The following are some
examples of data:

Int           integer (e.g., 10)


float         decimal value (e.g., 5.3)

3
Chapter 1 Basics

Boolean       logical values (e.g., true/false)


Char          single character (e.g., 'a')
String        a string of characters (e.g., "hello world")

String should start with a capitalized “S”. The B in Boolean can be upper or
lowercase. The data type is named for George Boole, an English mathematician credited
with originating symbolic algebra.
Our programs can include literal values such as 5, 100.345, and “Hello” in the
code. In addition, a feature in all programming languages is what is termed variables.
A variable is a construct for associating a name of our choosing with a value. We can
initialize the variable, change it, and use it in an expression; that is, the value associated,
often termed in the variable, can vary, that is, change. Using variables makes our
programs less mysterious. Moreover, we can define one variable in terms of another,
making relationships explicit and preventing certain errors. In Processing, Java, and
some, but not all, programming languages, variables need to be declared, or set up
before use. One characteristic of variables is termed scope, which indicates what code
has access (e.g., global variables vs. local variables), but that is best explained later.
The following are examples of Processing statements. Explanation is given in
comments and later.

int classSize; // this declares, that is, sets up classSize to


                // be a variable.
classSize = 21; //assigns the value 21 to the variable classSize.
classSize = classSize + 5; //takes whatever is the current value held in
               // the variable classSize
               // and adds 5 to it and resets classSize to the new value
float score = 0; //declares the variable score AND
                 // assigns it a value. This is called initialization.
if (score == 0) {
      text("You did not score anything.", 100,100);
      text("Try again.", 100,300);
}

The // indicates that the rest of the line is a comment, meaning that Processing
ignores it. It is intended for readers of the code, including you, to make things clear. You
also can use the delimiters /* and */ for long comments.

4
Chapter 1 Basics

Note
My examples, because they are surrounded by explanations, tend not to have as many
comments as I would use outside of teaching and writing books.
There are rules for variable and function names in all programming languages.
Generally, they must start with a letter, uppercase or lowercase, and cannot contain
spaces. The most important guidance for naming is that the names should have meaning
for you. The programming language will accept single character names or names with no
apparent meaning, but these will not be helpful when you are trying to recall what you
were trying to do. So-called camel casing, as in classSize, can be helpful.
A single equal sign (=) means assignment and is used in what are called, naturally
enough, assignment statements and initialization statements. The statement

classSize = classSize + 5;

will seem less illogical if you read it as

classSize is assigned or gets the total of the current value of


classSize plus 5.

A double equal sign (==) is a comparison operator and often appears in an if


statement. Think of it as like < or <=.
The if statement is an example of a compound statement. The expression score ==
0 is interpreted as a comparison. If the value of the variable score is equal to zero, then
the statement within the brackets is executed. If the value of score is greater than zero
or less than zero, nothing happens. Again, you will see many more statements in the
context of examples.

Functions
Programming work in any language is structured into units. One important way of
structuring code comes with different names: function, procedure, subroutine, method.
These are ways of packaging one or more statements into one unit. You will read about
functions in the “Processing Programming Features” section and methods in the “Under
the Covers” section. Briefly, functions are defined, and functions are invoked. I can give you
directions , perhaps orally, perhaps by text, to my house, which is analogous to defining a
function. At that point, I am not directing you to come to my house. At some later time, I can
direct you to go to my house, and this is analogous to invoking the function.

5
Chapter 1 Basics

Programs can be considerably shorter as well as easier to modify through the use of
functions and variables, so understanding both of these concepts is important. You do
not need to accept this or understand this right now. It will be demonstrated later by my
sketch for displaying two Daddy logos that takes just one statement more than displaying
the Daddy logo just once.

Specifying Positions and Angles


Displaying drawings and images and text on the screen requires a coordinate system.
The coordinate system used by most computer languages and many graphical tools
is similar to what we learned (but might or might not remember) from high school
geometry, with one big difference. Horizontal positions, sometimes called x positions,
are specified starting from the left. Vertical positions, sometimes called y, are specified
starting from the top of the screen. Figure 1-2 shows the coordinate system with a small
circle at the 100, 200 location.

Figure 1-2. Coordinate system

If you say to yourself “This is upside down,” then I know you understood. Another
important point is that the unit is very small, so if your code positions something at
100, 200 and later at 101, 201, you probably will not detect the difference. Your intuition
regarding this will improve with experience.

6
Chapter 1 Basics

Note
As a teaser, Processing has facilities for 3D as well as 2D. We get to 3D in later chapters.
In this chapter, my Daddy logo has a smile made by specifying an arc of an ellipse. To
produce the arc, I need to write code to indicate a starting angle and an ending angle of
the arc. The system used in most computer languages is not the standard one in which
a right angle is 90 degrees, a U-turn is a 180, and snowboarders do 1800s. (I am writing
this during the Olympics, and yes, snowboarders did tricks measuring 1800 and bigger.)
It might be upsetting to realize this, but the notion of degrees with a circle consisting of
360 degrees was invented by people. I typically offer my students extra credit to identify
where and when this happened. Instead, in most programming languages, we use a
measure called radians. Think of wrapping a circle with lengths equal to one radius. How
many lengths will this take? You know the answer: It is not a whole number, it is 2 times
π, where π is an irrational number often approximated by 3.14159. In our programming,
we will use the built-in values TWO_PI, PI, HALF_PI, and QUARTER_PI. You will see
radians in use, so be patient.

Colors
There are different ways to specify colors in computer languages and computer
applications, and Processing supports more than one. In this text, we stick with
grayscale and RGB (red/green/blue). Because of how these values are stored, the range
of grayscale is from 0 (black) to 255 (white), and the values for redness, greenness,
and blueness are specified by a number from 0 to 255. This approach is used in many
applications. If you want to use a certain color that you see in a photo, you can open the
image file in Adobe Photoshop or the online Pixlr or some other graphics tool and use
the eye drop on the pixel (picture element) you want, and an information window will
tell you the RGB value. See also the mention of the Color Selector in the “Things to Look
Up” section.

Development Environment
Programmers need to prepare programs and test programs. We also need to save our
work to come back to it another time. We might need to send the program to someone
else. Processing has what is termed an integrated development environment, the
Processing Development Environment (PDE), which provides a way to prepare and

7
Chapter 1 Basics

make changes to a program as well as test it and save it. To give you a different example,
Hypertext Markup Language (HTML) documents containing JavaScript are prepared and
saved using a text editor, such as Sublime. The resulting files are opened (and run) using
a browser, such as Chrome. In the Appendix, I will show you how to use an editor for
p5.js, which is a version of JavaScript incorporating Processing features.

Role of Planning
I close this first “Programming Concepts” section by noting that preparing programs
such as a Processing sketch generally involves planning and design. It might be best to
step away from the keyboard. Some of the plans might need to be modified when you get
to writing the code, but it is best to have plans!

Under the Covers


As I indicated earlier, Processing is a language built on Java. This means that the
Processing code you write is Java code that the development environment puts into a
larger Java program prepared for handling Processing sketches. In Java, there are no
functions, but, instead, what are termed methods. I will introduce methods for our use in
Processing in Chapter 4.
The PDE (Processing Development Environment) makes use of libraries, collections
of methods holding the built-in functions of Processing, such as functions to draw a
rectangle.
In the big Java program, there are calls to functions that we write, or, to put it more
accurately, we code the body of the function. For example, all Processing sketches
contain a function called setup, the purpose of which is to do what the name implies.
It nearly always includes a statement that defines the width and height of the window,
for example. The big Java program invokes the setup program once at the start of the
sketch. Similarly, we can write the body of a function named draw. The Java program
invokes this function over and over, the frequency defined by the frame rate, which can
be reset by assigning a value to the built-in variable frameRate. This enables us to build
applications producing animations and responding to events such as a user clicking the
mouse button. There are many other functions for which we, the programmers, specify
the response to an event, for example, keyPressed or mouseClick.

8
Chapter 1 Basics

The Java program also defines default settings. Processing and other computer
languages and many computer applications provide powerful features. If we needed to
specify each aspect of each feature before anything happens, it would be tremendously
burdensome. It is important to be aware that certain things can be adjusted, though, as
you will see in our very first example later, with the discussion on default values for font,
text size, fill color, and stroke color.
The design and capabilities of Processing provide us a way to get started creating and
implementing our ideas quickly.

Processing Programming Features


In this section, I explain the concepts focusing on Processing features. There will be
small coding examples to prepare for the larger (although not too large) examples
covered later in the chapter.
To use Processing, you need to go to the processing.org website and follow the
directions to download and install Processing on your computer.

Processing Development Environment


To describe the PDE in abstract terms is too difficult, so let’s get started. Once you have
downloaded and installed Processing, open it. At the top of the PDE window, you will see
the Processing File toolbar.
Click File, which will open a drop-down menu. Select New. The toolbar will change
to hold more options. A window that looks like Figure 1-3 will appear on your screen.
The number after sketch_ will be different than what you see here. I believe in saving
early, and often so, at this point, you can think about where you want to save your
Processing work in terms of the file system on your computer. I leave that to you. You
also should give some thought to what you will name each sketch. I suggest the name
first0 for this one. Click File, then select Save As…, and proceed with a file name and a
location in the usual way for your operating system.

9
Chapter 1 Basics

Figure 1-3. Window for new sketch

Using Save As… in the PDE produces a folder, in this case named first0, which
contains a file named first0.pde. The examples explored in future chapters will
consist of folders containing additional items. For example, a Processing sketch named
myFamily that makes use of an image file aviva.jpg and an image file daniel.jpg will
be a folder named myFamily containing a file named myFamily.pde and a folder named
data that contains the two files aviva.jpg and daniel.jpg. The relationship of these
files is shown in Figure 1-4.

10
Chapter 1 Basics

Figure 1-4. Typical file structure for a sketch

Functions
Processing uses the term function for grouping together one or more statements into
something that can be invoked (called). Functions are defined with header statements
and then the body, a sequence of statements, contained within brackets. You will see
in this chapter and every chapter definitions for the setup function, a function that
Processing expects the programmer to supply. The header is

void setup()

The term void indicates that this function does not produce or return a value. The
opening and closing parentheses with nothing between them indicate that this function
does not expect any parameters.
The Daddy logo example includes a function called daddy that does the work of
drawing the cartoon. Its header is

void daddy(int x, int y, int w, int h)

The parameters are the things between the parentheses. The parameter list is the
place for the programmer to give names and specify the data type. This means that when
I wrote the code to invoke daddy, which is necessary because daddy was something I
made up, not anything Processing expects, Processing will check that the values cited in
the call are the correct type.
I feel obliged to show you an example of a function that does produce a value, a
standard one supplied in many textbooks.

11
Chapter 1 Basics

float calculateTax (float bill, float rate) {


     return (bill*rate);
}

The header indicates that this function calculates a floating-point value, sometimes
called a decimal number. The code includes what is termed an expression: bill*rate.
The asterisk indicates multiplication.
Because it generates a value, a call of this function can be used in an expression.
With this function defined, I could write an expression (part of a statement) with
something like this:

Total = 150.53 + calculateTax(150.53, .07);

Processing will assign the 150.53 to the parameter bill and the .07 to the parameter
rate, perform the multiplication bill * rate, which in this case is 150.53 * .07, and
return the result so it is available to be added to 150.53. The variable Total will be set to
161.0671.
I hope the names of these variables are suggestive. My examples are more complex
and more interesting and, because context is given, more understandable, in later
chapters.

Angles
Processing provides us built-in variables—PI, TWO_PI, HALF_PI, and QUARTER_PI—to use
when requiring specification of angles. These names are case-sensitive. Figure 1-5 shows
the designation of some angles.

12
Chapter 1 Basics

Figure 1-5. Diagram showing some angles in radians

In Processing, angles start at 0 and move clockwise around the circle as the number
increases. Notice the location of PI/3. However, you can designate a negative angle. The
angle labeled –PI/4 could also be specified as PI+.75PI or 1.75*PI.
Processing provides a function named radians for converting from the degree system
to radian measure. So radians(90) will produce a floating-point number very close to
PI/2, and radians(180) will produce a floating-point number very close to PI. We can

13
Chapter 1 Basics

go back and forth between degrees and radians, but I suggest building up your intuition
in radians. One way to do that is to examine my code and change the smile. You get
immediate feedback and can try again.

Implementing Hello, World


In Processing, we need to write a function named setup. Here is the code for my first try
at a Hello, World program.

// a Hello, world program


void setup() {
    size(900,600);
    text("Hello, world",100,200);
}

It is not necessary, but it is good practice to put a comment at the start, as I did here.
The // indicates a comment, which is ignored by Processing.
The first line of actual code is the header line of a function, which has several
elements. The term setup gives a name to the function. As I indicated earlier, we define
a setup function to get our sketch started. The parentheses, (), after the name indicate
that there are no parameters to this function. Parameters are extra information passed to
the function, and you will see examples of parameters in the Daddy logo example. The
brackets, the opening { on the first line and the closing } on the last line, mark off the
body, or contents, of the function. People follow different conventions for the location
of the brackets. They do not have to be where they are but can instead be what you
see here:

void setup()
     {size(900,600);
     text("Hello, world",100,200);}

My general advice is to not be skimpy about line breaks or blank lines. I also need
to tell you that indentation is not required and is not interpreted by Processing, but I
advise you to use indentation for functions and for compound statements such as the
if and for loop constructs we see later because it will make your code easier for you to
understand. There are Auto Format under edit and a keyboard shortcut (Command+T)
for automatic indentation.

14
Chapter 1 Basics

The first statement within the body of the function specifies the size of the display
window. The width is set at 900 and the height at 600. When you run or execute the
program, you will see what these settings produce.
The second and last statement within the body of the function does the work of
displaying the string “Hello, world” at the position 100 pixel units from the left side of the
display window and 200 pixel units from the top.
You should save the program, which you do by clicking File and then selecting Save.
Select Save rather than Save As… to save the file in the same place as you indicated in the
first Save As… command. Of course, you could wait to rename the program and then use
Save As…, but my motto is to save early and often.
The next step is to try the program by running it. Do this by clicking on the play
(triangle/arrow) button in the upper left of the screen shown in Figure 1-6.

Figure 1-6. The first sketch

15
Chapter 1 Basics

The result will be disappointing, but it is educational. You should see what is shown
in Figure 1-7, namely, the phrase “Hello, world” in tiny, white letters.

Figure 1-7. Result of running first0

Now, perhaps you do not see anything. Perhaps the program did not even start.
This could happen if you made any syntactic mistakes, or mistakes of form. To put it in
practical terms, Processing can detect syntactic errors but cannot correct them. Examine
Figure 1-8. I made a mistake, omitting a comma between the 100 and the 200. The
Processing program shows that there is a problem in the statement indicating the call
to the function text. The message, called an error message, does not say what I know
happened: it does not say anything about a missing comma. It does say that the function
text() expects three parameters. Error messages might not tell you everything, but they
generally are helpful. One of the most common syntactic mistakes is a problem with
brackets or parentheses. Processing can detect when there are too many or too few but
does not indicate exactly where the problem is.

16
Chapter 1 Basics

Figure 1-8. Example of a syntactic mistake and error message

In addition to syntactic mistakes, we could make semantic mistakes, mistakes of


meaning or faulty logic. If you or I had written “Hellowold,” the rules of Processing would
accept it, but it might not be what we intended. Similarly, if we intended to draw a red
circle and instead drew a blue one or if we produced a drawing with the left eye not on
the face, that would be a semantic mistake. Processing does not help us notice or fix
these. We are on our own.
You can say that the program shown in Figure 1-6 and producing the result shown in
Figure 1-7 represents a semantic error. I will say it was a success—the desired message
was displayed—but we can do better. Remember my mention of default values? The call
to the text function makes use of the current settings for text size, text font, text color,
and text alignment. I will show you an improvement. To encourage good habits, go to the
File menu, select Save As…, and save with a new name, first1. The improved sketch will
change the text size and the color. I leave font and alignment to you.
The Processing function fill() sets the color of a shape or the color of text, and the
function stroke() sets the color of the outline of a shape. If we use just one number, the
color is grayscale, or black to white. The value should be a number from 0 to 255, where
0 is black and 255 is white. If we use three numbers, the numbers specify the amounts of
redness, greenness, and blueness. As with positions and angles, you will gain intuition
on this as you use it.

17
Chapter 1 Basics

Here is the complete code for the improved sketch; notice that two statements have
been added to the original sketch, and I also changed the comment at the start.

// improved Hello, world program, setting size and color


void setup() {
     size(900,600);
     textSize(30); //bigger than default
     fill(250,0,250); //changed color for text
     text("Hello, world",100,200);
}

The call to the function textSize sets the new size. The call to the fill function sets
the color. Save the sketch and then run this program; it will produce what is shown in
Figure 1-9.

Figure 1-9. Result of first1, the improved sketch

18
Chapter 1 Basics

Because Processing facilitates much more than displaying text, I describe one more
program here. Click File, select Save As…, and save this file with the name first2. Now
modify the program with the addition of one more statement. I provide the whole sketch,
but it is just the line with the call to the ellipse function that is to be added. The ellipse
is centered at 180, 200. Its width is 300, and its height is 200. Ellipses can be specified in
different ways depending on the setting of a variable named ellipseMode. You can look
this up to see the possibilities.

// a Hello, world inside of ellipse


void setup() {
    size(900,600);
    ellipse(180,200,300,200);//I fiddled with these values
    textSize(30); //bigger than the default
    fill(250,0,250); //changed color for text
    text("Hello, world",100,200);
}

Do take my comment “I fiddled” seriously; that is, I tried a few things until the result
was what I wanted. Save and run the program. You should see what is displayed in
Figure 1-10.

19
Chapter 1 Basics

Figure 1-10. Hello, world inside an ellipse

Why is the ellipse white with a black border? The answer is that the default value for
fill is 255, producing white, and the default for stroke is 0, producing black. I strongly
urge you to put the book down (or close the window on whatever application you are
reading the e-book version) and do some experiments. Put a call to the fill function
and a call to the stroke function before the ellipse command. Change “Hello, world” to
something else. Draw a circle instead of an ellipse. Try stuff!
This activity with Hello, world examples introduced the basics, but not every
feature required for the Daddy logo project. Here is a list of what additional Processing
constructs will be used, with short explanations.

• Declaration of variables, including initialization. An example of this is

int skinnyFaceWidth = 60;

This sets skinnyFaceWidth as a variable of data type int and an initial


value of 60. I say initial value, but in fact, this variable and many of the
others do not change: they are not assigned different values.
20
Chapter 1 Basics

• The color data type and the color function: This is an unusual but
acceptable situation of one name being used for two distinct things.
In Processing, color is a data type similar to int or float. The color
function is used to produce a value of data type color. The following
code could appear:

color skinTone = color(255,224,189);

I advise you to not use the same name for different things even if they
are related.

• The ellipseMode function: Processing provides different ways to


specify an ellipse. For example, a programmer can specify the center
or the upper left corner. I use it here to introduce the idea. A call to

ellipseMode(CENTER);

means that the parameters specify the center of the ellipse. In


different situations, you might find one way more natural than
the other.

• Expressions, making use of arithmetic operators: You will read later


in the “Planning” section how my code defines certain variables in
terms of other variables. For example, the center of the arc that is the
mouth is set to be a certain distance, namely, one tenth of the height,
further down the screen than the center of the ellipse that is the lower
part of the peanut shape. My code converts (the technical term cast is
used) the results to be rounded to an integer.

int mouthYoffset = int(.10*h);

• Definition of a programmer-defined function, daddy, with


parameters: Defining what are called programmer-defined functions
is the main lesson of this chapter. The function I define is called
daddy, and its parameters are used to specify the position and the
dimensions of the Daddy figure.
• Definition of the draw function and turning off the invocation of
draw: In the Daddy logo example, the draw function calls the daddy
function two times (wait for the next section). Normally, the draw

21
Another Random Scribd Document
with Unrelated Content
Transcriber’s Notes:
The spelling, punctuation and hyphenation are as the original,
with the exception of apparent typographical errors which have been
corrected.
*** END OF THE PROJECT GUTENBERG EBOOK THE AMERICAN
MISSIONARY — VOLUME 34, NO. 09, SEPTEMBER, 1880 ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

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.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute


this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU AGREE
THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT
EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE
THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status
by the Internal Revenue Service. The Foundation’s EIN or
federal tax identification number is 64-6221541. Contributions
to the Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or determine
the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.

Вам также может понравиться