Showing posts with label Games. Show all posts

Sloan Kelly


e-books shop
e-books shop
Purchase Now !
Just with Paypal



Book Details
 Price
 4.00
 Pages
 395 p
 File Size 
 5,991 KB
 File Type
 PDF format
 ISBN-13
 978-1-4842-4532-3 (pbk)
 978-1-4842-4533-0(electronic) 
 Copyright©   
 2019 by Sloan Kelly

About the Author
Sloan Kelly has worked in the games industry
for nearly 12 years. He has worked on a
number of AAA and indie titles and currently
works for an educational game company. He
lives in Ontario, Canada, with his wife and
children. Sloan is on Twitter @codehoose and
makes YouTube videos in his spare time.

About the Technical Reviewer
John Watson is a game developer, artist, guitar
player, husband, and father. Among John’s
many software-powered side projects, he’s
building a Raspberry Pi–powered device that
generates interactive music in live modern
dance performances. He’s also developing a
retro-inspired 2D twin-stick arcade shooter
called Gravity Ace. You can follow his progress
on Twitter @yafd or at gravityace.com. Stop by
and say hi!

Introduction
This book is intended for anyone who wants to learn how to program
games. It is ideally suited to students who want to learn Python and
PyGame on their Raspberry Pi. While not necessary, this book has been
oriented toward the Raspberry Pi computer.
The Python programming language is ideally suited to beginners and
experts alike. The skills you will learn in this book are easily transferable to
other computer languages too.
If you are unfamiliar with the Raspberry Pi, there are several good
eBook guides on getting started including mine called A Slice of Raspberry
Pi, available from all good eBook retailers.
This book assumes that you are familiar with the Raspberry Pi
computer and that you have the Raspberry Pi Foundation’s recommended
Raspbian operating system installed. Raspbian is a distribution of the
Debian Linux operating system built specifically for the Raspberry Pi. This
distribution contains all the Software Development Kits (SDKs) including
one for Python that includes PyGame. If you don’t have Raspbian installed,
you will have to ensure that you have Python and PyGame installed on
your system.
Don’t have a Raspberry Pi? Not to worry, you can still learn Python and
PyGame. The code in this book will work on other OSs with Python and
PyGame installed; Python is a platform-independent language.
You can obtain more information and download versions of Python from
www.python.org. PyGame can be obtained from www.pygame.org/.
Sprites from Ari Feldman’s SpriteLib have been used for the projects
contained in this book.


