Merge pull request #575 from nature-of-code/notion-update-docs

edits to acknowledgments and introduction
This commit is contained in:
Daniel Shiffman 2023-12-03 15:35:16 -05:00 committed by GitHub
commit a444c2faa1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 69 additions and 69 deletions

View file

@ -1,32 +1,32 @@
<section data-type="chapter">
<h1 id="acknowledgments">Acknowledgments</h1>
<blockquote data-type="epigraph">
<p>"The world around us moves in complicated and wonderful ways. We spend the earlier parts of our lives learning about our environment through perception and interaction. We expect the physical world around us to behave consistently with our perceptual memory, e.g. if we drop a rock it will fall due to gravity, if a gust of wind blows, lighter objects will be tossed by the wind further. This class focuses on understanding, simulating, and incorporating motion-based elements of our physical world into the digital worlds that we create. Our hope is to create intuitive, rich, and more satisfying experiences by drawing from the perceptual memories of our users."</p>
<p> James Tu, Dynamic Bodies course description, Spring 2003, ITP</p>
<p>The world around us moves in complicated and wonderful ways. We spend the earlier parts of our lives learning about our environment through perception and interaction. We expect the physical world around us to behave consistently with our perceptual memory, e.g., if we drop a rock, it will fall due to gravity, if a gust of wind blows, lighter objects will be tossed by the wind further. This class focuses on understanding, simulating, and incorporating motion-based elements of our physical world into the digital worlds that we create. Our hope is to create intuitive, rich, and more satisfying experiences by drawing from the perceptual memories of our users.</p>
<p>—James Tu, Dynamic Bodies course description, Spring 2003, ITP</p>
</blockquote>
<p>In 2003, as a graduate student at the Interactive Telecommunications Program (ITP) in the Tisch School of the Arts at New York University, I enrolled in a course called Dynamic Bodies. The course was taught by interaction designer and ITP adjunct professor James Tu. At the time, my work was focused on a series of software experiments that generated real-time non-photorealistic imagery. The applications involved capturing images from a live source and “painting” the colors with elements that moved about the screen according to various rules. Tus course—which covered vectors, forces, oscillations, particle systems, recursion, steering, and springs—aligned perfectly with my work.</p>
<p>In 2003, as a graduate student at the Interactive Telecommunications Program (ITP) in the Tisch School of the Arts at New York University, I enrolled in a course called Dynamic Bodies. The course was taught by interaction designer and ITP adjunct professor James Tu. At the time, my work was focused on a series of software experiments that generated real-time, non-photorealistic imagery. The applications involved capturing images from a live source and “painting” the colors with elements that moved about the screen according to various rules. Tus course—which covered vectors, forces, oscillations, particle systems, recursion, steering, and springs—aligned perfectly with my work.</p>
<p>I had been using these concepts informally in my own projects but had never taken the time to closely examine the science behind the algorithms or learn object-oriented techniques to formalize their implementation. That very semester, I also enrolled in Foundations of Generative Art Systems, a course taught by Philip Galanter that focused on the theory and practice of generative art, covering topics such as chaos, cellular automata, genetic algorithms, neural networks, and fractals. Both Tus and Galanters courses opened my eyes to the world of simulation algorithms, techniques that carried me through the next several years of work and teaching and that served as the foundation and inspiration for this book.</p>
<p>But theres another piece of the puzzle missing from this story.</p>
<p>Galanters course was mostly theory-based, while Tus was taught using Macromedia Director and the Lingo programming language. That semester, I learned many of the algorithms by translating them into C++ (the language I was using quite awkwardly at the time, well before C++ creative coding environments like openFrameworks and Cinder had arrived). Toward the end of the semester, however, I discovered something called <a href="http://www.processing.org/">Processing</a>. Processing was in alpha then (version 0055), and having had some experience with Java, I was intrigued enough to ask the question: Could this open-source, artist-friendly programming language and environment be the right place to develop a suite of tutorials and examples about programming and simulation? With the support of the ITP and Processing communities, I embarked on what has now been an almost 20 year journey of teaching coding.</p>
<p>Id like to first thank Red Burns, ITPs founder, who passed away in 2013. Red supported and encouraged me in my work for well over 10 years. Dan OSullivan, the Associate Dean of Emerging Media at Tisch School of the Arts, has been a mentor and was the first to suggest that I try teaching a course on Processing, giving me a reason to start assembling programming tutorials in the first place. Shawn Van Every, current chair of the department, was my officemate during my first year of teaching full time, and has been a rich source of help and inspiration over the years. I am grateful for the support and encouragement of ITP professor Luisa Peirera. Her work on her book, <em>Code of Music</em>, was deeply inspiring. Her innovative approach to interactive educational materials helped me rethink and redefine my own writing and publishing process.</p>
<p>The vibrant and nurturing environment of ITP has been shaped by so many incredible individuals. Whether they were colleagues from the early days of this books conception or newer faces bringing fresh waves of inspiration, Im so thankful to the full-time faculty of ITP/IMA: Ali Santana, Allison Parrish, Blair Simmons, Clay Shirky, Craig Protzel, David Rios, Danny Rozin, Gabe Barcia-Colombo, Katherine Dillon, Marianne Petit, Marina Zurkow, Matt Romein, Mimi Yin, Nancy Hechinger, Pedro Galvao Cesar de Oliveira, Sarah Rothberg, Sharon de la Cruz, Tom Igoe, Yeseul Song<em>.</em></p>
<p>The dedicated and tireless staff at ITP/IMA play such a vital role in keeping the ecosystem thriving and making everything. My thanks go to the many people Ive worked with over the years: Adrian Mandeville, Brian Kim, Daniel Tsadok, Dante Delgiacco, Edward Gordon, Emma Asumeng, George Agudow, John Duane, Lenin Compres, Luke Bunn, Marlon Evans, Matt Berger, Megan Demarest, Midori Yasuda, Phil Caridi, Rob Ryan, Scott Broussard, and Shirley Lin.</p>
<p>But another piece of the puzzle is missing from this story.</p>
<p>Galanters course was mostly theory based, while Tus was taught using Macromedia Director and the Lingo programming language. That semester, I learned many of the algorithms by translating them into C++ (the language I was using quite awkwardly at the time, well before C++ creative coding environments like openFrameworks and Cinder had arrived). Toward the end of the semester, however, I discovered something called <a href="http://www.processing.org/">Processing</a>. Processing was in alpha then (version 0055), and having had some experience with Java, I was intrigued enough to ask the question, Could this open source, artist-friendly programming language and environment be the right place to develop a suite of tutorials and examples about programming and simulation? With the support of the ITP and Processing communities, I embarked on what has now been an almost 20-year journey of teaching coding.</p>
<p>Id like to first thank Red Burns, who led ITP through its first 30 years and passed away in 2013. Red supported and encouraged me in my work for well over 10 years. Dan OSullivan, the associate dean of Emerging Media at the Tisch School of the Arts, has been a mentor and was the first to suggest that I try teaching a course on Processing, giving me a reason to start assembling programming tutorials in the first place. Shawn Van Every, current chair of the department, was my officemate during my first year of teaching full-time, and has been a rich source of help and inspiration over the years. I am grateful for the support and encouragement of ITP professor Luisa Pereira. Her work on her upcoming book, <em>Code of Music</em>, was deeply inspiring. Her innovative approach to interactive educational materials helped me rethink and redefine my own writing and publishing process.</p>
<p>The vibrant and nurturing environment of ITP has been shaped by so many incredible individuals. Whether they were colleagues from the early days of this books conception or newer faces bringing fresh waves of inspiration, Im so thankful to the full-time faculty of ITP/IMA: Ali Santana, Allison Parrish, Blair Simmons, Clay Shirky, Craig Protzel, Danny Rozin, David Rios, Gabe Barcia-Colombo, Katherine Dillon, Marianne Petit, Marina Zurkow, Matt Romein, Mimi Yin, Nancy Hechinger, Pedro Galvao Cesar de Oliveira, Sarah Rothberg, Sharon De La Cruz, Tom Igoe, and Yeseul Song<em>.</em></p>
<p>The dedicated and tireless staff at ITP and NYUs Interactive Media Arts (IMA) play such a vital role in keeping the ecosystem thriving and making everything. My thanks go to the many people Ive worked with over the years: Adrian Mandeville, Brian Kim, Daniel Tsadok, Dante Delgiacco, Edward Gordon, Emma Asumeng, George Agudow, John Duane, Lenin Compres, Luke Bunn, Marlon Evans, Matt Berger, Megan Demarest, Midori Yasuda, Phil Caridi, Rob Ryan, Scott Broussard, and Shirley Lin.</p>
<p>A special note of thanks goes to ITP adjunct faculty members Ellen Nickles and Nuntinee Tansrisakul, who co-taught an online, asynchronous version of the Nature of Code course with me in 2021, amid the peak of a global pandemic. Their contributions and the ideas from that semester greatly enriched the course materials.</p>
<p>The students of ITP and IMA, too numerous to mention, have been an amazing source of feedback throughout this process. Much of the material in this book comes from my course of the same title, which Ive now taught seventeen times. I have stacks of draft printouts of the book with notes scrawled in the margins, as well as a vast archive of student emails with corrections, comments, and generous words of encouragement.</p>
<p>I would like to spotlight several students who worked as graduate associates on the Nature of Code materials. Through their work with the ITP/IMA Equitable Syllabus project, Chaski No and Briana Jones provided extraordinary research support that expanded the books concepts and references. As the GA for the inaugural undergraduate version of the Nature of Code class, Gracy Whelihan offered invaluable support, feedback, and alway reminded me of the wonder of random numbers.</p>
<p>The students of ITP and IMA, too numerous to mention, have been an amazing source of feedback throughout this process. Much of the material in this book comes from my course of the same title, which Ive now taught 17 times. I have stacks of draft printouts of the book with notes scrawled in the margins, as well as a vast archive of student emails with corrections, comments, and generous words of encouragement.</p>
<p>I would like to spotlight several students who worked as graduate associates on the Nature of Code materials. Through their work with the ITP/IMA Equitable Syllabus project, Chaski No and Briana Jones provided extraordinary research support that expanded the books concepts and references. As the graduate assistant for the inaugural undergraduate version of the Nature of Code class, Gracy Whelihan offered invaluable support and feedback, and always reminded me of the wonder of random numbers.</p>
<p>Jason Gao and Stuti Mohgaonkar worked on the build systems for the book materials, inventing new workflows for writing and editing. Elias Jarzombek also warrants a mention for his advice and technical support, stemming from the <em>Code of Music</em> book project.</p>
<p>After graduating, Jason Gao continued to develop and design the Nature of Code website. If you head to <a href="http://natureofcode.com/">natureofcode.com</a> right now, you will see the fruits of his many talents: a full version of the book that seamlessly integrates with the p5.js web editor. Its a realization far beyond my initial vision.</p>
<p>The interior of the book was meticulously designed by Tuan Huang. Tuan began developing layout ideas while taking the Nature of Code class in the spring of 2023. After graduating, Tuan further refined the design, working to develop a consistent visual language across the many elements of the book. Her minimal and elegant aesthetics greatly enhanced the books visual appeal and accessibility. A special thanks also to the OpenMoji project—the open-source emoji and icon project. License: <a href="https://creativecommons.org/licenses/by-sa/4.0/#">CC BY-SA 4.0</a>—for providing a delightful and comprehensive set of emojis, used throughout this book for various elements.</p>
<p>Im also indebted to the energetic and supportive creative coding community and Processing Foundation. I wouldnt be writing this book if it werent for Casey Reas and Ben Fry, who created Processing in 2001 and co-founded the Processing Foundation. Theyve dedicated 20+ years to building and maintaining both the software and its community. Ive learned half of what I know simply from reading through the Processing source code and documentation; the elegant simplicity of the Processing language, website, and IDE is the original source of inspiration for all of my teaching and work.</p>
<p>Lauren Lee McCarthy, the creator of p5.js, planted the seed that made everything possible for transforming the book into JavaScript. Shes a tireless champion for inclusion and access in open source, and her approach to community-building has been profoundly inspiring to me. Cassie Tarakajian invented the p5.js web editor, a heroic undertaking that has made it possible to collect and organize all of the example code in the book.</p>
<p>My heartfelt thanks extends to the other current and former members (along with Casey, Ben, and Lauren) of the Processing Board of Directors: Dorothy Santos, Kate Hollenbach, Xin Xin, and Johanna Hedva. A special acknowledgment to the project leads, staff, and alumni of the foundation, who have each played a pivotal role in shaping and propelling the community and its projects: Andres Colubri, Charles Reinhardt, evelyn masso, Jesse C Thompson, Jonathan Feinberg, Moira Turner, Qianqian Ye, Rachel Lim, Raphaël de Courville, Saber Khan, Suhyun (Sonia) Choi, Toni Pizza, Tsige Tafesse, and Xiaowei R. Wang.</p>
<p>After graduating, Jason Gao continued to develop and design the Nature of Code website. If you head to <a href="http://natureofcode.com/"><em>https://natureofcode.com</em></a> right now, you will see the fruits of his many talents: a full version of the book that seamlessly integrates with the p5.js web editor. Its a realization far beyond my initial vision.</p>
<p>The interior of the book was meticulously designed by Tuan Huang. Tuan began developing layout ideas while taking the Nature of Code class in the spring of 2023. After graduating, Tuan further refined the design, working to develop a consistent visual language across the many elements of the book. Her minimal and elegant aesthetics greatly enhanced the books visual appeal and accessibility. A special thanks also to the OpenMoji project—the open source emoji and icon project (Creative Commons license <a href="https://creativecommons.org/licenses/by-sa/4.0/#">CC BY-SA 4.0</a>)—for providing a delightful and comprehensive set of emojis used throughout this book for various elements.</p>
<p>Im also indebted to the energetic and supportive creative coding community and the Processing Foundation. I wouldnt be writing this book if it werent for Casey Reas and Ben Fry, who created Processing in 2001 and co-founded the Processing Foundation. Theyve dedicated over 20 years to building and maintaining the software and its community. Ive learned half of what I know simply from reading through the Processing source code and documentation; the elegant simplicity of the Processing language, website, and IDE is the original source of inspiration for all my teaching and work.</p>
<p>Lauren Lee McCarthy, the creator of p5.js, planted the seed that made everything possible for transforming the book into JavaScript. Shes a tireless champion for inclusion and access in open source, and her approach to community building has been profoundly inspiring to me. Cassie Tarakajian invented the p5.js web editor, a heroic undertaking that has made it possible to collect and organize all the example code in the book.</p>
<p>My heartfelt thanks extends to the other current and former members (along with Casey, Ben, and Lauren) of the Processing board of directors: Dorothy Santos, Kate Hollenbach, Xin Xin, and Johanna Hedva. A special acknowledgment to the project leads, staff, and alumni of the foundation, who have each played a pivotal role in shaping and propelling the community and its projects: Andres Colubri, Charles Reinhardt, evelyn masso, Jesse C Thompson, Jonathan Feinberg, Moira Turner, Qianqian Ye, Rachel Lim, Raphaël de Courville, Saber Khan, Suhyun (Sonia) Choi, Toni Pizza, Tsige Tafesse, and Xiaowei R. Wang.</p>
<p>In Chapter 10, I introduce the ml5.js project, a companion library to p5.js that aims to bring machine learning capabilities to creative coders in a friendly and approachable manner. Thank you to the numerous researchers and students at ITP/IMA who contributed to its development: Ashley Lewis, Bomani McClendon, Christina Dacanay, Cristóbal Valenzuela, Lydia Jessup, Miaoye Que, Michael Weinberg, Ozi Chukwukeme, Sam Krystal, Yining Shi, and Ziyuan (Peter) Lin. Id like to especially thank Joey K. Lee, who provided valuable advice and feedback on the <em>Nature of Code</em> book itself while working on ml5.js.</p>
<p>I would also like to thank AI researcher David Ha, whose research on neuroevolution (see the further reading on the books website), inspired me to create examples implementing the technique with ml5.js and add a new chapter to this book.</p>
<p>For the last 10 years, Ive spent the bulk of my time making video tutorials on my YouTube channel, The Coding Train. Im incredibly grateful for the immense support and collaboration from so many people in keeping the engines running and on the tracks (as much as I work very hard to veer off), including Chloe Desaulles, Cy X, David Snyder, Dusk Virkus, Elizabeth Perez, Jason Heglund, Katie Chan, Kline Gareth, Kobe Liesenborgs, and Mathieu Blanchette. A special thanks to Melissa Rodriguez, who help research and secure permissions for the images you see at the start of each chapter.</p>
<p>I would also like to thank AI researcher David Ha, whose research on neuroevolution (see “Additional Resources” on the books website) inspired me to create examples implementing the technique with ml5.js and add a new chapter to this book.</p>
<p>For the last 10 years, Ive spent the bulk of my time making video tutorials on my YouTube channel, the Coding Train. Im incredibly grateful for the immense support and collaboration from so many people in keeping the engines running and on the tracks (as much as I work very hard to veer off), including Chloe Desaulles, Cy X, David Snyder, Dusk Virkus, Elizabeth Perez, Jason Heglund, Katie Chan, Kline Gareth, Kobe Liesenborgs, and Mathieu Blanchette. A special thanks to Melissa Rodriguez, who helped research and secure permissions for the images you see at the start of each chapter.</p>
<p>My thanks also extend to the Nebula streaming platform and its CEO Dave Wiskus for their unwavering support, and to Nebula creator Grady Hillhouse, who recommended I collaborate with No Starch Press to actually print this darn thing. I wouldnt be able to reach such a wide audience without the YouTube platform itself; a special thanks goes to my illustrious YouTube partner manager Dean Kowalski, as well as to Doreen Tran, who helps lead YouTube Skilling for North America.</p>
<p>I have many thoughtful, smart, generous, and kind viewers. Id like to especially thank Dipam Sen, Francis Turmel, Simon Tiger, and Kathy McGuiness who offered advice, feedback, corrections, technical support, and more. The book is so much better because of them.</p>
<p>I have many thoughtful, smart, generous, and kind viewers. Id like to especially thank Dipam Sen, Francis Turmel, Simon Tiger, and Kathy McGuiness, who offered advice, feedback, corrections, technical support, and more. The book is so much better because of them.</p>
<p>I also would like to thank many people who collaborated with me over 10 years ago on the 2012 edition: David Wilson (book cover and design), Rune Madsen and Steve Klise (build system and website), Shannon Fry (editing), Evan Emolo, Miguel Bermudez, and all of the Kickstarter backers who helped fund the work.</p>
<p>A special mention goes to Zannah Marsh, who worked tirelessly to create over 100 illustrations for the 2012 version of this book, and by some miracle agreed to do it all again for this new edition. I especially want to thank her for her patience and willingness to go with the flow as I changed my mind on certain illustrations way too many times. And the cats! I smile from ear to ear every time I see them typing.</p>
<p>Now, the real reason why were all here. If it werent for No Starch Press, Im almost certain youd never be reading these words. Sure, you might be perusing some updated tutorials on the website, but the collaboration, support, and thoughtful and kind deadline-setting of the team was the thing that really pushed me over the hump. I want to express my gratitude to editor Nathan Heidelberger, who is responsible for this book actually making any sense at all, not to mention all of the legitimately funny jokes. (The blame for any bad puns lies squarely with me.) Thank you to Jasper Palfree, the technical editor, who patiently explained to me, as many times as it took for me to grok, the difference between linear and rotational motion (and clarified countless other science and code concepts). Thank you to the founder of No Starch, Bill Pollock, who taught me everything I need to know about shopping at Trader Joes; Managing Editor Jill Franklin, for her kind and patient support; and the production team led by Senior Production Editor Jennifer Kepler and Production Manager Sabrina Plomitallo-González who accomodated my unusual Notion → GitHub → PDF workflow.</p>
<p>Finally, a heartfelt thank you to my wife, Aliki Caloyeras, who is always right. Seriously, its like a superpower at this point. I love you. To my children, Elias, who graciously allows me to maintain a semblance of dignity by not utterly obliterating me at basketball and video games, and Olympia, who reminds me “Im feeling 22” when we play backgammon and cards and laugh together. Id also like to thank my father, Bernard Shiffman, who generously lent his mathematical expertise and provided feedback along the way, as well as my mother, Doris Yaffe Shiffman, and brother, Jonathan Shiffman, who were always tremendously supportive in asking the question: “How is the book coming along?”</p>
<p>Now, the real reason were all here. If it werent for No Starch Press, Im almost certain youd never be reading these words. Sure, you might be perusing updated tutorials on the website, but the collaboration, support, and thoughtful and kind deadline setting of the team was the thing that really pushed me over the hump. I want to express my gratitude to editor Nathan Heidelberger, who is responsible for this book making any sense at all, not to mention for all the legitimately funny jokes. (The blame for any bad puns lies squarely with me.) Thank you to Jasper Palfree, the technical editor, who patiently explained to me, as many times as it took for me to grok, the difference between linear and rotational motion (and clarified countless other science and code concepts). I also want to extend special thanks to copyeditor Sharon Wilkey, whose meticulous attention to detail polished every sentence and provided the perfect finishing touches. Thank you to the founder of No Starch, Bill Pollock, who taught me everything I need to know about shopping at Trader Joes; managing editor Jill Franklin, for her kind and patient support; and the production team, led by senior production editor Jennifer Kepler and production manager Sabrina Plomitallo-González, who accommodated my unusual Notion → GitHub → PDF workflow.</p>
<p>Finally, a heartfelt thank-you to my wife, Aliki Caloyeras, who is always right. Seriously, its like a superpower at this point. I love you. To my children, Elias, who graciously allows me to maintain a semblance of dignity by not utterly obliterating me at basketball and video games, and Olympia, who reminds me “Im feeling 22” when we play backgammon and cards and laugh together. Id also like to thank my father, Bernard Shiffman, who generously lent his mathematical expertise and provided feedback along the way, as well as my mother, Doris Yaffe Shiffman, and brother, Jonathan Shiffman, who were always tremendously supportive in asking the question, “How is the book coming along?”</p>
</section>

