Introduction to Game Programming using Processing For Designers Artists Players Non Tech People and Everybody Else 1st Edition Daniel Cermak-Sassenrath 2025 Scribd Download
Introduction to Game Programming using Processing For Designers Artists Players Non Tech People and Everybody Else 1st Edition Daniel Cermak-Sassenrath 2025 Scribd Download
https://ebookfinal.com/download/processing-a-programming-handbook-for-
visual-designers-and-artists-second-edition-casey-reas/
https://ebookfinal.com/download/c-game-programming-for-serious-game-
creation-1st-edition-daniel-schuller/
https://ebookfinal.com/download/c-game-programming-for-serious-game-
creation-1st-edition-daniel-schuller-2/
https://ebookfinal.com/download/opengl-game-programming-prima-tech-s-
game-development-1st-edition-kevin-hawkins/
Ray Davies Not Like Everybody Else 2007 1st Edition Thomas
Kitts
https://ebookfinal.com/download/ray-davies-not-like-everybody-
else-2007-1st-edition-thomas-kitts/
https://ebookfinal.com/download/the-artist-s-guide-to-gimp-2nd-
edition-creative-techniques-for-photographers-artists-and-designers-
michael-hammel/
https://ebookfinal.com/download/introduction-to-scientific-
programming-and-simulation-using-r-2nd-edition-owen-jones/
https://ebookfinal.com/download/introduction-to-3d-game-programming-
with-directx-10-1st-edition-frank-d-luna/
This is an introductory textbook focusing on games (specifically interaction and graphics) as a pathway
into programming. It empowers readers to do basic programming, prototyping, game creation, and other
highly interactive applications, all from scratch and without any prior programming knowledge.
Using the popular programming language Processing, this book describes, explains, and demonstrates the
basic and general programming principles and mechanisms used in typical game algorithms and concrete
game projects. Chapters cover basic graphics, text output, loops, data types and variables, movement,
time, audio and sound, debugging, classes and objects, event-based programming, real-time input con-
trols, computer speed compensation, animation, tiling, scrolling, collision detection, basic AI, and much
more. Additional support materials such as code examples and demo programs are available to download
from this book’s webpage.
This book is a great resource for students and aspiring professionals looking for an approachable entry
into game programming.
Daniel Cermak-Sassenrath
First edition published 2024
by CRC Press
2385 NW Executive Center Drive, Suite 320, Boca Raton FL 33431
Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume
responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted
to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission
to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us
know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or uti-
lized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopy-
ing, microfilming, and recording, or in any information storage or retrieval system, without written permission from the
publishers.
For permission to photocopy or use material electronically from this work, access www.copyright.com or contact the
Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works that are not
available on CCC please contact [email protected]
Trademark Notice: Product or corporate names may be trademarks or registered trademarks and are used only for iden-
tification and explanation without intent to infringe.
DOI: 10.1201/9781003345916
Foreword................................................................................................................................................... vii
Preface....................................................................................................................................................... ix
Acknowledgements.................................................................................................................................... xi
Introduction..............................................................................................................................................xiii
7. Relational Expressions (e.g. <, >) and Logical Operators (e.g. &&, ||)...................................... 53
9. Short Cuts........................................................................................................................................ 67
13. Arrays............................................................................................................................................... 84
14. Functions.......................................................................................................................................... 94
v
vi Contents
22. Images..............................................................................................................................................151
23. The Processing IDE, Technical Documentation, Debugging and Common Errors............... 156
Glossary..................................................................................................................................................311
References...............................................................................................................................................313
Code Index..............................................................................................................................................317
Subject Index..........................................................................................................................................321
Foreword
Toke Krainert
Senior Technical Level Designer, IO Interactive,
Copenhagen, October 2023
vii
Preface
This is the book I wish I had when I started out to learn programming, in the mid-1980s. It would have
changed my life. Back then it was tricky to learn such an obscure skill. There was no Internet, of course,
and the few resources that were available to me were pretty inaccessible. For instance, I had the techni-
cal documentation for BASIC which listed and explained all commands of the language in alphabetical
order. Over time I acquired some programming books, but all of them were pretty stiff, and I didn’t even
know how to start. None of them worked for me. The magazines of the day were glorious; some focused
on hardware and many on games. In my recollection, at least, the magazines that focused on program-
ming, mostly featured long listings of program code; but typing-in many pages of, at the time, incompre-
hensible gibberish, did not appeal to me. Some of my friends had computers and were also interested, but
they knew even less than me, and I had no idea. Having a computer was seen, in the best case, a weird
hobby, and otherwise as a social stigma (not as a career move, as happened a decade or two later, and not
as an ubiquitous part of modern life, as today).
Today, computers have won – many people carry one (or several of them) on them at all times, many
attend to it day and night, and a myriad of productive and unproductive applications exist, and it is almost
unthinkable to live without it. Access to education about digital media is abundant; school courses, books
and online resources cater to many various and specialised interests.
Games have been a great attraction of home computers in the 1980s, and for many non-tech people,
they were the first point of contact with the novel medium. A considerable number of these people
were, in fact, children. For many of them, games became a pathway into programming. Collins (2022)
comments that ‘children in the 1980s might have become interested in computers because of games,
but the nature of computers at the time meant that many of them got into programming almost by
accident’. Digital games are still, and probably more than ever, a popular path into competent com-
puter use.
In the last 20 years, there has been an unbelievable cultural and economic boost to the field of digital
media. Where only a handful of geeks were interacting with computers before, ignored by a worried
(in the case of gamers) and scared society (in the case of hackers), there are now billions of ordinary
people and members of the general public using and playing with computers. But it appears, after several
decades of strong innovation, exponential growth, upward mobility and several spectacular and unusual
careers (for instance, of early IT entrepreneurs whose names are well-known today), that a gap is widen-
ing between the increasing professionalism of the producers with specialisations of sophisticated skills,
and the end users and consumers of digital media. Digital media becomes more mainstream, and at the
same time, the distance increases between the producers and the increasingly numerous, diverse and
likely less tech-savvy users. This division between the pros and the amateurs has happened with other
technologies before, for instance, with the motor car.
Tech is becoming increasingly like rocket science – far removed from and closed to the general
public. It is even dangerous; sharing self-written programs is almost made impossible in some recent
operating systems. The operating system informs the user: This software was downloaded from the
Internet and is not signed by an official developer registered with the computer manufacturer – so, no,
sorry, you can’t run this. Let’s delete it (Figure 0.1)!2 In today’s digital media, users better leave their
hands off the machine and buy and use software that is made for them. The early days, when digital
culture was fuelled and propelled forward and inspired by ideas (and illusions) of societal progress,
individual freedom, participation, and a better future for all through the digital computer, of everybody
making and sharing software collectively and for free, seem to be over for most people. But competent
computer use needs programming. The medium of the computer can arguably only be understood,
appreciated and fully utilised when users have at least basic knowledge about what computers can do
and how they work.
ix
x Preface
FIGURE 0.1 The OS protects the users from themselves: Downloaded programs which are not officially signed by devel-
opers registered with the manufacturer cannot be run (the OS (wrongly) claims that the file was corrupt, and offers to delete
it; macOS 12.6)
This book is an attempt to support non-tech people such as designers, artists, players, other non-tech
people and the interested public, to start programming, hopefully, in a fun and accessible way: Games
as a pathway into programming. It empowers readers to do basic programming, prototyping, creat-
ing games and other highly interactive applications, and to talk competently with tech people. This is
also an entry-level introduction to programming with examples in the popular language Processing.
Basic and general programming principles and mechanisms are described, explained, demonstrated and
applied in typical game algorithms and concrete game projects.
Acknowledgements
The book is based on my course Introduction to Programming for (Game) Designers that I have been
teaching for more than ten years, first at the Creative Technologies programme at Auckland University
of Technology (AUT) in New Zealand, and then at the Games’ Programme at the ITU in Copenhagen,
Denmark. I got the idea to turn the course materials into a book when I heard that students were passing
around the course materials to their friends who were not taking the course but were keen on learning
programming.
I’d like to thank the many students who have been taking the course, from within and without the ITU,
for their enthusiasm and energy that have kept the course (and me) going. Also, my co-teachers along the
way, for their invaluable contributions and company, the many TAs for their essential work, and every-
body else who supported this project over the years. Finally, Will Bateman at Routledge/CRC Press for
believing in the book and his friendly and professional support to make it happen.
xi
Introduction
Outline
• Motivation
• A Very Brief History of Programming
• Programming Needs Diversity
• How this Book Works
Motivation
The computer has entered all areas of people’s lives, media and culture – with digital games and their
popularity being one of the very visible expressions of this trend. Because of their lack of technical
expertise, non-tech people regularly have limited possibilities to participate in and contribute to the
creation of the digital world, and their innovative ideas might never be known or realised. To know
something about programming is arguably the only way to use a computer to the full extent and a key
skill to substantially participate in and contribute to the brave new digital world.1 This book aims to offer
an accessible pathway into fun, meaningful, skilful and competent computer use. It offers a potentially
disruptive change of perspective, and participants will experience the world of digital media in a differ-
ent way, and be able to participate and contribute in ways they could not before.
Learning to program appears desirable for multiple reasons. It is an inspiring and powerful way of cre-
ative and artistic expression. It is clearly much in-demand in today’s and tomorrow’s job markets. Basic
programming knowledge is an asset in communication: Project work benefits from non-tech people
being able to understand and effectively negotiate with all team members, including the tech people, and
to appreciate their roles and contributions.
This book approaches and presents programming from a hands-on, non-tech, application-centred per-
spective. It is all about the application of programming in practical, genuine design challenges; not
about gathering abstract knowledge, to be used in the future in some other context; but hands-on skills,
to be used here and now. The book aims to facilitate the making of projects people want to have. And
this does not imply little learning or learning on a low level. But learning that centres on motivation and
builds on curiosity.
Arguably, the most interesting things to program are interactive systems for people to use produc-
tively, express themselves and play with each other.2 The computer has been used and it is still often used
as a tool to model other media, e.g. to paint pictures and to cut movies. But increasingly, the computer is
coming into its own, and people start to question its uses and experiment with it, and interact with it in
novel, provocant, and playful ways that were unimaginable before, and which have no precedent.
The book integrates the endeavour to learn programming with a focus on (digital) games. The audi-
ence this book addresses is people interested in games who have no previous experience in coding:
Students of Game Design and other (design) students, DIY indie game designers, freelance design pro-
fessionals, game enthusiasts, but also ordinary people just wanting to learn to program.
Learning to program is not just learning another program or tool; it is a meta-skill similar to learning
the principles of a universal language; people will be able to read one another’s programs and create their
own, share, discuss and collaborate.
xiii
xiv Introduction
• Similar to other skills, e.g. sketching, writing, using Photoshop, Illustrator, Director, dancing,
singing, sports and foreign languages;
• A way of expression that goes beyond (or is simply different from) static representations and
(human, live) performances;
• Required in some exciting areas of design such as interaction design and parametric design;
and
• As useful as reading, writing and math; for instance, for animation, scripting and websites –
and for creating games!
Programming is a unique way to test and communicate ideas about interaction. A player can then do it
himself or herself, and experience it first-hand, directly and immediately, and not just imagine doing it.
It is a difference like hearing about the scene in Pulp Fiction where the guy in the car gets accidentally
shot and watching it oneself. One can’t quite compare one experience with the other.
• To have the first shot at an idea, one can use interactive programs to communicate one’s vision
• Quickly prototype, test and find out if an idea is any good
• Competently communicate with and understand programmers, e.g. as part of a project team
• To use game engines (such as Unity), game makers and tools (such as graphics programs) effec-
tively through scripting
Introduction xv
But most of all, it is tremendously fun!4 It is a kind of magic, but a kind that everybody can command.
It is a tricky challenge, it allows, invites and is based on exploring and discovering what can be done (not
reading the manual), it is uncharted territory. When I program, I can make a digital artefact that was not
there before. I can try out, have control over what happens, test it, see (i.e. experience) what it is and what
it is doing, how it can be used and misused.
FIGURE 0.2 Various Arduino projects: A sensorised boxing bag, a multi-legged walking robot, and a self-driving slot
car (photos by the author)
xvi Introduction
FIGURE 0.3 More Arduino projects: A mobile phone theremin, a wave measuring device, and an air quality sensor (photos
by the author)
by several years (e.g. use of tubes), and inventions were occasionally made almost simultaneously in
different places. Immense gaps separated abstract concepts of computing from technical research,
experiments and inventions from military, commercial and (much later) private use. The moment in
time, when an innovative development became commercially available and successful, rarely corre-
sponded to the order of invention (e.g. the local network was developed in parallel with the mouse and
a windowed interface, but it took more than a decade for it to make its way to a widespread application
by the end user). Magic was not involved in the emergence of the modern computer. It was all mundane,
iterative advances and progress, sometimes in brilliant and surprising leaps, but often painstakingly
slow and basic.
In the last 100 years or so, the development of the computer has exploded. But not only from a techni-
cal perspective but also, and more relevant here, from a user perspective. Using a computer meant for a
long time, programming. And programming could mean changing gears, plugs, punching cardboard, or
entering number codes, commands and more sophisticated structures. The computer user was an opera-
tor. Individuals only own (personal) computers since the 1980s, and commercial off-the-shelf applica-
tion software has only around for a bit longer. Early on, there was no gap between tinkerer, inventor,
developer and user, because everybody who ever came near a computer was a highly-trained expert (the
experts never went away, and are still around; they just became very few compared to the vast number
of (novice) users). Soon, a new class of knowledge workers emerged, computer programmers, specialis-
ing in creating software. The gap started to widen when professional (i.e. non-technical) experts (e.g.
business people) started to use computers in the late 1950s, and attempts to spread the wisdom (BASIC,
LOGO) did not meet with large-scale success. The gap reached its widest point probably by the end of the
1990s, after the massive booms that the video gaming (in the late 1970s), the personal computer (in the
early 1980s) and the popularisation of the Internet (from 1995) triggered. The gap is still immense, and
unlikely to disappear completely, but it is getting smaller: Ordinary people are learning to move beyond
using the computer by clicking (or tapping) on pretty icons; they script, fab, mod, code and hack. This
happens because it is easy and fun, and people have (easy access to) the technical equipment and the
competencies, and are probably also disillusioned with commercial offers and being spied upon. Now
end users and even school children code – programming for all.
Programming has become quite a general skill7; this was proposed since at least the 1970s (e.g. by
Alan Kay), and there have been a number of programming languages aimed at novices, and intended as
introductory paths into programming, such as BASIC, LOGO, Pascal and Java. Processing is a language
made from a similar perspective and proves to be quite popular. Now, arguably, as before, the time has
finally come.
First, the development of programming faced fundamental and hard technical challenges, but begin-
ning from the 1980s the challenge was no longer about raw computing power, speed and resource man-
agement, but the ease of use came into focus. First professionals started to use the computer, e.g. in
engineering and business, followed then increasingly by ordinary people. And these ordinary, non-tech
people are precisely the target group that limited, reduced, simplified languages such as Processing and
scripting addresses. Programming is today on the verge to become a ubiquitous skill, taught, learned
and used as part of a general curriculum, an additional way of expression, and learning, of engagement,
experimentation, similar to math and writing.
What is already clear is that it is now possible to do things with computers that were only fantasies
before. And we are still finding out what this new medium is.
the Internet by the US military). Generally less recognised, so far, are the contributions of women to the
technological progress in computing and programming8.
While also the area of game design is certainly male-dominated, there are several notable examples of
female game designers; the most high-profile, in my view, could be Roberta Williams, who invented the
graphic adventure and designed many very successful games (for instance, the King’s Quest franchise, with
her husband Ken) and Brenda Laurel and her company Purple Moon9; other female designers of famous
games include Mabel Addis (The Sumerian Game), Danielle Bunten Berry (M.U.L.E.), Dona Bailey
(Centipede), Rebecca Heineman (Bard’s Tale series), Sheri Graner Ray (Ultima franchise), Ellen Beeman
(Wing Commander games), Kellee Santiago (Journey), and Kim Swift (Portal, Left 4 Dead)10.
The existing conventions of the digital world are just that, conventions, which people have agreed upon
for various reasons and in various circumstances, and not invariable laws of nature. The people who
made (and make) the decisions might not be representative of (or aware of or interested in) the people
who are affected by them. The digital world could have developed very differently than it has, and it can
certainly develop in any direction in the future.
Diversity and inclusion with regard to, for instance, people’s age, gender, sexual orientation, religion,
ethnicity, nationality, professional experiences, academic education, knowledge, skills and (dis-) abili-
ties can arguably benefit both the processes and the results of collaborative activities. Phillips [2014]
notes that ‘[d]ecades of research by organizational scientists, psychologists, sociologists, economists and
demographers show that socially diverse groups […] are more innovative than homogeneous groups’ and
‘better [prepared] than a homogeneous group at solving complex, nonroutine problems’.
For instance, in an economic context, it is regularly reported ‘that businesses with more diverse work-
forces perform better on a whole range of measures’ (Blackman 2017). In a two-year study on 180 pub-
licly traded companies in four large Western countries, Barta et al. (2012) observe that ‘[c]ompanies with
diverse executive boards [with regard to gender and nationality] enjoy significantly higher earnings and
returns on equity’. A 2014 Gallup poll ‘of more than 800 business units from two companies represent-
ing two different industries – retail and hospitality – finds that gender-diverse business units have better
financial outcomes than those dominated by one gender’ (Badal 2014): A ‘14% higher average compa-
rable revenue’ in the retail sector, and a ‘19% higher average quarterly net profit’ in the hospitality sector
(ibid.). A McKinsey study ‘of 1000 companies in 12 countries [finds] that organisations in the top 25%
when it comes to gender diversity among executive leadership teams were more likely to outperform on
profitability (21%) and value creation (27%)’ [Catalyst 2018].
Ashcraft and Breitzman’s (2012) ‘30-year study of US patents in the IT industry’ observes that mixed-
gender teams ‘produce patents that get cited by other researchers 30–40% more often than average’
(Blackman 2017). On a board of directors, ‘deep-level diversity’, that is, ‘differences in background,
personality, and values’ […] contributed to a higher degree of creativity’ (Catalyst 2018). Other observed
benefits for businesses include retaining talent (ibid.), maximising productivity (ibid.), as well as reduc-
ing groupthink and enhancing decision-making (ibid.). Cognitively diverse teams ‘solve problems faster’
(ibid.). Mixed-gender corporate boards are reported to ‘[h]ave [f]ewer [i]nstances of [f]raud’ and […] are
associated with more effective risk-management practices’ (ibid.).
There might be various problems and trade-offs associated with creating and maintaining diversity
at the workplace. For instance, ‘individual employees may prefer less diverse settings’ (Dizikes 2014)
because ‘more homogeneous offices have higher levels of social capital’ (Sara Ellison qtd. in ibid.).
But MIT economist Ellison (qtd. in ibid.) also points out that the ‘higher levels of social capital are not
important enough to cause those offices to perform better’. While ‘[t]he employees might be happier,
they might be more comfortable, and these might be cooperative places, but they seem to perform less
well’. Progress towards diverse work settings might be slow. In 2019, ‘Google’s [t]ech [s]taff is [o]nly
4.8% African American […] [and] only 1.1% […] is Hispanic, and only 33.1% are women’ (Wholley
2019). Diversity programs in business might be ‘designed to preempt lawsuits by policing managers’
thoughts and actions’ (Dobbin, Kalev 2016) rather than actually to prompt a change in corporate
culture.
If digital technology, which is already used in many or most areas of life in First World societies, is
to be inclusive and to speak to various groups of users, the participation of a mix of diverse players in
the creation of it might become increasingly urgent. We arguably need more non-tech people coming
Introduction xix
into digital media to help us out. With mostly geeky (male) nerds developing everything, one can only
get so far –
The bugs are based on my own programming experience and observations during many years of
teaching programming courses. For concrete info on finding and fixing programming errors, see the
sections ‘The Process of Debugging’ and ‘Common Errors’ in Chapter 23.
Multiple Links are given on the book’s website that connects to learning resources outside of this
book (e.g. Processing’s own video tutorials, OpenProcessing, Arduino Projects at Instructables, math
for collision detection, an audio library, game programming patterns, and graphics resources). There are
various styles of learning and teaching; readers should pick and use the resources that they prefer and
which work best for them.
If in Doubt, Do It
This book is intended as an introduction and as an inspiring first point of contact with programming for
non-tech people11 with a specific focus on game programming. The book explains the raw basics of (any)
programming for readers who have not done a line of programming ever before, and the functions, tools
and concepts popularly used in game programming.
Programming needs to be done by oneself; yes, one can work with friends, and this can be a lot of fun, and
I welcome and recommend that later, but learning programming is like learning to ride a bicycle: One has
to do it oneself! Not watch somebody – none of one’s mates and not me. Readers should program something
they want to have now, really anything. Don’t wait; look things up, try things out, and start today!
The book shows stuff and explains it, but readers need to do it, themselves – see it run, toy around with
it, break it, fix it, feel the magic –
Notes
1. ‘There is a need for learning how to code, if we are not going to be programmed ourselves.’ (Marckmann
2019:69)
2. Warren Sack (2019) maintains that interaction had initially been an integral and even central part of com-
puter science, and was only de-emphasized when computer science developed a strong if not exclusive
focus on algorithms, promoted, for instance, by Donald Knuth.
3. If the software proves to have, e.g., commercial potential, it can then be re-implemented from scratch (e.g.
by professional programmers). Probably a fair bit of commercial software starts that way.
4. ‘I sometimes forget one of the main reasons I like programming, and that’s that programming is fun.
People can talk all they want about problem solving and helping others to accomplish tasks, but for me it’s
all about realizing that I can do it, and that’s always been a fun thing. Granted, there’s some code to write
Introduction xxi
because some user (somewhere) needs a new feature, or there’s a bug to be tracked down and squished,
but the main reason I like programming is that it’s, well, fun.’ [Paul Barry, October 24 (2011, presumably),
qtd. in blogs.oreilly.com/headfirst/2011/10/programming-is-fun-again.html (December 8, 2015)].
5. Make: magazine (www.makezine.com) and AUTODESK Instructables (www.instructables.com/Arduino-
Projects) are great starting points.
6. See the section ‘The Choice of Programming Language’ in Chapter 1.
7. This observation appears to apply, very roughly, to the US, Europe, South East Asia and Australia.
8. See, for instance, www.hackerearth.com/blog/developers/top-women-programmers-history, www.
computerscience.org/resources/most-influential-women-computer-science, mashable.com/article/unsung-
women-in-tech or www.fullstackacademy.com/blog/remarkable-women-programmers (all September 2,
2023).
9. For info on some female game designers connected to Atari, including Brenda Laurel, see the AtariWomen
project (www.atariwomen.org/stories).
10. Read more: Jason W. Bay. 17 Most influential women game developers. Blog post, www.gameindustry
careerguide.com/influential-women-game-developers (December 11, 2021).
11. For a well-written and comprehensive book on Processing from an art and design perspective see the
books by Reas and Fry (e.g. 2014); and for tech people there are many excellent computer science books
on all kinds of programming languages.
1
The Process of Programming
Outline
• What is Programming?
• The Choice of Programming Language
• Programming First Aid
What Is Programming?
By itself, the computer does nothing. To control this technical medium and to elicit some interesting
behaviour from it, humans have to give it explicit instructions. For practical purposes, instructions are
written down, in multiple programs, in languages that the computer can read. The practice to create such
programs is called programming.
Programming tries hard to be accessible. Programming languages are made for humans, not for
machines. High-level languages are specifically made to be suited to what humans want to do with
computers1. They are tools designed by people for people to use, and they have come a long way already
towards the user. Specifically, programmers do not need to learn to talk, write or think like machines, to
instruct or use computers. Modern languages do what they can to make it easy for humans to use them.
They aim to be close to how humans act and think and not to emulate or reproduce how machines func-
tion. The translation between such programming languages and the actual machine code (which is, in
fact, pretty incomprehensible) is then done automatically under the hood.
There are only a handful of programming structures; mainly these are: Loops to repeat operations,
checks to make decisions based on particular conditions and variables to store data. For people to inter-
act with programs, there is often some form of output (e.g. text, graphics, sound) and input (e.g. key-
board, mouse, joystick, sensors). Only what is formulated in its programs happens, the computer does not
suddenly start to do weird (or wonderful) things by itself. Programming is quite mundane:
• Selecting a language3
• Creating reasonably elegant code
• Reading (other people’s) code
DOI: 10.1201/9781003345916-1 1
2 Introduction to Game Programming Using Processing
To emphasise one aspect, that might be specifically similar to other design practices: Programming
means to create the tools along with the artefacts, in one seamless process. Programming is not only or
even primarily concerned with picking and using pre-made functions (except for the most trivial tasks)
but mainly with the construction of systems. Programs are developed in iterative processes which oscil-
late between creating code and using it to make artefacts. Programming is a multi-faceted process of
making and adapting and testing and fixing and re-using.
start of a new project, it is often pretty unclear what the precise requirements for the programme are and
which issues will emerge over time. Also, then, over time, many features are often added to a program,
and the structure gets overloaded, and an increasing level of effort has to be made to integrate new
features and to maintain the old ones, and to keep everything working together. Thus, at some point, it
is less trouble to re-implement a project with the experience and benefit of hindsight. Sometimes the re-
development of a program includes the port to another (for instance, more modern) language.
Particularly when starting out, even trivial programs take a considerable amount of time to be devel-
oped; and even the professional development of software often takes longer than anticipated.
Arguably, programs remain unfinished; there is always more to do, add, include or test. There is no
obvious endpoint when a game or application is done. Usually, software gets released at some point, and
then, later, more advanced incarnations of it are iteratively released as well (e.g. as bugfixes, updates or
as new program versions, occasionally over many years). For games, there are often new features and
contents released over time (such as levels or characters).
• Processing is free, platform-independent, stable, regularly updated and available for many
computer systems. It can be downloaded (from processing.org) or might be already installed;
• It can do graphics and interaction out of the box, and no setup of libraries is required;
• It can be used with Arduino boards for easy hardware access (e.g. buttons, sensors, LEDs,
motors)6;
• It has a vibrant online community, especially for beginner-oriented, introductory stuff and
• It is based on Java and very similar to widely-used and industry-relevant languages such as C#,
so skills can readily be transferred7.
FIGURE 1.1 The Processing language is used as a vehicle to learn (general) programming (pictured: Version 4.2, Linux)
4 Introduction to Game Programming Using Processing
It is to be expected that for many years, Processing will continue to play a role in learning program-
ming and as a preferred language for artists and designers.8
Many of my colleagues support the use of Processing for an introductory course and book on game
programming, but several have questioned it. Thus, some reasoning is given here. Many people who
code have their favourite programming language and occasionally are quite opinionated on the topic, and
some have kindly shared their views and recommendations about the best programming language to use
in this endeavour. There has not been a consensus, not even close. All the currently popular languages
(as well as several scripting languages and game engines) have been proposed and argued for, with the
vote roughly evenly split.
Various other languages are used in teaching (such as JavaScript, Python, C#). Processing is popu-
larly used in artistic and design projects and rarely in game design. Certainly, it is not a language used in
the game industry. Professional game development happens in C++ or C#. Python is the new hot thing
but not made for highly interactive applications (there is a game library, of course, and it does work),
and syntactically quite different from C-style languages. C and Python are also typically employed in
Computer Science programmes. Java and JavaScript are also available, possibly with decreasing popu-
larity. And there are new (e.g. browser-based) scripting languages every few years.
Also popular are versatile game engines such as Unity, Unreal and Godot, and they can only be used
to full (or any) effect with coding. Arguably, one can teach and learn programming within an engine. The
question is, is this representative of general programming, and can it be transferred to other (scripting)
tools and ‘proper’ languages? And the answer is, yes. And there is no shortage of resources (courses,
books, online videos and fora) of various qualities.
It might be a matter of preference to favour one or the other approach: Programming within engines
might have impressive initial results (e.g. engines usually have physics engines, and with very little cod-
ing anybody can make something that moves and can be shot). Programming outside of engines, on the
other side, affords more freedom and requires the programmer to take control because very little (if any)
structure is given. In my (own, rough) assessment, programming in engines is reading documentation
and finding out what one can do with elaborate pre-made engine structures and functions; while pro-
gramming outside of engines is laborious fiddling with tiny snippets of code (and reading some docu-
mentation) and trying to make meaningful things happen.
A reason to favour learning (and teaching) programming without engines is, that it is more universal:
Learning programming in an engine creates a substantial reliance (technically and psychologically) on
that engine. Take away the engine, and the learner hits a wall; he or she can do nothing. Somebody who
learned programming without an engine can (almost) start from scratch with a blank screen; and also use
an engine with very little preparation.
Probably the essential challenge of programming is to get the machine to do exciting and complex
things while instructing the machine with rather basic and clunky commands. I remember how disap-
pointed I was when I started to programme and was only given those relatively low-level and open com-
mands. I was expecting words but was given letters. Instead of using sophisticated future tech, I had to
build things up myself. For novel, original work, skills are needed, and this may apply to programming
to the same degree it applies to other areas of design. The trade-off between convenience and control
is well-known. Of course, there are programming techniques and tools that require less practice and
skill to produce desirable results than textual programming. There are many digital tools for prototyp-
ing and communicating ideas for interaction, that require very little programming knowledge. One can
use tools such as Director, game makers and website editors such as FrontPage, or subvert tools such as
PowerPoint. But of course, without programming, one is left to follow and accept what these programs
offer. Tools often focus on a specific kind of interaction (such as a genre, e.g. Adventure Game Studio9
and the online Retro Arcade Creator10 game maker), and have in-built behaviour that cannot be changed.
In other words, a platform game maker makes the same game every time. The reliance and dependence
on pre-made work not only channels, scopes and limits a tool’s expressive power but also one’s own ide-
ation and creativity. Using a text-based programming language such as Processing requires some effort
and practice to build up interesting behaviour but offers a very high level of control11.
Of course, at different points in the creative process and for different situations, different methods and
tools are useful. Programming certainly adds a tool to the box that significantly empowers designers.
The Process of Programming 5
• Take a break, do something else for a minute, talk to a human (about something else);
• Check what is going on in the program and make things visible: Use println() or text()
to output variable contents13 or graphics, to confirm the internal (e.g. collision detection) logic
corresponds to what one assumes or observes;
• Explain the code to somebody else14;
• Assume it will work eventually, comment it out for now, and come back to this issue later;
• See if anybody with coding skills is around who can help or
• Search the Internet, or more specifically, online fora15 for an answer to the question or problem.
Likely, other people have encountered it before. If nothing helpful can be found, post a question
to the forum.
Notes
1. There are certainly languages that are fairly removed from applications such as assembler, and old code
(e.g. Fortran) is and will be around for decades, but today much is done in languages that humans can
read – chances are, as a designer living in the 21st century, all code one will ever see, is fairly user-friendly
(e.g. C-based).
2. Computers are not capable of any complex operations; what they are tremendously good at, is to repeat
simple things rapidly and very often. Specifically, computers can store and retrieve data, and a lot of pre-
sumably ‘intelligent’ behaviour of the computer is actually searching and retrieving data. Google search
results and (some) poker-playing programmes are examples.
3. Section, The Choice of Programming Language is a discussion of why Processing was selected for this
project, and the most prominent features of Processing are listed.
4. The typical process of iteratively developing programmes is demonstrated in the section ‘Grids’ in Chapter 12
and in the section ‘Eye and Math Examples’ in Chapter 14.
5. Thus, if one works in a team, but also if a person works alone on a project, it is useful to avoid overly
wonky or idiosyncratic ways of coding.
6. Arduino uses (a subset of) C++ actually, but for basic applications, the differences between Processing
and C++ are marginal (class use is different, e.g.).
7. For instance, the Unity engine uses C# for scripting.
8. Theoretically, one can program anything in Processing; practically, it is a bit limited (which is not a bad
thing for learning) and for serious stuff (such as 3D graphics) too slow.
9. www.adventuregamestudio.co.uk (Jan 24, 2017)
10. www.sploder.com/free-arcade-game-maker.php (Jan 24, 2017)
11. In computer science lingo Processing is called an imperative programming language, because it states
how the computer should do things; opposed to declarative languages which state what the computer
should do.
12. For more info on debugging, see the section ‘The Process of Debugging’ in Chapter 23.
13. On console output, see Chapter 3.
14. The important part is the explaining; the other person does not need to be an expert, or even to say any-
thing at all.
15. Such as the forum on discourse.processing.org (May 21, 2023).
2
Hello Game World!
Outline
• Hello World
• First Interactivity
• Pixel Graphics
• A Brief Look at Colours
Hello World
Programming code is a piece of text, similar to a shopping list or cooking recipe. The computer reads
and executes each item (i.e. command) when (and if) it reaches it, starting at the top. The machine looks
at one spot at a time, line by line, command by command, does exactly what the code says, at best
remembers what happened before, but has no idea where things are going and what is coming next.
Often, texts on programming start with a program that prints ‘Hello World’ on the screen, so the user
can try it out and see that something is happening. Because Processing is all about graphics, this text
starts with graphical output, a line:
Start Processing on the computer and type or copy this command1 into Processing’s window.2 Then
press the Play button (showing a circle with a triangle, it looks like a play button on a cassette recorder)
or press Ctrl-R or Apple-R, and a little window with a black line on a grey background should appear:
The line is drawn between two points: (20, 70) and (80, 20). The coordinate system origin (0, 0)
is located in the top-left corner of the window.
Modify the two pairs of coordinates and the line will be drawn somewhere else.3 Add more line()
commands (with different coordinates) and several lines will be drawn.
6 DOI: 10.1201/9781003345916-2
Hello Game World! 7
With just a few commands similar to the line() command, it is possible to draw some simple graphics
on the screen; such as a large eyeball (Code 1).
Code 1
size(480, 240);
strokeWeight(4);
background(255, 255, 255);
fill(60, 120, 190);
ellipse(230, 90, 400, 400);
fill(0, 0, 0);
ellipse(229, 88, 250, 250);
fill(255, 255, 255);
ellipse(180, 40, 70, 70);
There are many things one can already draw like this; and for the moment it is fine to understand code
as a kind of list or recipe (and it is, actually, for instance, in the examples Code 1–Code 15). But, as will
become obvious soon, the code is different. Lists and recipes are usually read from top to bottom and
each line or item in-between is attended to. But code can include decisions (i.e. which code to execute
depending on e.g. user action), repetition (e.g. keep repeating part of the code a number of times), vari-
ables (to store data) and structures (such as functions and classes). While it happens that code is executed
line by line and every command once, and from top to bottom, it is a rather rare exception.
Here are more examples to try out, such as a rainbow (Code 2).
Code 2
size(480, 240);
noStroke();
background(0, 0, 0);
fill(255, 0, 0);
ellipse(240, 240, 480, 480);
fill(255, 128, 0);
ellipse(240, 240, 400, 400);
fill(255, 255, 0);
ellipse(240, 240, 320, 320);
fill(0, 255, 0);
ellipse(240, 240, 240, 240);
fill(0, 0, 255);
ellipse(240, 240, 160, 160);
fill(255, 0, 255);
ellipse(240, 240, 80, 80);
8 Introduction to Game Programming Using Processing
If one wants something more artsy-looking, that is possible, too (Code 3 and Code 4).
Code 3
size(640, 200);
noStroke();
background(235, 230, 230);
fill(245, 215, 0);
triangle(110, 20, 20, 180, 200, 180);
fill(90, 130, 210);
ellipse(310, 100, 160, 160);
fill(230, 70, 70);
rect(440, 20, 160, 160);
Code 4
size(400, 400);
noStroke();
fill(137, 67, 221);
rect(0, 0, 200, 200);
fill(178, 64, 233);
rect(200, 0, 200, 200);
fill(240, 71, 28);
rect(0, 200, 200, 200);
fill(2, 168, 88);
rect(200, 200, 200, 200);
fill(232, 175, 20);
rect(50, 50, 100, 100);
rect(250, 50, 100, 100);
rect(50, 250, 100, 100);
rect(250, 250, 100, 100);
Some things can now already be observed: There are different graphical output functions such as
line(), rect(), triangle() and ellipse(), maybe more; they are somehow controlled by num-
bers (called arguments) in parenthesis; and there are other functions such as fill(), noStroke() and
strokeWeight() that change the way the (following) objects are drawn (equivalent to picking up a
Hello Game World! 9
drawing tool such as a coloured pen). The order in which functions are called is important, that is, later
ones draw over earlier ones on the screen; colours are written in RGB values, red being, for instance,
(255, 0, 0). Things can be drawn within and without the window.
Functions
Functions carry out actions, e.g.:
• Draw shapes
• Set colours
• Calculate pixel coordinates
Functions are either language-specific (such as size() and background()), provided by libraries
(e.g. sound or network) or programmer-made. We’ll be making lots of functions here in the book4 – some
specific to a project, others that are used in many projects. Often, programmers have a bunch of functions
they have made over time, and which they re-use often.
A function has a name, which can be anything; it only needs to be unique.5 Often (i.e. by convention)
the name is spelled in lowercase letters or in a mix of (mostly) lowercase letters and some uppercase
ones, as in noStroke(). Functions can take arguments, which follow after the function name in paren-
thesis and are separated by commas. Many functions require arguments, but some do not.
Now let us revisit some of the code from the examples above. The first function that is called in
Code 1 is
size(480, 240);
size() takes two arguments to set the window size. The first argument defines the dimension of the
window in pixels in the x-direction, the second argument in the y-direction.
The function
strokeWeight(4);
takes only one argument to set the width of the contour lines of graphic objects (e.g. rectangles and
ellipses).
And the function (called in Code 2)
noStroke();
does not take any arguments; it just sets the contour line width to zero.
Functions can have any number of parameters. These parameters can also be (almost) anything, e.g.
numbers or words. For the most common functions (such as line()) one probably remembers the param-
eters, but often one simply looks them up in the documentation or uses an IDE feature similar to auto-
completion to be reminded (see the section ‘The Processing IDE’ in Chapter 23).
In Processing (as in many similar languages6), each statement (such as a function call or a variable
assignment) is ended with a semicolon (not e.g. with a line break). In the following example, the com-
puter reads two function calls, each of them terminated by a semicolon:
This would work fine, but is hard to read for humans. As a general rule, always place statements in
separate lines:
size(200, 200);
strokeWeight(3);
10 Introduction to Game Programming Using Processing
size(200, 200);
which is correct (if one wants to invoke the function for setting the window size), or
Size(200, 200);
which is not.
However, whitespace can be inserted or omitted in some places:
size(200,200);
strokeWeight ( 3 ) ;
x += 50;
These examples compile, but the code might be hard to read (and look unconventional); not everything
that is possible is advisable to do.
Whitespace is not permitted within function names and operator symbols:
stroke Weight(3);
x+ =50;
What is meant is
strokeWeight(3);
x += 50;
First Interactivity
The examples above demonstrate that the computer can do some stuff when instructed to do so, such as
drawing graphical shapes. But so far, the programs are not interactive. We will come back to the topic
soon, but already now programs can be fitted with basic interactivity. Code 5 shows how a rectangle can
be moved about the screen with the mouse.
Code 5
void setup() //runs once at program start
{ }
void draw() //runs repeatedly after that
{
rect(mouseX, mouseY, 20, 10);
}
Hello Game World! 11
The structure works like this: The code in the first function, which is called setup(), is run once on
program starts, and the second function draw() is run repeatedly after that until the program stops.7 In
Code 5, nothing is done at program start (because setup() is empty; although we might add something
like setting the window size or colouring the background), but then (in draw()) the mouse pointer coor-
dinates are used to draw a rectangle at the current position. When the mouse pointer is moved, rectangles
are drawn at various places (as in the example’s screenshot).
In Code 6, the setup() function sets the window size (once, at program start) to 320 by 240 pixels. In
draw(), first, the background is (re-) drawn all the time, so the graphical output looks much cleaner than
in Code 5; then the mouseX and mouseY variables are used to draw a line and a circle: The variables are
used as an endpoint for the line (which starts at (160, 0), which is the top-middle of the window) and as
a centre point for the ellipse (which is round, so it is a circle).
Code 6
void setup()
{
size(320, 240);
}
void draw()
{
background(220, 110, 0);
line(160, 0, mouseX, mouseY);
ellipse(mouseX, mouseY, 60, 60);
}
While most of the code snippets in this first part of the book omit the setup() and draw() structure,
do experiment with it, and with interactivity! The mouse pointer coordinates are readily available in the
variables mouseX and mouseY and can be used to control not only the position where something is drawn
but also, e.g. its size, colour or line thickness.
Pixel Graphics
Today’s popular computer screens are made up of grids of little, rectangular elements called pixels
(Figure 2.1). All the pixels on the screen or in the display window are controlled by the program.
The function call
size(100, 50);
point(x, y);
12 Introduction to Game Programming Using Processing
FIGURE 2.1 A 1987–8 Ms. Pac-Man arcade machine (branded as Super Pac Gal; left); and a screen detail showing
individual pixels on the scratched and misaligned CRT (right; photo by the author)
FIGURE 2.3 How it really looks: Close-up of a 100x100 pixel window with some graphics
Computer people tend to re-invent the world. For historical reasons,10 on computers, coordinates
always start in the upper-left corner of the window/screen (Figure 2.3). Note that everything in comput-
ers is numbered starting from 0, and thus the pixels are numbered from 0 to 99 in the x-direction, and
from 0 to 49 in the y-direction.
Code 7
size(100, 100);
point(10, 10);
point(50, 10);
point(90, 10);
point(10, 50);
point(90, 50);
point(10, 90);
point(50, 90);
point(90, 90);
Code 8
size(100, 100);
point(50, 10);
point(30, 30);
point(70, 30);
point(10, 50);
point(90, 50);
point(30, 70);
point(70, 70);
point(50, 90);
Code 9
size(100, 100);
line(20, 20, 80, 20);
line(80, 20, 80, 80);
line(80, 80, 20, 80);
line(20, 80, 20, 20);
line(20, 20, 80, 80);
line(20, 80, 80, 20);
Code 10
size(100, 100);
line(25, 25, 25, 35);
line(75, 25, 75, 35);
line(25, 75, 75, 75);
line(25, 60, 25, 75);
line(75, 60, 75, 75);
Code 11
size(100, 100);
line(10, 50, 30, -10);
line(30, -10, 90, 10);
line(90, 10, 70, 70);
line(70, 70, 10, 50);
Code 12
size(100, 100);
ellipse(50, 50, 100, 100);
line(-100, 50, 200, 50);
rect(-10, -10, 120, 120);
point(-20, 50);
point(100, 100);
14 Introduction to Game Programming Using Processing
Code 13
size(100, 100);
line(10, 10, 90, 90);
line(10, 10, 10, 90);
line(10, 90, 90, 90);
point(50, 50);
point(10, 90);
ellipse(90, 10, 0, 0);
Here are the parameters of the graphical functions that were used in the above examples, plus two
others: The quad and the Bézier curve.12
The ellipse, for instance, mixes as parameters: Coordinates and the size of it in pixels; it could even
include a colour or a name – anything can be given as a parameter, there is no law against that (of course,
one would need to write one’s own function for that to work).13
Bézier curves are much used in drawing programs such as Illustrator and Corel Draw (Figure 2.4).
Bézier curves are defined by anchor points and control points. Each anchor point has one (if it is an start/
end point) or two control points associated with it. The curve goes through (or starts/ends at) the anchor
points and curves towards the control points.
Hello Game World! 15
FIGURE 2.4 Bézier curve with control points in a typical (vector-based) drawing program
Processing’s function draws a curve between two anchor points. It takes eight parameters:
bezier(x1, y1, control x1, control y1, control x2, control y2, x2, y2);
The two anchor points are given first and last, with two control points in-between (Code 14–Code 15).
Code 14
bezier(40, 20, 20, 45, 20, 80, 70, 60);
stroke(160, 160, 160);
line(40, 20, 20, 45);
line(70, 60, 20, 80);
Code 15
bezier(80, 20, 20, 25, 80, 90, 20, 80);
stroke(160, 160, 160);
line(80, 20, 20, 25);
line(20, 80, 80, 90);
16 Introduction to Game Programming Using Processing
Use a (vector) drawing program to get a feel for Bézier curves – many popular, commercial programs
use the same thing as Processing; also, try this interactive example (Code 16):
Code 16
void setup()
{
size(200, 200);
}
void draw()
{
background(12, 244, 22);
bezier(40, 20, mouseX, mouseY, 10, 110, 160, 140);
line(40, 20, mouseX, mouseY);
}
Drawing Order
Computers execute one command after the other, and this also applies to graphical output. As is visible
in some of the examples above (for instance, in Code 1), on pixel displays, a shape that is drawn later
occludes shapes drawn earlier. This is often very useful (e.g. it makes drawing a rainbow quite simple
using circles, Code 2), but it can also be problematic (for instance, the last flower petal to be drawn
occludes the first, so they do not look all the same (Figure 2.3).
When a graphical object is not visible, and one expects it to be, it may be because it is drawn outside
the display window, it is obscured by another object or is too small (or big) or is drawn in an unexpected
colour (for instance, it might have the same colour as the background or might be transparent).
Try it out:
Code 17
ellipse(50, 50, 40, 50);
rect(25, 55, 50, 25);
Code 18
ellipse(25, 50, 10, 10);
ellipse(75, 50, 10, 10);
rect(25, 40, 50, 20);
RGB is but one way to represent colour. It is not the only way, and also not the way to achieve the ideal
alignment with the colours humans can see. But it is technically convenient and became the default model
in screen-based computer graphics (as opposed to print). Processing uses by default the RGB model to
define colours (alternatively, it can be switched to the HSB model14). A colour is given as a triplet of whole
numbers, with each number going from 0 to 255; for example, maximum red is (255, 0, 0) – the red
component of RGB is set to 255, green to 0, and blue to 0. For some other popular colours, see Figure 2.5.15
In the RGB colour model, black is (0, 0, 0), white is (255, 255, 255) and middle grey is (128, 128,
128). Processing offers a shortcut for grey values, and that is, to only use one value to describe a shade
of grey (Code 19).
Code 19
noStroke();
fill(0);
rect(0, 0, 100, 20);
fill(64);
rect(20, 20, 80, 20);
fill(128);
rect(40, 40, 60, 20);
fill(192);
rect(60, 60, 40, 20);
fill(255);
rect(80, 80, 20, 20);
The stroke() function sets the colour for the contour lines, and the fill() function for the fill of the
following shapes. The settings remain valid until a new setting occurs. The default values are white fill
and black lines (Code 20).
Exploring the Variety of Random
Documents with Different Content
CHAPTER IX.
THEIR AMUSEMENTS AND ACCOMPLISHMENTS.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookfinal.com