Table of Contents
About the Author ..............................................................................xvii
About the Technical Reviewer ...........................................................xix
Acknowledgments .............................................................................xxi
Introduction .....................................................................................xxiii
Chapter 1: What Is a Programming Language? ....................................1
What Does a Computer Program Do? ...................................................................2
Conclusion ............................................................................................................3
Chapter 2: What Is Python? ..................................................................5
Programming Styles ..............................................................................................5
Object-Oriented .....................................................................................................7
Functional .............................................................................................................8
What Is Pygame? ..................................................................................................8
Conclusion ............................................................................................................9
Chapter 3: Introducing Python ............................................................11
The Terminal Window ..........................................................................................11
Running the Python Interpreter ...........................................................................12
Python Is Interpreted ...........................................................................................13
Python As a Calculator ........................................................................................13
Keywords ............................................................................................................16
Printing ...............................................................................................................17
String Formatting ..........................................................................................19
Variables .............................................................................................................22
Naming Variables ...........................................................................................22
Python As a Calculator, Part II .............................................................................23
Arithmetic Operators .....................................................................................26
Data Types .....................................................................................................27
Numeric Types ...............................................................................................27
String Formatting Again ................................................................................29
Conclusion ..........................................................................................................31
Chapter 4: Breaking Free from the Interpreter ...................................33
What Is IDLE? ......................................................................................................33
Starting IDLE .......................................................................................................33
Starting a New File .............................................................................................34
Hello, World! ........................................................................................................36
Running from the Command Line ..................................................................36
Running from Inside IDLE ..............................................................................38
Conclusion ..........................................................................................................39
Chapter 5: Making Decisions ..............................................................41
A Note About Blocks ............................................................................................44
Testing for Equality .............................................................................................45
Using Boolean Logic ............................................................................................50
And ................................................................................................................50
Or ...................................................................................................................51
Not .................................................................................................................52
Nesting Ifs ...........................................................................................................52
A Note on Switch ................................................................................................54
Conclusion ..........................................................................................................54
Chapter 6: Making the Raspberry Pi Repeat Itself .............................55
The for Loop ........................................................................................................55
The range() Function .....................................................................................57
While Loops .........................................................................................................58
Counting ........................................................................................................58
Sentinel .........................................................................................................60
Conditional .....................................................................................................62
Conclusion ..........................................................................................................62
Chapter 7: Containers .........................................................................63
Container Nomenclature .....................................................................................63
Tuples ..................................................................................................................64
Removing Elements from a Tuple ..................................................................64
Changing Element Values ..............................................................................65
Tuples in Printing ...........................................................................................66
Deconstructing Tuples ...................................................................................67
Lists ....................................................................................................................67
List Creation ..................................................................................................68
Adding Values to the List ...............................................................................68
Removing Values from a List .........................................................................69
Doctor’s Waiting Room Program ....................................................................70
Dictionaries .........................................................................................................73
Iterating Through Dictionaries .......................................................................74
Adding New Items to Dictionaries .................................................................74
Removing Entries from a Dictionary ..............................................................74
Conclusion ..........................................................................................................75
Chapter 8: Putting It Together: Tic-Tac-Toe ........................................77
The Rules ............................................................................................................77
Program Layout ...................................................................................................79
Variables .............................................................................................................79
The Game ............................................................................................................80
Save and Run ......................................................................................................85
Conclusion ..........................................................................................................85
Chapter 9: Basic Introduction to PyGame ...........................................87
Importing the PyGame Framework .....................................................................87
Initializing PyGame ..............................................................................................88
The Main Loop ....................................................................................................89
Images and Surfaces ..........................................................................................92
Creating Images ..................................................................................................93
Loading Images ...................................................................................................93
Drawing Images ..................................................................................................94
Screen Coordinates and Resolution ....................................................................94
Sprite Sheets ......................................................................................................95
Full Listing ..........................................................................................................97
Conclusion ..........................................................................................................97
Chapter 10: Designing Your Game ......................................................99
Initial Concept .....................................................................................................99
Prototyping ..................................................................................................100
Functional Specification ...................................................................................101
Weapon Firing .............................................................................................101
Program Design ................................................................................................101
Coding ...............................................................................................................102
Testing ..............................................................................................................104
Iteration .............................................................................................................105
Conclusion ........................................................................................................105
Chapter 11: Game Project: Bricks ....................................................107
The Main Framework ........................................................................................108
Images ..............................................................................................................109
Moving the Bat ..................................................................................................110
Bat Initialization ...........................................................................................111
Drawing the Bat ...........................................................................................112
Moving the Bat ............................................................................................112
Moving the Ball .................................................................................................114
Ball Initialization ..........................................................................................114
Ball Movement .............................................................................................115
Bat and Ball Collision ...................................................................................118
Serving the Ball ...........................................................................................120
Brick Wall ..........................................................................................................121
Brick and Ball Collision ................................................................................122
Out of Bounds ..............................................................................................124
Conclusion ........................................................................................................125
Chapter 12: User-Defined Functions .................................................127
What Is a Function? ..........................................................................................127
Format of a Function .........................................................................................127
Functions as a Menial Task/Mnemonic Device .................................................128
Sending Parameters .........................................................................................129
Default Argument Values ...................................................................................131
Named Parameters ......................................................................................132
Returning Values ...............................................................................................133
Returning Tuples ..........................................................................................134
Accessing Global Variables ...............................................................................135
Real-World Example of a Function ....................................................................136
Conclusion ........................................................................................................139
Chapter 13: File Input and Output .....................................................141
Reading a File from Disk ...................................................................................141
Writing Data to a File ........................................................................................143
Reading and Writing Containers to a File ..........................................................144
Writing Your Own Serializer .........................................................................145
Writing Your Own Deserializer .....................................................................147
JSON .................................................................................................................148
JSON Serialization .......................................................................................148
JSON Deserializer ........................................................................................149
Handling Errors .................................................................................................150
Conclusion ........................................................................................................151
Chapter 14: Introducing Object-Oriented Programming ...................153
Classes and Objects ..........................................................................................154
Encapsulation ...................................................................................................154
Abstraction ........................................................................................................155
Inheritance ........................................................................................................155
Polymorphism ...................................................................................................155
Why Should You Use OOP? ................................................................................156
Data Hiding ..................................................................................................156
Reusable ......................................................................................................156
Easier to Code and Test Separately .............................................................156
The Ball Class ...................................................................................................157
Creating an Instance of the Class .....................................................................160
The Ball update( ) Method ............................................................................161
Constructors ................................................................................................162
SOLID ................................................................................................................164
Single Responsibility ...................................................................................165
Open-Closed Principle .................................................................................165
Liskov Substitution ......................................................................................166
Interface Segregation ..................................................................................166
Dependency Inversion .................................................................................167
Conclusion ........................................................................................................170
Chapter 15: Inheritance, Composition, and Aggregation ..................171
Inheritance ........................................................................................................172
Base and Child Classes .....................................................................................173
Programming to the Interface .....................................................................175
A Note About Constructors and Base Classes .............................................175
Composition ......................................................................................................177
Aggregation .......................................................................................................179
Conclusion ........................................................................................................180
Chapter 16: Game Project: Snake .....................................................181
Functions ..........................................................................................................182
Snake Framework .............................................................................................183
Images ..............................................................................................................190
Loading the Images .....................................................................................191
The Game Map ..................................................................................................192
Drawing the ‘Game Over’ Screen ......................................................................193
Drawing the Game ............................................................................................195
Drawing the Walls .............................................................................................196
Drawing the Player Data ...................................................................................198
Drawing the Snake ............................................................................................199
Updating the Game ...........................................................................................202
The updateGame( ) Method ..........................................................................203
Snake Movement .........................................................................................205
Touching a Berry ..........................................................................................206
Collision Detection ............................................................................................208
Helper Functions .........................................................................................208
Conclusion ........................................................................................................212
Chapter 17: Model View Controller ...................................................213
Model ................................................................................................................214
View ..................................................................................................................214
Controller ..........................................................................................................214
Why Use MVC? ..................................................................................................215
The Classes .................................................................................................216
Folder ..........................................................................................................217
The Robot Model .........................................................................................217
The Robot View ............................................................................................219
The Radar View ............................................................................................221
The Robot Controller ....................................................................................222
The Robot Generator ....................................................................................225
Ensuring Constant Speed ..................................................................................227
The Main Robot Program ..................................................................................228
Conclusion ........................................................................................................230
Chapter 18: Audio .............................................................................233
Playing a Sound ................................................................................................234
Playing, Pausing, and Changing Volume ...........................................................235
Conclusion ........................................................................................................240
Chapter 19: Finite State Machines ...................................................241
Game State .......................................................................................................241
Menu System ....................................................................................................241
Non-player Artificial Intelligence .......................................................................242
A Finite State Machine Example .......................................................................243
Finite State Machine Manager ....................................................................244
Conclusion ........................................................................................................249
Chapter 20: Game Project: Invaders .................................................251
The Classes .......................................................................................................253
The Finite State Machine ..................................................................................254
MVC and ‘Invaders’ ...........................................................................................255
The Framework .................................................................................................255
Bitmap Font .................................................................................................259
Interstitial Screens ......................................................................................263
The Main Menu ............................................................................................264
Player and Bullets .............................................................................................267
The Bullet Classes .......................................................................................267
The Player Classes ......................................................................................270
Testing Player ..............................................................................................273
The Alien Swarm Classes ..................................................................................275
Collision Detection ............................................................................................282
Explosions ...................................................................................................282
Collision Controller ......................................................................................285
The Main Program .............................................................................................288
The Main Game State ........................................................................................289
Running the Game ............................................................................................292
Conclusion ........................................................................................................293
Chapter 21: Simple Electronics with the GPIO Pins ..........................295
Voltage, Current, and Resistance ......................................................................296
What You Will Need ...........................................................................................298
Breadboard ..................................................................................................298
Breakout Board ............................................................................................299
Jumper Wires ..............................................................................................300
LEDs ............................................................................................................302
Resistors ......................................................................................................304
Switches ......................................................................................................307
Building a Circuit ...............................................................................................308
Connecting the Breakout Board to the Raspberry Pi ...................................308
Providing Power and Ground .......................................................................311
Adding the LED ............................................................................................312
Completing the Circuit .................................................................................313
Testing the Circuit ........................................................................................315
Pin Meanings ....................................................................................................316
The gpiozero Library .........................................................................................317
The Circuit ...................................................................................................318
The Python Program ....................................................................................319
Getting Button Input ....................................................................................320
Reading Button Input in Python ...................................................................321
Conclusion ........................................................................................................322
Chapter 22: Game Project: Memory ..................................................323
Arranging the Breadboard .................................................................................324
Placing the LEDs ..........................................................................................324
Testing the Circuit .............................................................................................326
Placing the Tact Switches ............................................................................327
Testing the Button Circuit ............................................................................328
The Memory Game ............................................................................................330
The ButtonLED and ButtonLEDCollection Classes .......................................331
The Main Program .......................................................................................334
Full Listing buttonled.py ....................................................................................336
Full Listing memorygame.py .............................................................................338
Conclusion ........................................................................................................339
Chapter 23: Game Project: Quiz ........................................................341
The Electronics .................................................................................................341
Testing the Buttons ......................................................................................342
The Finite State Machine ..................................................................................345
Making the Game ..............................................................................................347
The Questions ..............................................................................................348
UI Helper Classes .........................................................................................354
The Game Runner and Base State Class .....................................................359
Player Input .................................................................................................361
The State Classes ........................................................................................362
Playing the Game ..............................................................................................376
Conclusion ........................................................................................................377
Chapter 24: Conclusion .....................................................................379
Index .................................................................................................381