View file

@ -1,54 +1,54 @@
<section data-type="chapter">
<h1 id="introduction">Introduction</h1>
<p>Over a decade ago, I self-published <em>The Nature of Code</em>, an online resource and print book exploring the unpredictable evolutionary and emergent properties of nature in software using the creative coding framework Processing. Its the understatement of the century to say that much has changed in the world of technology and creative media since then, and so here I am again, with a new and rebooted version of this book built around JavaScript and the p5.js library. There are a few new coding tricks this time, but its still the same old nature—birds still flap their wings, and apples still fall on our heads.</p>
<p>Over a decade ago, I self-published <em>The Nature of Code</em>, an online resource and print book exploring the unpredictable evolutionary and emergent properties of nature in software via the creative coding framework Processing. Its the understatement of the century to say that much has changed in the world of technology and creative media since then, and so here I am again, with a new and rebooted version of this book built around JavaScript and the p5.js library. The book has a few new coding tricks this time, but its the same old nature—birds still flap their wings, and apples still fall on our heads.</p>
<h2 id="what-is-this-book">What Is This Book?</h2>
<p>At ITP/IMA (Tisch School of the Arts, New York University), Ive been teaching a course entitled Introduction to Computational Media since 2004. The origins of this class date back to 1987 and the work of Mike Mills and John Henry Thompson (inventor of the Lingo programming language). In the course, students learn the basics of programming (variables, conditionals, loops, objects, arrays) as well as concepts related to making interactive media projects (pixels, data, sound, networking, 3D, and more). In 2008, I synthesized my materials for this class into an introductory book, <em>Learning Processing</em>, and in 2015 I created a series of video tutorials that follow the same trajectory in JavaScript with the p5.js library.</p>
<p>At ITP/IMA (Tisch School of the Arts, New York University), Ive been teaching a course titled Introduction to Computational Media since 2004. The origins of this class date back to 1987 and the work of Mike Mills and John Henry Thompson (inventor of the Lingo programming language). In the course, students learn the basics of programming (variables, conditionals, loops, objects, arrays) as well as concepts related to making interactive media projects (pixels, data, sound, networking, 3D, and more). In 2008, I synthesized my materials for this class into an introductory book, <em>Learning Processing</em>, and in 2015, I created a series of video tutorials that follow the same trajectory in JavaScript with the p5.js library.</p>
<p>Once a student has learned the basics and seen an array of applications, their next step might be to delve deeply into a particular area. Maybe they want to focus on computer vision, data visualization, or generative poetry. My Nature of Code course (also taught at ITP and IMA since 2008) represents another possible next step. It picks up exactly where my introductory material leaves off, demonstrating a world of programming techniques that focus on algorithms and simulation. The book youre reading has evolved from that course.</p>
<p>My goal for this book is simple: I want to take a look at phenomena that naturally occur in the physical world and figure out how to write code to simulate them.</p>
<p>What, then, is this book exactly? Is it a science book? The answer is a resounding no. True, I might examine topics that come from physics or biology, but I wont investigate these topics with a particularly high level of academic rigor. Instead, the book is “inspired by actual events.” Im grabbing the parts from science and mathematics needed to build a software interpretation of nature, and veering off course or skipping details as I see fit.</p>
<p>Is this an art or design book? I would also say no. Regardless of how informal my approach might be, Im still putting my focus on algorithms and their related programming techniques. Sure, the resulting demonstrations are visual in nature (manifested as animated p5.js sketches), but theyre literal visualizations of the algorithms and programming techniques themselves, drawn only with basic shapes and grayscale color. Its my hope, however, that you, dear reader, can use your creativity and visual ideas to make new, engaging work out of the examples. (I wont complain if you turn every sketch into a rainbow.)</p>
<p>Is this an art or design book? I would also say no. Regardless of how informal my approach might be, Im still focusing on algorithms and their related programming techniques. Sure, the resulting demonstrations are visual (manifested as animated p5.js sketches), but theyre literal visualizations of the algorithms and programming techniques themselves, drawn only with basic shapes and grayscale color. Its my hope, however, that you, dear reader, can use your creativity and visual ideas to make new, engaging work out of the examples. (I wont complain if you turn every sketch into a rainbow.)</p>
<p>In the end, if this book is anything, its an old-fashioned programming textbook. While a scientific topic (Newtonian physics, cellular growth, evolution) may seed a chapter and the results might inspire artistic projects, the content itself will always boil down to the code implementation, with a particular focus on object-oriented programming.</p>
<h2 id="a-word-about-p5js">A Word About p5.js</h2>
<p>The p5.js library is a reimagining of the Processing creative coding environment for the modern web. Im using it in this book for a number of reasons. For one, its an environment that Im very familiar with. While the original Processing built on top of Java is my first love and still what I turn to when trying out a new idea, p5.js is what I now use for teaching many of my programming classes. Its free, open source, and well suited to beginners, and because its JavaScript, everything runs right there in the web browser itself—no installation required.</p>
<p>For me, however, Processing and p5.js are first and foremost a community of people, not coding libraries or frameworks. Those people have generously dedicated countless hours to making and sharing the software. Ive written this book for that community and for anyone and everyone who loves to explore their curiosity and play through code.</p>
<p>All that said, theres nothing that ties what Im doing in this book strictly to p5.js—or Processing, for that matter. This book could have been written with “vanilla” JavaScript or Java, or with any number of other open-source creative coding environments like openFrameworks, Cinder, and so on. Its my hope that after Ive completed this book, Ill be able to release versions of the examples that run in other environments. If anyone is interested in helping to port the examples, please feel free to contact me (<code>daniel@shiffman.net</code>). Go on, you know you want to port <em>The Nature of Code</em> to PHP!</p>
<p>All of the examples in this book have been tested with p5.js version 1.7.0, but for the most part they should also work with earlier versions of p5.js. Ill be keeping them up-to-date with whatever the latest version is. The most recent code can always be found on this books website, <em>https://natureofcode.com</em> (and its associated GitHub repository).</p>
<p>All that said, nothing that this books content strictly to p5.js—or Processing, for that matter. This book could have been written with “vanilla” JavaScript or Java, or with any number of other open source creative coding environments like openFrameworks, Cinder, and so on. Its my hope that after Ive completed this book, Ill be able to release versions of the examples that run in other environments. If anyone is interested in helping to port the examples, please feel free to contact me (<em>daniel@natureofcode.com</em>). Go on, you know you want to port <em>The Nature of Code</em> to PHP!</p>
<p>All the examples in this book have been tested with p5.js version 1.8.0, but for the most part they should also work with earlier versions. Ill be keeping them up-to-date with the latest version. The most recent code can always be found on this books website, <em>https://natureofcode.com</em> (and its associated GitHub repository).</p>
<h2 id="what-do-you-need-to-know">What Do You Need to Know?</h2>
<p>The prerequisites for understanding the material in this book could be stated as “one semester of programming instruction with p5.js, Processing, or any other creative coding environment.” That said, theres no reason why you couldnt read this book having learned programming using a different language or development environment.</p>
<p>If youve never written any code before, while you could read the book for the concepts and inspiration, youll likely struggle with the code because Im assuming knowledge of the fundamentals: variables, conditionals, loops, functions, objects, and arrays. If these concepts are new to you, my “Code! Programming with p5.js” or “Introduction to Creative Coding with Processing 4” video courses on YouTube (found on the “tracks” page of <em>thecodingtrain.com</em>) provide the fundamentals of what you need to know.</p>
<p>If youre an experienced programmer but havent worked with p5.js, you can probably pick it up by <a href="https://p5js.org/">checking out the p5.js documentation</a>, poking through the examples, and reading through the librarys <a href="https://p5js.org/get-started/">Getting Started</a> page.</p>
<p>I should also point out that experience with object-oriented programming is fairly critical. Ill review some of the basics in Chapter 0, but if classes and objects are unfamiliar to you, I would suggest watching my p5.js or Processing object-oriented video tutorials, both also available at <em>thecodingtrain.com</em>.</p>
<p>The prerequisites for understanding the material in this book could be stated as “one semester of programming instruction with p5.js, Processing, or any other creative coding environment.” That said, theres no reason you couldnt read this book having learned programming with a different language or development environment.</p>
<p>If youve never written any code before, while you could read the book for the concepts and inspiration, youll likely struggle with the code because Im assuming knowledge of the fundamentals: variables, conditionals, loops, functions, objects, and arrays. If these concepts are new to you, my “Code! Programming with p5.js” or “Introduction to Creative Coding with Processing 4” video courses on YouTube (found on the “Tracks” page of the Coding Train website, <a href="https://thecodingtrain.com/tracks"><em>https://thecodingtrain.com/tracks</em></a>) provide the fundamentals of what you need to know.</p>
<p>If youre an experienced programmer but havent worked with p5.js, you can probably pick it up by checking out the p5.js documentation (<a href="https://p5js.org/"><em>https://p5js.org</em></a>), poking through the examples, and reading through the librarys “Get Started” page (<a href="https://p5js.org/get-started/"><em>https://p5js.org/get-started/</em></a>).</p>
<p>I should also point out that experience with object-oriented programming is fairly critical. Ill review some of the basics in Chapter 0, but if classes and objects are unfamiliar to you, I suggest watching my p5.js or Processing object-oriented video tutorials, both also available at the Coding Train (<a href="https://thecodingtrain.com/oop"><em>https://thecodingtrain.com/oop</em></a>).</p>
<h2 id="how-are-you-reading-this-book">How Are You Reading This Book?</h2>
<p>Are you reading this book on a Kindle? Printed paper? On your laptop in PDF form? On a tablet showing an animated HTML5 version? Are you strapped to a chair, absorbing the content directly into your brain via a series of electrodes, tubes, and cartridges?</p>
<p>My dream has always been to write the book in one single format (in this case, a collection of Notion documents) and then, after pressing a magic button (<code>npm run build</code>), out comes the book in any and all formats you might want—PDF, HTML5, printed hardcopy, Kindle, and so on. This was largely made possible by the <a href="https://github.com/magicbookproject/">Magic Book project</a>, an open source framework for self-publishing originally developed at <a href="http://itp.nyu.edu/">ITP</a> by Rune Madsen and Steve Klise. Everything has been designed and styled using CSS—no manual typesetting or layout.</p>
<p>The reality of putting this book together isnt quite so clean as that, and the story of how it happened is long. If youre interested in learning more, make sure to read the books acknowledgements, and then go hire the people Ive thanked to help you publish a book! Also, Ill include more details in the associated GitHub repository at the “nature-of-code” GitHub organization pages.</p>
<p>The bottom line is that no matter what format youre reading in, the material is all the same. The only difference will be in how you experience the code examples—more on that in the “How to Read the Code” section.</p>
<p>My dream has always been to write this book in one single format (in this case, a collection of Notion documents) and then, after pressing a magic button (<code>npm run build</code>), out comes the book in any and all formats you might want—PDF, HTML5, printed hard copy, Kindle, and so on. This was largely made possible by the <a href="https://github.com/magicbookproject/">Magic Book project</a>, an open source framework for self-publishing originally developed at <a href="http://itp.nyu.edu/">ITP</a> by Rune Madsen and Steve Klise. Everything has been designed and styled using CSS—no manual typesetting or layout.</p>
<p>The reality of putting this book together isnt quite so clean as that, and the story of how it happened is long. If youre interested in learning more, make sure to read the books acknowledgments, and then go hire the people Ive thanked to help you publish a book! Also, Ill include more details in the associated GitHub repository at <a href="https://github.com/nature-of-code"><em>https://github.com/nature-of-code</em></a>.</p>
<p>The bottom line is that no matter what format youre reading in, the material is all the same. The only difference will be in how you experience the code examples—more on that in “How to Read the Code” on page XX.</p>
<h3 id="the-coding-train-connection">The Coding Train Connection</h3>
<p>Personally, I still love an assembled amalgamation of cellulose pulp, meticulously bound together with a resilient spine, upon which pigmented compounds have been artfully deployed to convey words and ideas. Yet, ever since 2012, when I impulsively recorded my very first video lesson about programming in my office at ITP, Ive discovered that theres tremendous value and joy in conveying ideas and lessons through moving pictures.</p>
<p>All this is to say, I have a YouTube channel called The Coding Train. I mentioned it earlier when discussing options for learning the prerequisite material for this book, and if you continue reading, youll find I continue to reference related videos. I might allude to one I made about a related algorithm or alternative technique for a particular coding example, or suggest a series on a tangential concept that could provide additional context to a topic Im exploring.</p>
<p>If video learning is your style, Im also working on an accompanying set of video tutorials that follow the exact same material as this book. I made a whole bunch 10 years ago with Processing, and more recently I started publishing a series of updated ones with p5.js. At the time of this writing, Im about half way through Chapter 5.</p>
<p>Personally, I still love an assembled amalgamation of cellulose pulp, meticulously bound together with a resilient spine, upon which pigmented compounds have been artfully deployed to convey words and ideas. Yet, ever since 2012, when I impulsively recorded my very first video lesson about programming in my office at ITP, Ive discovered the tremendous value and joy in conveying ideas and lessons through moving pictures.</p>
<p>All this is to say, I have a YouTube channel called the Coding Train. I mentioned it earlier when discussing options for learning the prerequisite material for this book, and if you continue reading, youll find I continue to reference related videos. I might allude to one I made about a related algorithm or alternative technique for a particular coding example, or suggest a series on a tangential concept that could provide additional context to a topic Im exploring.</p>
<p>If video learning is your style, Im also working on an accompanying set of video tutorials that follow the exact same material as this book. I made a whole bunch 10 years ago with Processing, and more recently I started publishing a series of updated ones with p5.js. At the time of this writing, Im about halfway through Chapter 5.</p>
<h3 id="additional-resources">Additional Resources</h3>
<p>Theres also an abundance of exceptional educational material teaching simulation and generative algorithms that I did not write or record. I always recommend that you explore various perspectives and voices when attempting to learn something new. Its possible that what Ive written might not click with you, and even hearing me repeat the same information in video form, regardless of how much mugging I do for the camera, wont help. Sometimes whats best is someone else you can relate to writing or saying or demonstrating the same concepts in different words with a different style. To this end, Im including a “Further Reading and Watching” section on this books website. If you create your own materials or have any recommendations for inclusion, please get in touch!</p>
<p>Two quick recommendations I have right now are <em>The Computational Beauty of Nature</em> by Gary William Flake (1998)—its where I originally learned a lot of the ideas inside this book—and the superbly organized online resource “That Creative Code Page” by Taru Muhonen and Raphaël de Courville.</p>
<p>Theres also an abundance of exceptional educational material teaching simulation and generative algorithms that I did not write or record. I always recommend that you explore various perspectives and voices when attempting to learn something new. Its possible that what Ive written might not click with you, and even hearing me repeat the same information in video form, regardless of how much mugging I do for the camera, wont help. Sometimes whats best is someone else you can relate to writing or saying or demonstrating the same concepts in different words with a different style. To this end, Im including an “Additional Resources” section on this books website. If you create your own materials or have any recommendations for inclusion, please get in touch!</p>
<p>Two quick recommendations I have right now are <em>The Computational Beauty of Nature</em> by Gary William Flake (MIT Press, 1998)—its where I originally learned a lot of the ideas for this book—and the superbly organized online resource “That Creative Code Page” by Taru Muhonen and Raphaël de Courville (<a href="https://thatcreativecode.page/"><em>https://thatcreativecode.page</em></a>).</p>
<h2 id="the-story-of-this-book">The “Story” of This Book</h2>
<p>If you glance over the books table of contents, youll notice there are 12 chapters (011!), each one covering a different topic. And in one sense, this book is just that—a survey of a dozen concepts and associated code examples. Nevertheless, in putting together the material, I always imagined something of a linear narrative. Before you begin reading, Id like to walk you through this story.</p>
<p>If you glance over the books table of contents, youll notice 12 chapters (011!), each one covering a different topic. And in one sense, this book is just that—a survey of a dozen concepts and associated code examples. Nevertheless, in putting together the material, I always imagined something of a linear narrative. Before you begin reading, Id like to walk you through this story.</p>
<h3 id="part-1-inanimate-objects">Part 1: Inanimate Objects</h3>
<p>A soccer ball lies in the grass. A kick launches it into the air. Gravity pulls it back down. A heavy gust of wind keeps it afloat a moment longer until it falls and bounces off the head of a jumping player. The soccer ball isnt alive; it makes no choices as to how it will move throughout the world. Rather, its an inanimate object waiting to be pushed and pulled by the forces of its environment.</p>
<p>How would you model a soccer ball moving in a digital canvas? If youve ever programmed a circle moving across a screen, then youve probably written the following line of code:</p>
<p>A soccer ball lies in the grass. A kick launches it into the air. Gravity pulls it back down. A heavy gust of wind keeps it afloat a moment longer until it falls and bounces off the head of a jumping player. The soccer ball isnt alive; it makes no choices as to how it will move through the world. Rather, its an inanimate object waiting to be pushed and pulled by the forces of its environment.</p>
<p>How would you model a soccer ball moving in a digital canvas? If youve ever programmed a circle moving across a screen, youve probably written the following line of code:</p>
<pre class="codesplit" data-code-language="javascript">x = x + 1;</pre>
<p>You draw some shape at position <code>x</code>. With each frame of animation, you increment the value of <code>x</code>, redraw the shape, and voila—the illusion of motion! Maybe you took it a step or two further, and included a <code>y</code> position, as well as variables for speed along the x- and y-axes.</p>
<p>You draw a shape at position <code>x</code>. With each frame of animation, you increment the value of <code>x</code>, redraw the shape, and voila—the illusion of motion! Maybe you took it a step or two further and included a <code>y</code> position, as well as variables for speed along the x- and y-axes:</p>
<pre class="codesplit" data-code-language="javascript">x = x + xspeed;
y = y + yspeed;</pre>
<p>Part 1 of this story will take this idea even further. After exploring how to use different flavors of randomness to drive an objects motion (<strong>Chapter 0</strong>), Im going to take these <code>xspeed</code> and <code>yspeed</code> variables and demonstrate how together they form a vector (<strong>Chapter 1</strong>). You wont get any new functionality out of this, but it will build a solid foundation for programming motion in the rest of the book.</p>
<p>Once you know a little something about vectors, youre going to quickly realize that a force (<strong>Chapter 2</strong>) is a vector. Kick a soccer ball and youre applying a force. What does a force cause an object to do? According to Isaac Newton, force equals mass times acceleration, so that force causes an object to accelerate. Modeling forces will allow you to create systems with dynamic motion where objects move according to a variety of rules.</p>
<p>Once you know a little something about vectors, youre going to quickly realize that a force (<strong>Chapter 2</strong>) is a vector. Kick a soccer ball and youre applying a force. What does a force cause an object to do? According to Isaac Newton, force equals mass times acceleration, so that force causes an object to accelerate. Modeling forces will allow you to create systems with dynamic motion, in which objects move according to a variety of rules.</p>
<p>Now, that soccer ball to which you applied a force might have also been spinning. If an object moves according to its <em>linear</em> acceleration, it can spin according to its <em>angular</em> acceleration (<strong>Chapter 3</strong>). Understanding the basics of angles and trigonometry will allow you to model rotating objects as well as grasp the principles behind oscillating motion, like a pendulum swinging or a spring bouncing.</p>
<p>Once youve tackled the basics of motion and forces for an individual inanimate object, Ill demonstrate how to make thousands upon thousands of those objects and manage them as a single unit called a particle system (<strong>Chapter 4</strong>). Particle systems are also a good excuse to look at some additional features of object-oriented programming, namely inheritance and polymorphism.</p>
<p>Once youve tackled the basics of motion and forces for an individual inanimate object, Ill demonstrate how to make thousands upon thousands of those objects and manage them as a single unit called a <em>particle system</em> (<strong>Chapter 4</strong>). Particle systems are also a good excuse to look at some additional features of object-oriented programming—namely, inheritance and polymorphism.</p>
<h3 id="part-2-its-alive">Part 2: Its Alive!</h3>
<p>What does it mean to model life? Not an easy question to answer, but Ill begin by building objects that have an ability to perceive their environment. Lets think about this for a moment. A block that falls off a table moves according to forces, as does a dolphin swimming through the water. But theres a key difference: the block cant decide to leap off the table, whereas the dolphin can decide to leap out of the water. The dolphin has dreams and desires. It feels hunger or fear, and those feelings inform its movements. By examining techniques behind modeling autonomous agents (<strong>Chapter 5</strong>), youll learn to breathe life into inanimate objects, allowing them to make decisions about their movements according to their understanding of their environment.</p>
<p>In Chapters 1 through 5, all of the examples will be written “from scratch”—meaning the code for the algorithms driving the motion of the objects will be written directly in p5.js. Im certainly not the first programmer ever to consider the idea of simulating physics and life in animation, however, so next Ill examine how you can use physics libraries (<strong>Chapter 6</strong>) to model more sophisticated behaviors. Ill look at the features of two libraries: Matter.js and toxiclibs.js.</p>
<p>The end of Chapter 5 will explore group behaviors that exhibit the properties of complexity. A complex system is typically defined as a system thats more than the sum of its parts. While the individual elements of the system may be incredibly simple and easily understood, the behavior of the system as a whole can be highly complex, intelligent, and difficult to predict. Chasing complexity will lead you away from thinking purely about modeling motion and into the realm of rule-based systems. What can you model with cellular automata (<strong>Chapter 7</strong>), systems of cells living on a grid? What types of patterns can you generate with fractals (<strong>Chapter 8</strong>), the geometry of nature?</p>
<p>In Chapters 1 through 5, all the examples will be written “from scratch”—meaning the code for the algorithms driving the motion of the objects will be written directly in p5.js. Im certainly not the first programmer ever to consider the idea of simulating physics and life in animation, however, so next Ill examine how you can use physics libraries (<strong>Chapter 6</strong>) to model more sophisticated behaviors. Ill look at the features of two libraries: Matter.js and toxiclibs.js.</p>
<p>The end of Chapter 5 will explore group behaviors that exhibit the properties of complexity. A complex system is typically defined as a system thats more than the sum of its parts. While the individual elements of the system may be incredibly simple and easily understood, the behavior of the system as a whole can be highly complex, intelligent, and difficult to predict. Chasing complexity will lead you away from thinking purely about modeling motion and into the realm of rule-based systems. What can you model with cellular automata (<strong>Chapter 7</strong>), systems of cells living on a grid? What types of patterns can you generate with fractals (<strong>Chapter 8</strong>), the geometry of nature?</p>
<h3 id="part-3-intelligence">Part 3: Intelligence</h3>
<p>You made things move. Then you gave those things hopes and dreams and fears, along with rules to live by. The last step in this book will bring intelligent decision-making into your creations. Can you apply the biological process of evolution to computational systems (<strong>Chapter 9</strong>) in order to evolve the behavior of autonomous agents? Taking inspiration from the human brain, can you program an artificial neural network (<strong>Chapter 10</strong>)? How can agents make decisions, learn from their mistakes, and adapt to their environment (<strong>Chapter 11)</strong>?</p>
<p>You made things move. Then you gave those things hopes and dreams and fears, along with rules to live by. The last step in this book will bring intelligent decision-making into your creations. Can you apply the biological process of evolution to computational systems (<strong>Chapter 9</strong>) in order to evolve the behavior of autonomous agents? Taking inspiration from the human brain, can you program an artificial neural network (<strong>Chapter 10</strong>)? How can agents make decisions, learn from their mistakes, and adapt to their environment (<strong>Chapter 11</strong>)?</p>
<h2 id="using-this-book-as-a-syllabus">Using This Book as a Syllabus</h2>
<p>While the content in this book certainly makes for an intense and highly compressed semester, Ive designed it to fit into a 14-week course. I find that some chapters work better expanded across multiple weeks, while others can be combined and explored together in a single week. Heres one possible syllabus:</p>
<table>
@ -98,7 +98,7 @@ y = y + yspeed;</pre>
<td>Final project discussion</td>
</tr>
<tr>
<td>Weeks 12-13</td>
<td>Weeks 1213</td>
<td>Final project workshop</td>
</tr>
<tr>
@ -109,7 +109,7 @@ y = y + yspeed;</pre>
</table>
<p>If youre considering using this text for a course or workshop, please feel free to contact me. I hope to eventually finish the companion set of videos, as well as include helpful slides as supplementary educational materials. If you make your own, Id love to hear about it!</p>
<h2 id="how-to-read-the-code">How to Read the Code</h2>
<p>Code is the main medium of this book, weaving throughout the narrative as its dissected and examined. Sometimes it appears as full, standalone examples, other times it drops in as a single line or two, and often its stretched over whole sections in many short snippets, with explanations nestled in between. Whatever form it takes, code will always appear in a <code>monospaced font</code>. Heres a quick guide on how to navigate the different types of code sprinkled throughout the book.</p>
<p>Code is the main medium of this book, weaving throughout the narrative as its dissected and examined. Sometimes it appears as full, standalone examples, other times it drops in as a single line or two, and often its stretched over whole sections in many short snippets, with explanations nestled in between. Whatever form it takes, code will always appear in a <code>monospaced font</code>. Heres a quick guide on how to navigate the types of code sprinkled throughout the book.</p>
<h3 id="full-examples">Full Examples</h3>
<p>Each chapter includes fully functional code examples that are written with the p5.js library. Heres what they look like:</p>
<div data-type="example">
@ -128,20 +128,20 @@ y = y + yspeed;</pre>
function draw() {
fill(0, 25);
stroke(0, 50);
//{!1} Draw a random circle each time through draw.
//{!1} Draw a random circle each time through draw().
circle(random(width),random(height), 16)
}</pre>
<p>The examples are numbered sequentially within each chapter to help you find the corresponding code online. In the printed version of the book, youll see a screenshot right below the example title. The online version has the running sketch embedded right there on the page. For animated examples (which are almost all of them), the screenshots will often show a “trail” of motion. This effect was achieved by adding transparency to the <code>background(255, 10)</code> function, though the accompanying code wont include that enhancement.</p>
<p>Below the example, youll find the code, but its not always the <em>complete </em>code. Since many examples are quite long and span multiple files, I make my best effort to include a snippet that highlights the main aspects of the example or whatever new components are being introduced that werent already discussed earlier in the section.</p>
<p>You can find the full version of the code on the books website. There, you can interact with, modify, and experiment with the code in the <a href="https://editor.p5js.org/natureofcode/sketches/u4vTwZuhT">p5.js Web Editor</a>. Additionally, everything is included in the books GitHub repository. Here are the full URLs to access all of the materials:</p>
<p>You can find the full version of the code on the books website. There, you can interact with, modify, and experiment with the code in the <a href="https://editor.p5js.org/natureofcode/sketches/u4vTwZuhT">p5.js Web Editor</a>. Additionally, everything is included in the books GitHub repository. Here are the full URLs to access all the materials:</p>
<ul>
<li><a href="https://natureofcode.com/">https://natureofcode.com</a></li>
<li><a href="https://github.com/nature-of-code">https://github.com/nature-of-code</a></li>
<li><a href="https://editor.p5js.org/natureofcode/sketches">https://editor.p5js.org/natureofcode/sketches</a></li>
<li><a href="https://natureofcode.com/"><em>https://natureofcode.com</em></a></li>
<li><a href="https://github.com/nature-of-code"><em>https://github.com/nature-of-code</em></a></li>
<li><a href="https://editor.p5js.org/natureofcode/sketches"><em>https://editor.p5js.org/natureofcode/sketches</em></a></li>
</ul>
<p>Notice how Ive used comments in the example to address whats happening in the code. These comments float next to the code (though the appearance may vary depending on where youre reading the book). The background highlighting groups the comments with their corresponding lines of code.</p>
<p>Notice that Ive used comments in the example to address whats happening in the code. These comments float next to the code (though the appearance may vary depending on where youre reading the book). The background highlighting groups the comments with their corresponding lines of code.</p>
<h3 id="complete-snippets">Complete Snippets</h3>
<p>Though rare, there are occasionally “complete” sections of code mixed in with the body text. Sometimes, like with the sample “Example #.#” in the previous section, I might actually list all of the code associated with a complete p5.js sketch. In most cases, however, Im considering a “complete” snippet to be the code for an entire function or a class—a fully finished block of code, complete with opening and closing curly brackets and everything in between. Something like this:</p>
<p>Though rare, “complete” sections of code are occasionally mixed in with the body text. Sometimes, as with the sample “Example #.#” in the previous section, I might actually list all the code associated with a complete p5.js sketch. In most cases, however, Im considering a “complete” snippet to be the code for an entire function or a class—a fully finished block of code, complete with opening and closing curly brackets and everything in between. Something like this:</p>
<pre class="codesplit" data-code-language="javascript">// The entire draw() function for an example
function draw() {
background(255);
@ -152,22 +152,22 @@ function draw() {
}</pre>
<p>This snippet shows the entire <code>draw()</code> function, but it still isnt a complete sketch. It assumes the existence of a global variable called <code>spacing</code>, as well as a <code>setup()</code> function that calls <code>createCanvas()</code>.</p>
<h3 id="context-free-code">Context-Free Code</h3>
<p>Occasionally, youll find lines of code hanging out on the page without a surrounding function or context. These snippets are there to illustrate a point, not necessarily to be run as-is. They might represent a concept, a tiny piece of an algorithm, or a coding technique.</p>
<p>Occasionally, youll find lines of code hanging out on the page without a surrounding function or context. These snippets are there to illustrate a point, not necessarily to be run as is. They might represent a concept, a tiny piece of an algorithm, or a coding technique:</p>
<pre class="codesplit" data-code-language="javascript"> // RGB values to make the circles pink
fill(240, 99, 164);</pre>
<p>Notice how this “context-free” snippet matches the indentation of <code>fill(255)</code> in the previous “complete” snippet. Ill do this when some code has been established to be part of a something demonstrated previously. Admittedly, this wont always work out so cleanly or perfectly, but Im doing my best!</p>
<p>Notice that this context-free snippet matches the indentation of <code>fill(255)</code> in the previous “complete” snippet. Ill do this when the code has been established to be part of a something demonstrated previously. Admittedly, this wont always work out so cleanly or perfectly, but Im doing my best!</p>
<h3 id="snipped-code">Snipped Code</h3>
<p>Be on the lookout for the scissors! This design element indicates that a code snippet is a continuation of a previous piece or will be continued after some explanatory text. Sometimes, its not actually being continued but is just cut off because the rest of what would be written isnt relevant to the discussion at hand. The scissors are there to say, “Hey, there might be more to this code above or below, or at the very least, this is a part of something bigger!” Heres how this might play out with some surrounding body text.</p>
<p>The first step to building a p5.js sketch is to create a canvas.</p>
<p>Be on the lookout for the scissors! This design element indicates that a code snippet is a continuation of a previous piece or will be continued after some explanatory text. Sometimes its not actually being continued but is just cut off because all the code isnt relevant to the discussion at hand. The scissors are there to say, “Hey, there might be more to this code above or below, or at the very least, this is a part of something bigger!” Heres how this might play out with some surrounding body text:</p>
<p>The first step to building a p5.js sketch is to create a canvas:</p>
<div class="snip-below">
<pre class="codesplit" data-code-language="javascript">function setup() {
createCanvas(640, 240);</pre>
</div>
<p>Then its time to draw the background.</p>
<p>Then its time to draw the background:</p>
<div class="snip-above snip-below">
<pre class="codesplit" data-code-language="javascript"> background(255);</pre>
</div>
<p>I also like to include a circle in the center of the canvas.</p>
<p>I also like to include a circle in the center of the canvas:</p>
<div class="snip-above">
<pre class="codesplit" data-code-language="javascript"> circle(width / 2, height /2, 200);
}</pre>
@ -178,13 +178,13 @@ function draw() {
rectMode(CENTER);
square(random(width), random(height), 20);</pre>
</div>
<p>Notice again how Im keeping the indentation consistent to try to help establish the context, while using the scissors icon to help indicate where code is continued or cut off.</p>
<p>Notice again that Im keeping the indentation consistent to try to help establish the context, while using the scissors icon to help indicate where code is continued or cut off.</p>
<p>A particular side effect of using snipped code is that youll often notice opening curly brackets in one snippet that dont have a corresponding closing bracket until several snippets later (if at all). If youre used to looking at JavaScript code, this may initially send you into a mild panic, but hopefully youll get used to it.</p>
<h2 id="exercises">Exercises</h2>
<p>Each chapter includes numbered exercises that serve as your playground to apply, experiment with, and go beyond the concepts and code provided within the chapters. Heres what an exercise might look like:</p>
<div data-type="exercise">
<h3 id="exercise-">Exercise #.#</h3>
<p>Try tweaking Example #.# so that each circle has a random size.</p>
<p>Try tweaking Example #.# so that each circle has a random size:</p>
<pre class="codesplit" data-code-language="javascript">function draw() {
fill(0, 25);
stroke(0, 50);
@ -193,12 +193,12 @@ function draw() {
</div>
<p>To keep you on your toes, the exercises come in a variety of formats. Some pose technical challenges, asking you to write a variation of a specific algorithm or solve a highly specific problem. Others are open-ended inquiries, prompting you to play and experiment, following your own ideas. Some include snippets of code with blank spots, inviting you to fill them in directly. Dont hesitate to write, scribble, or doodle in this very book as you work through them!</p>
<h3 id="solutions">Solutions</h3>
<p>Solutions for the exercises are provided on the books website. Or I should say, I aspire to include solutions for all of the exercises on the books website. As of this moment, there are just a handful, but hopefully by the time youre reading this there will be many more. If youd like to contribute a solution to an exercise, I would love for you to do so via the books GitHub repository!</p>
<p>Solutions for the exercises are provided on the books website. Or I should say, I aspire to include solutions for all the exercises on the books website. As of this moment, just a handful are available, but hopefully by the time youre reading this, there will be many more. If youd like to contribute a solution to an exercise, I would love for you to do so via the books GitHub repository!</p>
<h3 id="the-ecosystem-project">The Ecosystem Project</h3>
<p>As much as Id like to pretend you could learn everything by curling up in a comfy chair and reading some prose, to learn programming, youre really going to have to do some programming. The exercises scattered throughout each chapter are a start, but you might find it helpful to also keep in mind a more substantial project idea (or two) that you can develop as you go from chapter to chapter. In fact, when teaching my Nature of Code course at ITP, Ive often found that students enjoy building a single project, step by step, week by week, over the course of the semester.</p>
<p>At the end of each chapter, youll find a series of prompts for one such project—exercises that build on each other, one topic at a time. Consider the following scenario. Youve been asked by a science museum to develop the software for a new exhibit, the Digital Ecosystem, a world of animated, procedural creatures that live in a computer simulation for visitors to enjoy as they enter the museum. I dont mean to suggest that this is a particularly innovative or creative concept. Rather, Ill use this example Ecosystem Project idea as a literal representation of the content in the book, demonstrating how the elements cam fit together in a single program. I encourage you to develop your own idea, one thats perhaps more abstract and non-traditional in its thinking.</p>
<p>As much as Id like to pretend you could learn everything by curling up in a comfy chair and reading some prose, to learn programming, youre really going to have to do some programming. The exercises scattered throughout each chapter are a start, but you might find it helpful to also keep in mind a more substantial project idea (or two) that you can develop as you go from chapter to chapter. In fact, when teaching my Nature of Code course at ITP, Ive often found that students enjoy building a single project, step by step, week by week, over the course of the semester.</p>
<p>At the end of each chapter, youll find a series of prompts for one such project—exercises that build on each other, one topic at a time. This project is based on the following scenario. Youve been asked by a science museum to develop the software for a new exhibit, the Digital Ecosystem, a world of animated, procedural creatures that live in a computer simulation for visitors to enjoy as they enter the museum. I dont mean to suggest that this is a particularly innovative or creative concept. Rather, Ill use this example Ecosystem Project idea as a literal representation of the content in the book, demonstrating how the elements can fit together in a single program. I encourage you to develop your own idea, one thats perhaps more abstract and nontraditional.</p>
<h2 id="getting-help-and-submitting-feedback">Getting Help and Submitting Feedback</h2>
<p>Coding can be tough and frustrating, and the ideas in this book arent always straightforward. You dont have to go it alone. Theres probably someone else reading right now who would love to co-organize a study group or a book club where you can meet, chat, and share your struggles and successes. If you dont find a local community for traveling this journey together, what about an online one? Two places Id suggest are the official Processing forums (<em>discourse.processing.org</em>) and the Coding Train Discord server (<em>thecodingtrain.com/discord</em>).</p>
<p>I consider the online version of this book a living document and welcome your feedback. For all things book-related, please visit the <a href="http://www.natureofcode.com/">Nature of Code website</a>: <em>https://natureofcode.com</em>. The raw source text of the book and all of the illustrations are on <a href="https://github.com/nature-of-code/noc-book-2">GitHub</a> under the “nature-of-code” organization account. Please leave feedback and submit corrections using GitHub issues.</p>
<p>More important, I want to see what you make! You can share your ideas by submitting to the passenger showcase on the Coding Train website, or in the channels on the aforementioned Discord. A hello in a YouTube comment is always welcome (although to be honest, its often best not to read the comments on YouTube), and feel free to tag me on whatever platform the future of social media has to offer—whichever one is the friendliest and least toxic! I want to enjoy all the bloops that swim in your ecosystem. Whether they leap triumphantly over a wave of creativity or a make a tiny splash in a pond of learning, lets bask in the ripples they send through the nature of coding!</p>
<p>Coding can be tough and frustrating, and the ideas in this book arent always straightforward. You dont have to go it alone. Theres probably someone else reading right now who would love to co-organize a study group or a book club where you can meet, chat, and share your struggles and successes. If you dont find a local community for traveling this journey together, what about an online one? Two places Id suggest are the official Processing forums (<a href="https://discourse.processing.org/"><em>https://discourse.processing.org</em></a>) and the Coding Train Discord server (<a href="https://thecodingtrain.com/discord"><em>https://thecodingtrain.com/discord</em></a>).</p>
<p>I consider the online version of this book a living document and welcome your feedback. For all things book related, please visit the Nature of Code website: <a href="https://natureofcode.com/"><em>https://natureofcode.com</em></a>. The raw source text of the book and all the illustrations are on GitHub at <a href="https://github.com/nature-of-code"><em>https://github.com/nature-of-code</em></a>. Please leave feedback and submit corrections by using GitHub issues.</p>
<p>More important, I want to see what you make! You can share your ideas by submitting to the passenger showcase on the Coding Train website, or in the channels on the aforementioned Discord. A hello in a YouTube comment is always welcome (although to be honest, its often best not to read the comments on YouTube), and feel free to tag me on whatever platform the future of social media has to offer—whichever one is the friendliest and least toxic! I want to enjoy all the bloops that swim in your ecosystem. Whether they leap triumphantly over a wave of creativity or make a tiny splash in a pond of learning, lets bask in the ripples they send through the nature of coding!</p>
</section>