Bookscreen
e-books shop

Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Spandana Chatterjee
Development Editor: James Markham
Coordinating Editor: Divya Modi
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)

- Code a Space Adventure Game! -

BY SEAN MCMANUS

BRIEF CONTENTS

Chapter 1: Your First Spacewalk
Chapter 2: Lists Can Save Your Life
Chapter 3: Repeat After Me
Chapter 4: Creating the Space Station
Chapter 5: Preparing the Space Station Equipment
Chapter 6: Installing the Space Station Equipment
Chapter 7: Moving into the Space Station
Chapter 8: Repairing the Space Station
Chapter 9: Unpacking Your Personal Items
Chapter 10: Make Yourself Useful
Chapter 11: Activating Safety Doors
Chapter 12: Danger! Danger! Adding Hazards
Appendix A: Escape: The Complete Game Listing
Appendix B: Table of Variables, Lists, and Dictionaries
Appendix C: Debugging Your Listings

e-books shop
e-books shop
Purchase Now !
Just with Paypal



Book Details
 Price
 3.00
 Pages
 345 p
 File Size 
 7,856 KB
 File Type
 PDF format
 ISBN-10
 ISBN-13
 1-59327-857-8
 978-1-59327-857-1
 Copyright©   
 2018 by Sean McManus  

ABOUT THE AUTHOR
Sean McManus is an expert technology and business writer. His other books
include Cool Scratch Projects in Easy Steps, Scratch Programming in Easy Steps,
Coder Academy, and Raspberry Pi For Dummies (co-authored with Mike Cook).
As a freelance copywriter, he writes for many of the world’s largest
technology companies. His novel for adults, Earworm, goes undercover in
the music industry, exposing a conspiracy to replace bands with computergenerated
music. He has been a Code Club volunteer, helping children at a
local school to learn computer programming. Visit his website at
www.sean.co.uk for sample chapters and bonus content from his books.

ABOUT THE TECHNICAL REVIEWER
Daniel Aldred is a passionate and experienced teacher of computer science.
He leads the computing department at a CAS hub school that supports and
develops other schools and organizations in the local area. He frequently
writes for Linux User & Developer and has created resources and projects for
Raspberry Pi, Pimoroni, micro:bit, and Cambridge International
Assessment. In his spare time he curates two websites,
www.canyoucompute.co.uk for the UK Computing examination course and
www.tecoed.co.uk for his own personal hacks. Daniel also led and managed a
team of eight students to win the first Astro Pi competition, where the
astronaut Major Tim Peake ran their program aboard the ISS.

INTRODUCTION
Air is running out. There’s a leak in the space station, so you’ve got to act
fast. Can you find your way to safety? You’ll need to navigate your way
around the space station, find access cards to unlock doors, and fix your
damaged space suit. The adventure has begun!
And it starts here: on Earth, at mission command, also known as your
computer. This book shows you how to use Python to build a space station
on Mars, explore the station, and escape danger in an adventure game
complete with graphics. Can you think like an astronaut to make it to safety?

Table of Contents
ACKNOWLEDGMENTS
INTRODUCTION
How to Use This Book
What’s in This Book?
Installing the Software
Installing the Software on Raspberry Pi
Installing Python on Windows
Installing Pygame Zero on Windows
Installing the Software on Other Machines
Downloading the Game Files
Downloading and Unzipping the Files on a Raspberry Pi
Unzipping the File on a Windows PC
What’s in the ZIP File
Running the Game
Running Pygame Zero Programs on the Raspberry Pi
Running Pygame Zero Programs in Windows
Playing the Game
1
YOUR FIRST SPACEWALK
Starting the Python Editor
Starting IDLE in Windows 10
Starting IDLE in Windows 8
Starting IDLE on the Raspberry Pi
Introducing the Python Shell
Displaying Text
Training Mission #1
Outputting and Using Numbers
Introducing Script Mode
Creating the Starfield
Understanding the Program So Far
Stopping Your Pygame Zero Program
Adding the Planet and Spaceship
Changing Perspective: Flying Behind the Planet
Training Mission #2
Spacewalking!
Training Mission #3
Understanding the Spacewalk Listing
Training Mission #4
Are You Fit to Fly?
Mission Debrief
2
LISTS CAN SAVE YOUR LIFE
Making Your First List: The Take-Off Checklist
Seeing Your List
Adding and Removing Items
Using Index Numbers
Inserting an Item
Accessing an Individual Item
Replacing an Item
Deleting an Item
Training Mission #1
Creating the Spacewalk Checklist
Training Mission #2
A List of Lists: The Flight Manual
Making a List of Lists
Training Mission #3
Finding an Item in the Flight Manual
Combining Lists
Making Maps from Lists: The Emergency Room
Making the Map
Finding an Emergency Item
Training Mission #4
Swapping Items in the Room
Training Mission #5
Are You Fit to Fly?
Mission Debrief
3
REPEAT AFTER ME
Displaying Maps with Loops
Making the Room Map
Displaying the Map with a Loop
Training Mission #1
Loop the Loop
Nesting Loops to Get Room Coordinates
Cleaning Up the Map
Training Mission #2
Displaying a 3D Room Image
Understanding How the Room Is Drawn
Working Out Where to Draw Each Item
Training Mission #3
Are You Fit to Fly?
Mission Debrief
4
CREATING THE SPACE STATION
Automating the Map Making Process
How the Automatic Map Maker Works
Creating the Map Data
Writing the GAME_MAP Code
Testing and Debugging the Code
Generating Rooms from the Data
How the Room Generating Code Works
Creating the Basic Room Shape
Adding Exits
Testing the Program
Training Mission #1
Exploring the Space Station in 3D
Training Mission #2
Making Your Own Maps
Are You Fit to Fly?
Mission Debrief
5
PREPARING THE SPACE STATION EQUIPMENT
Creating a Simple Planets Dictionary
Understanding the Difference Between a List and a Dictionary
Making an Astronomy Cheat Sheet Dictionary
Error-Proofing the Dictionary
Training Mission #1
Putting Lists Inside Dictionaries
Extracting Information from a List Inside a Dictionary
Training Mission #2
Making the Space Station Objects Dictionary
Adding the First Objects in Escape
Viewing Objects with the Space Station Explorer
Designing a Room
Training Mission #3
Adding the Rest of the Objects
Training Mission #4
Are You Fit to Fly?
Mission Debrief
INSTALLING THE SPACE STATION EQUIPMENT
Understanding the Dictionary for the Scenery Data
Adding the Scenery Data
Adding the Perimeter Fence for the Planet Surface
Loading the Scenery into Each Room
Updating the Explorer to Tour the Space Station
Training Mission #1
Are You Fit to Fly?
Mission Debrief
7
MOVING INTO THE SPACE STATION
Arriving on the Space Station
Disabling the Room Navigation Controls in the EXPLORER
Section
Adding New Variables
Teleporting onto the Space Station
Adding the Movement Code
Understanding the Movement Code
Training Mission #1
Moving Between Rooms
Are You Fit to Fly?
Mission Debrief
8
REPAIRING THE SPACE STATION
Sending Information to a Function
Creating a Function that Receives Information
How It Works
Training Mission #1
Adding Variables for Shadows, Wall Transparency, and Colors
Deleting the EXPLORER Section
Adding the DISPLAY Section
Adding the Functions for Drawing Objects
Drawing the Room
Understanding the New draw() Function
Positioning the Room on Your Screen
Making the Front Wall Fade In and Out
Displaying Hints, Tips, and Warnings
Showing the Room Name When You Enter the Room
Are You Fit to Fly?
Mission Debrief
9
UNPACKING YOUR PERSONAL ITEMS
Adding the Props Information
Adding Props to the Room Map
Finding an Object Number from the Room Map
Picking Up Objects
Picking Up Props
Adding the Keyboard Controls
Adding the Inventory Functionality
Displaying the Inventory
Adding the Tab Keyboard Control
Testing the Inventory
Dropping Objects
Training Mission #1
Examining Objects
Training Mission #2
Are You Fit to Fly?
Mission Debrief
10
MAKE YOURSELF USEFUL
Adding the Keyboard Control for Using Objects
Adding Standard Messages for Using Objects
Adding the Game Progress Variables
Adding the Actions for Specific Objects
Combining Objects
Training Mission #1
Adding the Game Completion Sequence
Exploring the Objects
Are You Fit to Fly?
11
ACTIVATING SAFETY DOORS
Planning Where to Put Safety Doors
Positioning the Doors
Adding Access Controls
Making the Doors Open and Close
Adding the Door Animation
Training Mission #1
Shutting the Timed Door
Adding a Teleporter
Training Mission #2
Activating the Airlock Security Door
Removing Exits for Your Own Game Designs
Mission Accomplished?
Are You Fit to Fly?
12
DANGER! DANGER! ADDING HAZARDS
Adding the Air Countdown
Displaying the Air and Energy Bars
Adding the Air Countdown Functions
Starting the Air Countdown and Sounding the Alarm
Training Mission #1
Adding the Moving Hazards
Adding the Hazard Data
Sapping the Player’s Energy
Starting and Stopping Hazards
Setting Up the Hazard Map
Making the Hazards Move
Displaying Hazards in the Room
Training Mission #2
Stopping the Player from Walking Through Hazards
Adding the Toxic Spills
Making the Finishing Touches
Disabling the Teleporter
Cleaning Up the Data
Your Adventure Begins
Your Next Mission: Customizing the Game
Are You Fit to Fly?
Mission Debrief
A ESCAPE: THE COMPLETE GAME LISTING
B TABLE OF VARIABLES, LISTS, AND DICTIONARIES
C DEBUGGING YOUR LISTINGS
Indentation
Case Sensitivity
Parentheses and Brackets
Colons
Commas
Images and Sounds
Spelling
INDEX


Bookscreen
e-books shop

HOW TO USE THIS BOOK
By following the instructions in this book, you can build a game called Escape
with a map to explore and puzzles to solve. It’s written in Python, a popular
programming language that is easy to read. It also uses Pygame Zero, which
adds some instructions for managing images and sounds, among other
things. Bit by bit, I’ll show you how to make the game and how the main
parts of the code work, so you can customize it or build your own games
based on my game code. You can also download all the code you need. If you
get stuck or just want to jump straight into playing the game and seeing it
work, you can do so. All the software you need is free, and I’ve provided
instructions for Windows PCs and the Raspberry Pi. I recommend you use
the Raspberry Pi 3 or Raspberry Pi 2. The game may run too slowly to enjoy
on the Pi Zero, original Model B+, and older models.

There are several different ways you can use the book and the game:
Download the game, play it first, and then use the book to
understand how it works. This way, you eliminate the risk of seeing
any spoilers in the book before you play the game! Although I’ve kept
them to a minimum, you might notice a few clues in the code as you
read the book. If you get really stuck on a problem in the game, you can
try reading the code to work out the solution. In any case, I recommend
you run the game at least once to see what you’ll be building and learn
how to run your programs.
Build the game, and then play it. This book guides you through
creating the game from start to finish. As you work your way through
the chapters, you’ll add new sections to the game and see how they
work. If you can’t get the code working at any point, you can just use
my version of the code listing and continue building from there. If you
choose this route, avoid making any custom changes to the game until
you’ve built it, played it, and finished it. Otherwise, you might
accidentally make the game impossible to complete. (It’s okay to make
any changes I suggest in the exercises.)
Customize the game. When you understand how the program works,
you can change it by using your own maps, graphics, objects, and
puzzles. The Escape game is set on a space station, but yours could be in
the jungle, under the sea, or almost anywhere. You could use the book
to build your own version of Escape first, or use my version of the final
game and customize that. I’d love to see what you make using the
program as a starting point! You can find me on Twitter at
@musicandwords or visit my website at www.sean.co.uk.

by Al Sweigart

Brief Contents

The Interactive Shell
Writing Programs
Guess the Number
A Joke-Telling Program 
Dragon Realm
Using the Debugger 
Designing Hangman with Flowcharts
Writing the Hangman Code
Extending Hangman
Tic-Tac-Toe
The Bagels Deduction Game 
The Cartesian Coordinate System
Sonar Treasure Hunt
Caesar Cipher 
The Reversegam Game
Reversegam AI Simulation
Creating Graphics
Animating Graphics
Collision Detection
Using Sounds and Images
A Dodger Game with Sounds and Images

e-books shop
e-books shop
Purchase Now !
Just with Paypal



Book Details
 Price
 3.00 USD
 Pages
 374 p
 File Size
 8,623 KB
 File Type
 PDF format
 ISBN-10
 ISBN-13
 1-59327-795-4
 978-1-59327-795-6 
 Copyright   
 2017 by Al Sweigart 

About the Author
Al Sweigart is a software developer, tech book author, and hoopy frood
who really knows where his towel is. He has written several programming
books for beginners, including Automate the Boring Stuff with Python and
Scratch Programming Playground, also from No Starch Press. 
His books are freely available under a Creative Commons license at his website https://inventwithpython.com/.

About the Technical Reviewer
Ari Lacenski is a developer of Android applications and Python software.
She lives in the Bay Area, where she writes about Android programming at
http://gradlewhy.ghost.io/ and mentors with Women Who Code.

Introduction
When I first played video games as a kid,
I was hooked. But I didn’t just want to
play video games, I wanted to make them.
I found a book like this one that taught me
how to write my first programs and games. It was fun
and easy. The first games I made were like the ones
in this book. They weren’t as fancy as the Nintendo
games my parents bought for me, but they were games
I had made myself.
Now, as an adult, I still have fun programming and I get paid for it. But
even if you don’t want to become a computer programmer, programming
is a useful and fun skill to have. It trains your brain to think logically, make
plans, and reconsider your ideas whenever you find mistakes in your code.

Many programming books for beginners fall into two categories. The
first category includes books that don’t teach programming so much as
“game creation software” or languages that simplify so much that what is
taught is no longer programming. The other category consists of books
that teach programming like a mathematics textbook—all principles and
concepts, with few real-life applications for the reader. This book takes
a different approach and teaches you how to program by making video
games. I show the source code for the games right up front and explain
programming principles from the examples. This approach was the key
for me when I was learning to program. The more I learned how other
people’s programs worked, the more ideas I had for my own programs.
All you’ll need is a computer, some free software called the Python
interpreter, and this book. Once you learn how to create the games in this
book, you’ll be able to develop games on your own.

Computers are incredible machines, and learning to program them
isn’t as hard as people think. A computer program is a bunch of instructions
that the computer can understand, just like a storybook is a bunch of sentences
that the reader can understand. To instruct a computer, you write a
program in a language the computer understands. This book will teach you
a programming language called Python. There are many other programming
languages you can learn, like BASIC, Java, JavaScript, PHP, and C++.
When I was a kid, I learned BASIC, but newer programming languages
like Python are even easier to learn. Python is also used by professional programmers
in their work and when programming for fun. Plus it’s totally free
to install and use—you’ll just need an internet connection to download it.

Because video games are nothing but computer programs, they are
also made up of instructions. The games you’ll create from this book seem
simple compared to the games for Xbox, PlayStation, or Nintendo. These
games don’t have fancy graphics because they’re meant to teach you coding
basics. They’re purposely simple so you can focus on learning to program.
Games don’t have to be complicated to be fun!

Table of Contents
Acknowledgments xix
Introduction xxi
Who Is This Book For? xxii
About This Book xxiii
How to Use This Book xxiv
Line Numbers and Indentation . xxiv
Long Code Lines xxv
Downloading and Installing Python . xxv
Starting IDLE . xxvi
Finding Help Online xxvii
1 The Interactive Shell 1
Some Simple Math 2
Integers and Floating-Point Numbers . 2
Expressions . 3
Evaluating Expressions . 3
Syntax Errors 4
Storing Values in Variables 5
Summary . 8
2 Writing Programs 11
String Values 12
String Concatenation . 13
Writing Programs in IDLE’s File Editor 13
Creating the Hello World Program . 14
Saving Your Program 15
Running Your Program 16
How the Hello World Program Works . 17
Comments for the Programmer . 17
Functions: Mini-Programs Inside Programs . 18
The End of the Program   19
Naming Variables . 20
Summary . 20
3 Guess the Number 21
Sample Run of Guess the Number . 22
Source Code for Guess the Number 22
Importing the random Module  23
Generating Random Numbers with the random.randint() Function . 24
Welcoming the Player . 26
Flow Control Statements . 26
Using Loops to Repeat Code 26
Grouping with Blocks . 27
Looping with for Statements . 28
Getting the Player’s Guess 29
Converting Values with the int(), float(), and str() Functions . 29
The Boolean Data Type 31
Comparison Operators . 32
Checking for True or False with Conditions 32
Experimenting with Booleans, Comparison Operators, and Conditions . 33
The Difference Between = and == 34
if Statements . 34
Leaving Loops Early with the break Statement . 35
Checking Whether the Player Won . 35
Checking Whether the Player Lost . 35
Summary . 36
4 A Joke-Telling Program 39
Sample Run of Jokes 40
Source Code for Jokes . 40
How the Code Works 41
Escape Characters 41
Single and Double Quotes . 42
The print() Function’s end Keyword Parameter . 43
Summary . 44
5 Dragon Realm 45
How to Play Dragon Realm 45
Sample Run of Dragon Realm . 46
Flowchart for Dragon Realm . 46
Source Code for Dragon Realm 47
Importing the random and time Modules 48
Functions in Dragon Realm . 49
def Statements . 49
Calling a Function 49
Where to Put Function Definitions . 50
Multiline Strings 50
How to Loop with while Statements . 51
Boolean Operators 52
The and Operator 52
The or Operator . 53
The not Operator . 53
Evaluating Boolean Operators . 54
Return Values 55
Global Scope and Local Scope . 56
Function Parameters 57
Displaying the Game Results  58
Deciding Which Cave Has the Friendly Dragon 59
The Game Loop 60
Calling the Functions in the Program . 60
Asking the Player to Play Again . 61
Summary . 61
6 Using the Debugger 63
Types of Bugs . 64
The Debugger . 65
Starting the Debugger . 65
Stepping Through the Program with the Debugger 67
Finding the Bug  70
Setting Breakpoints 73
Using Breakpoints . 73
Summary . 75
7 Designing Hangman with Flowcharts 77
How to Play Hangman . 78
Sample Run of Hangman . 78
ASCII Art . 79
Designing a Program with a Flowchart 80
Creating the Flowchart 81
Branching from a Flowchart Box 81
Ending or Restarting the Game 83
Guessing Again . 83
Offering Feedback to the Player . 85
Summary . 86
8 Writing the Hangman Code 87
Source Code for Hangman  88
Importing the random Module   91
Constant Variables 91
The Lists Data Type 92
Accessing Items with Indexes . 92
List Concatenation 94
The in Operator . 94
Calling Methods . 94
The reverse() and append() List Methods . 95
The split() String Method . 95
Getting a Secret Word from the Word List . 96
Displaying the Board to the Player . 97
The list() and range() Functions . 98
List and String Slicing . 98
Displaying the Secret Word with Blanks 99
Getting the Player’s Guess 101
The lower() and upper() String Methods 101
Leaving the while Loop . 103
elif Statements 103
Making Sure the Player Entered a Valid Guess . 104
Asking the Player to Play Again 104
Review of the Hangman Functions . 105
The Game Loop 105
Calling the displayBoard() Function 106
Letting the Player Enter Their Guess 106
Checking Whether the Letter Is in the Secret Word . 106
Checking Whether the Player Won 107
Handling an Incorrect Guess . 107
Checking Whether the Player Lost 108
Ending or Resetting the Game 108
Summary . 109
9 Extending Hangman 111
Adding More Guesses . 112
The Dictionary Data Type . 112
Getting the Size of Dictionaries with len() 113
The Difference Between Dictionaries and Lists 113
The keys() and values() Dictionary Methods . 114
Using Dictionaries of Words in Hangman . 115
Randomly Choosing from a List . 115
Deleting Items from Lists . 117
Multiple Assignment 118
Printing the Word Category for the Player 119
Summary . 120
10 Tic-Ta c-Toe 121
Sample Run of Tic-Tac-Toe 122
Source Code for Tic-Tac-Toe . 123
Designing the Program 127
Representing the Board as Data . 127
Strategizing with the Game AI . 128
Importing the random Module 129
Printing the Board on the Screen . 129
Letting the Player Choose X or O . 130
Deciding Who Goes First . 131
Placing a Mark on the Board 131
List References . 132
Using List References in makeMove() 135
Checking Whether the Player Won . 135
Duplicating the Board Data 137
Checking Whether a Space on the Board Is Free 138
Letting the Player Enter a Move . 138
Contents in Detail xiii
Short-Circuit Evaluation 139
Choosing a Move from a List of Moves 141
The None Value 142
Creating the Computer’s AI 142
Checking Whether the Computer Can Win in One Move . 143
Checking Whether the Player Can Win in One Move . 144
Checking the Corner, Center, and Side Spaces (in That Order) . 144
Checking Whether the Board Is Full 145
The Game Loop 145
Choosing the Player’s Mark and Who Goes First . 146
Running the Player’s Turn 146
Running the Computer’s Turn . 147
Asking the Player to Play Again . 148
Summary . 148
11 The Bagels Deduction Game 149
Sample Run of Bagels 150
Source Code for Bagels . 151
Flowchart for Bagels 152
Importing random and Defining getSecretNum() . 153
Shuffling a Unique Set of Digits . 154
Changing List Item Order with the random.shuffle() Function 154
Getting the Secret Number from the Shuffled Digits 154
Augmented Assignment Operators 155
Calculating the Clues to Give . 156
The sort() List Method . 157
The join() String Method . 158
Checking Whether a String Has Only Numbers 158
Starting the Game . 159
String Interpolation 159
The Game Loop 160
Getting the Player’s Guess . 161
Getting the Clues for the Player’s Guess 161
Checking Whether the Player Won or Lost 161
Asking the Player to Play Again . 162
Summary . 162
12 The Cartesian Coordinate System 163
Grids and Cartesian Coordinates 164
Negative Numbers 166
The Coordinate System of a Computer Screen 167
Math Tricks 168
Trick 1: A Minus Eats the Plus Sign on Its Left . 168
Trick 2: Two Minuses Combine into a Plus . 169
Trick 3: Two Numbers Being Added Can Swap Places . 169
Absolute Values and the abs() Function 170
Summary . 170
13 Sonar Treasure Hunt 171
Sample Run of Sonar Treasure Hunt  173
Source Code for Sonar Treasure Hunt 175
Designing the Program 180
Importing the random, sys, and math Modules 180
Creating a New Game Board 180
Drawing the Game Board 181
Drawing the X-Coordinates Along the Top of the Board 182
Drawing the Ocean 183
Printing a Row in the Ocean 184
Drawing the X-Coordinates Along the Bottom of the Board 184
Creating the Random Treasure Chests 184
Determining Whether a Move Is Valid . 185
Placing a Move on the Board . 185
Finding the Closest Treasure Chest . 186
Removing Values with the remove() List Method . 189
Getting the Player’s Move . 190
Printing the Game Instructions for the Player . 191
The Game Loop 192
Displaying the Game Status for the Player . 193
Handling the Player’s Move . 193
Finding a Sunken Treasure Chest . 194
Checking Whether the Player Won 194
Checking Whether the Player Lost 195
Terminating the Program with the sys.exit() Function . 195
Summary . 196
14 Caesar Cipher 197
Cryptography and Encryption . 198
How the Caesar Cipher Works . 199
Sample Run of Caesar Cipher 200
Source Code for Caesar Cipher 201
Setting the Maximum Key Length . 202
Deciding to Encrypt or Decrypt the Message 202
Getting the Message from the Player . 203
Getting the Key from the Player . 203
Encrypting or Decrypting the Message . 203
Finding Passed Strings with the find() String Method . 204
Encrypting or Decrypting Each Letter 205
Starting the Program 206
The Brute-Force Technique 206
Adding the Brute-Force Mode . 207
Summary . 208
15 The Reversegam Game 209
How to Play Reversegam 210
Sample Run of Reversegam 213
Contents in Detail xv
Source Code for Reversegam . 215
Importing Modules and Setting Up Constants 220
The Game Board Data Structure 220
Drawing the Board Data Structure on the Screen 221
Creating a Fresh Board Data Structure 222
Checking Whether a Move Is Valid . 222
Checking Each of the Eight Directions . 223
Finding Out Whether There Are Tiles to Flip Over 224
Checking for Valid Coordinates 225
Getting a List with All Valid Moves . 226
Calling the bool() Function 227
Getting the Score of the Game Board 227
Getting the Player’s Tile Choice 228
Determining Who Goes First 228
Placing a Tile on the Board 229
Copying the Board Data Structure . 229
Determining Whether a Space Is on a Corner 230
Getting the Player’s Move 230
Getting the Computer’s Move . 232
Strategizing with Corner Moves . 232
Getting a List of the Highest-Scoring Moves . 233
Printing the Scores to the Screen . 234
Starting the Game . 234
Checking for a Stalemate 234
Running the Player’s Turn 235
Running the Computer’s Turn . 236
The Game Loop 237
Asking the Player to Play Again 238
Summary . 238
16 Reversegam AI Simulation 239
Making the Computer Play Against Itself 240
Sample Run of Simulation 1 . 240
Source Code for Simulation 1 241
Removing the Player Prompts and Adding a Computer Player 242
Making the Computer Play Itself Several Times 243
Sample Run of Simulation 2 . 243
Source Code for Simulation 2 244
Keeping Track of Multiple Games 245
Commenting Out print() Function Calls 245
Using Percentages to Grade the AIs . 246
Comparing Different AI Algorithms 247
Source Code for Simulation 3 248
How the AIs Work in Simulation 3 . 249
Comparing the AIs . 252
Summary . 254
17 Creating Graphics 255
Installing pygame 256
Hello World in pygame . 256
Sample Run of pygame Hello World . 257
Source Code for pygame Hello World . 257
Importing the pygame Module 259
Initializing pygame 259
Setting Up the pygame Window . 260
Tuples . 260
Surface Objects . 261
Setting Up Color Variables . 261
Writing Text on the pygame Window 262
Using Fonts to Style Text 262
Rendering a Font Object . 263
Setting the Text Location with Rect Attributes 264
Filling a Surface Object with a Color . 266
pygame’s Drawing Functions 266
Drawing a Polygon 266
Drawing a Line 267
Drawing a Circle . 268
Drawing an Ellipse . 268
Drawing a Rectangle 268
Coloring Pixels 269
The blit() Method for Surface Objects  270
Drawing the Surface Object to the Screen 270
Events and the Game Loop . 270
Getting Event Objects . 271
Exiting the Program 271
Summary . 272
18 Animating Graphics 273
Sample Run of the Animation Program . 274
Source Code for the Animation Program 274
Moving and Bouncing the Boxes . 276
Setting Up the Constant Variables . 277
Constant Variables for Direction . 277
Constant Variables for Color . 278
Setting Up the Box Data Structures 278
The Game Loop 279
Handling When the Player Quits 279
Moving Each Box . 280
Bouncing a Box . 281
Drawing the Boxes on the Window in Their New Positions 282
Drawing the Window on the Screen . 282
Summary . 283
19 Collision Detection 285
Sample Run of the Collision Detection Program . 286
Source Code for the Collision Detection Program 287
Importing the Modules . 289
Using a Clock to Pace the Program . 289
Setting Up the Window and Data Structures . 290
Setting Up Variables to Track Movement 291
Handling Events 292
Handling the KEYDOWN Event . 293
Handling the KEYUP Event 294
Teleporting the Player 295
Adding New Food Squares 295
Moving the Player Around the Window . 296
Drawing the Player on the Window 297
Checking for Collisions . 297
Drawing the Food Squares on the Window 298
Summary . 299
20 Using Sounds and Images 301
Adding Images with Sprites 302
Sound and Image Files 302
Sample Run of the Sprites and Sounds Program 303
Source Code for the Sprites and Sounds Program . 304
Setting Up the Window and the Data Structure . 306
Adding a Sprite . 307
Changing the Size of a Sprite 307
Setting Up the Music and Sounds 307
Adding Sound Files 308
Toggling the Sound On and Off . 308
Drawing the Player on the Window . 309
Checking for Collisions 309
Drawing the Cherries on the Window 310
Summary . 310
21 A Dodger Game with Sounds and Images 311
Review of the Basic pygame Data Types 312
Sample Run of Dodger . 313
Source Code for Dodger 313
Importing the Modules . 317
Setting Up the Constant Variables . 318
Defining Functions . 319
Ending and Pausing the Game  319
Keeping Track of Baddie Collisions 320
Drawing Text to the Window . 320
xviii Contents in Detail
Initializing pygame and Setting Up the Window . 321
Setting Up Font, Sound, and Image Objects . 322
Displaying the Start Screen . 323
Starting the Game 324
The Game Loop 325
Handling Keyboard Events 325
Handling Mouse Movement . 327
Adding New Baddies 327
Moving the Player’s Character and the Baddies 328
Implementing the Cheat Codes . 329
Removing the Baddies . 330
Drawing the Window 330
Drawing the Player’s Score . 331
Drawing the Player’s Character and Baddies . 331
Checking for Collisions 332
The Game Over Screen . 332
Modifying the Dodger Game 333
Summary . 334
Index 335


Bookscreen
e-books shop

Who Is This Book For?
Programming isn’t hard, but it is hard to find materials that teach you to
do interesting things with programming. Other computer books go over
many topics most new coders don’t need. This book will teach you how to
program your own games; you’ll learn a useful skill and have fun games to
show for it! This book is for:
• Complete beginners who want to teach themselves programming, even
if they have no previous experience.
• Kids and teenagers who want to learn programming by creating games.
• Adults and teachers who wish to teach others programming.
• Anyone, young or old, who wants to learn how to program by learning a
professional programming language.
Loading...
DMCA.com Protection Status