Download Python Programming: Understanding Operators, Strings, and Functions and more Study notes Computer Science in PDF only on Docsity!
i
Invent Your Own
Computer Games
with Python, 2
nd
Edition
By Al Sweigart
ii
Copyright © 2008-2012 by Albert Sweigart
Some Rights Reserved. "Invent Your Own Computer Games with Python" ("Invent with Python") is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
You are free:
To Share — to copy, distribute, display, and perform the work
To Remix — to make derivative works
Under the following conditions:
Attribution — You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). (Visibly include the title and author's name in any excerpts of this work.)
Noncommercial — You may not use this work for commercial purposes.
Share Alike — If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one.
This summary is located here: http://creativecommons.org/licenses/by-nc-sa/3.0/us/
Your fair use and other rights are in no way affected by the above. There is a human-readable summary of the Legal Code (the full license), located here: http://creativecommons.org/licenses/by-nc-sa/3.0/us/legalcode
Book Version 31
If you've downloaded this book from a torrent, it’s probably out of date. Go
to http://inventwithpython.com to download the latest version instead.
ISBN 978-0-9821060-1-
2.1 Edition
iv
For Caro, with more love
than I ever knew I had.
v
A Note to Parents and
Fellow Programmers
Thank your for reading this book. My motivation for writing this book comes from a gap I saw in today's literature for kids interested in learning to program. I started programming when I was 9 years old in the BASIC language with a book similar to this one. During the course of writing this, I've realized how a modern language like Python has made programming far easier and versatile for a new generation of programmers. Python has a gentle learning curve while still being a serious language that is used by programmers professionally.
The current crop of programming books for kids that I've seen fell into two categories. First, books that did not teach programming so much as "game creation software" or a dumbed-down languages to make programming "easy" (to the point that it is no longer programming). Or second, they taught programming like a mathematics textbook: all principles and concepts with little application given to the reader. This book takes a different approach: show the source code for games right up front and explain programming principles from the examples.
I have also made this book available under the Creative Commons license, which allows you to make copies and distribute this book (or excerpts) with my full permission, as long as attribution to me is left intact and it is used for noncommercial purposes. (See the copyright page.) I want to make this book a gift to a world that has given me so much.
Thank you again for reading this book, and feel free to email me any questions or comments.
Al Sweigart
[email protected]
The full text of this book is available in HTML or PDF format at:
http://inventwithpython.com
vii
The get_rect() Methods for pygame.font.Font and pygame.Surface Objects
- Installing Python TABLE OF CONTENTS
- Downloading and Installing Python.............................................................................................
- Windows Instructions
- Mac OS X Instructions.................................................................................................................
- Ubuntu and Linux Instructions
- Starting Python.............................................................................................................................
- How to Use This Book.................................................................................................................
- The Featured Programs
- Line Numbers and Spaces
- Text Wrapping in This Book
- Tracing the Program Online
- Checking Your Code Online
- Summary
- The Interactive Shell
- Some Simple Math Stuff
- Integers and Floating Point Numbers...........................................................................................
- Expressions
- Evaluating Expressions
- Expressions Inside Other Expressions
- Storing Values in Variables
- Using More Than One Variable
- Overwriting Variables
- Summary
- Strings
- Strings
- String Concatenation..................................................................................................................
- Writing Programs in IDLE's File Editor viii
- Hello World!
- hello.py
- Saving Your Program
- Opening The Programs You've Saved
- How the “Hello World” Program Works
- Comments
- Functions
- The print() function
- The input() function
- Ending the Program
- Variable Names
- Summary
- Guess the Number
- The “Guess the Number” Game.................................................................................................
- Sample Run of “Guess the Number”
- Guess the Number's Source Code
- The import statement
- The random.randint() function
- Calling Functions that are Inside Modules
- Passing Arguments to Functions
- Welcoming the Player
- Loops
- Blocks
- The Boolean Data Type
- Comparison Operators
- Conditions
- Experiment with Booleans, Comparison Operators, and Conditions.........................................
- Looping with while statements
- The Player Guesses ix
- Converting Strings to Integers with the int() function
- Incrementing Variables
- if statements
- Is the Player's Guess Too Low?
- Is the Player's Guess Too High?
- Leaving Loops Early with the break statement.......................................................................
- Check if the Player Won
- Check if the Player Lost
- Summary: What Exactly is Programming?
- A Web Page for Program Tracing..............................................................................................
- Jokes...............................................................................................................................................
- Making the Most of print()
- Sample Run of Jokes
- Joke's Source Code
- How the Code Works
- Escape Characters
- Some Other Escape Characters
- Quotes and Double Quotes
- The end Keyword Argument
- Summary
- Dragon Realm
- Introducing Functions
- How to Play “Dragon Realm”
- Sample Run of Dragon Realm
- Dragon Realm's Source Code
- How the Code Works
- Defining the displayIntro() Function
- def Statements
- Defining the chooseCave() Function................................................................................... x
- Boolean Operators
- Evaluating an Expression That Contains Boolean Operators
- Experimenting with the and and or Operators
- Experimenting with the not Operator
- Truth Tables
- Getting the Player's Input
- Return Values.............................................................................................................................
- Variable Scope
- Global Scope and Local Scope
- Defining the checkCave() Function
- Parameters
- Where to Put Function Definitions
- Displaying the Game Results
- Deciding Which Cave has the Friendly Dragon
- The Colon :
- Where the Program Really Begins
- Calling the Functions in Our Program
- Asking the Player to Play Again
- Designing the Program
- Summary
- Using the Debugger
- Bugs!
- The Debugger.............................................................................................................................
- Starting the Debugger
- Stepping
- Click the Step button twice to run the two import lines.
- Click the Step button three more times to execute the three def statements.
- Click the Step button again to define the playAgain variable.
- The Go and Quit Buttons xi
- Stepping Into, Over, and Out
- Find the Bug...............................................................................................................................
- Break Points
- Example of Using Break Points
- Summary
- Flow Charts
- How to Play “Hangman”
- Sample Run of “Hangman”
- ASCII Art
- Designing a Program with a Flowchart......................................................................................
- Creating the Flow Chart
- Branching from a Flowchart Box...............................................................................................
- Ending or Restarting the Game
- Guessing Again
- Offering Feedback to the Player
- Summary: The Importance of Planning Out the Game
- Hangman
- Hangman's Source Code
- How the Code Works
- Multi-line Strings
- Constant Variables
- Lists
- Changing the Values of List Items with Index Assignment
- List Concatenation
- The in Operator
- Removing Items from Lists with del Statements
- Lists of Lists.............................................................................................................................
- Methods
- The lower() and upper() String Methods xii
- The reverse() and append() List Methods
- The Difference Between Methods and Functions
- The split() List Method
- How the Code Works
- Displaying the Board to the Player
- The range() and list() Functions...................................................................................
- for Loops
- A while Loop Equivalent of a for Loop
- Slices and Slicing
- Displaying the Secret Word with Blanks
- Replacing the Underscores with Correctly Guessed Letters
- Get the Player's Guess
- elif (“Else If”) Statements
- Making Sure the Player Entered a Valid Guess
- Asking the Player to Play Again
- Review of the Functions We Defined
- The Main Code for Hangman
- Setting Up the Variables
- Displaying the Board to the Player
- Letting the Player Enter Their Guess
- Checking if the Letter is in the Secret Word
- Checking if the Player has Won
- When the Player Guesses Incorrectly
- Making New Changes to the Hangman Program.....................................................................
- Dictionaries
- Getting the Size of Dictionaries with len()
- The Difference Between Dictionaries and Lists
- Sets of Words for Hangman
- The random.choice() Function xiii
- Evaluating a Dictionary of Lists
- Multiple Assignment
- Printing the Word Category for the Player
- Summary
- Tic Tac Toe
- Sample Run of Tic Tac Toe
- Source Code of Tic Tac Toe
- Designing the Program
- Representing the Board as Data
- Game AI
- How the Code Works: Lines 1 to
- The Start of the Program
- Printing the Board on the Screen
- Letting the Player be X or O
- Deciding Who Goes First.....................................................................................................
- Asking the Player to Play Again
- Placing a mark on the Board
- List References.........................................................................................................................
- Using List References in makeMove()
- Checking if the Player Has Won
- Duplicating the Board Data
- Checking if a Space on the Board is Free
- Letting the Player Enter Their Move
- Short-Circuit Evaluation
- An Example of Short-Circuit Evaluation
- The First if statement (Cats and Dogs)
- The Second if statement (Hello and Goodbye)
- The Third if statement (Spam and Cheese)
- The Fourth if statement (Red and Blue) xiv
- How the Code Works: Lines 83 to
- Choosing a Move from a List of Moves
- The None Value
- How the Code Works: Lines 96 to
- Creating the Computer's Artificial Intelligence
- The Computer Checks if it Can Win in One Move
- The Computer Checks if the Player Can Win in One Move
- Checking the Corner, Center, and Side Spaces (in that Order)
- Checking if the Board is Full
- The Start of the Game
- Deciding the Player's Mark and Who Goes First
- Running the Player's Turn
- Running the Computer's Turn
- Summary: Creating Game-Playing Artificial Intelligences
- Bagels...........................................................................................................................................
- Sample Run
- Bagel's Source Code
- Designing the Program
- How the Code Works: Lines 1 to
- Shuffling a Unique Set of Digits
- The random.shuffle() Function
- Getting the Secret Number from the Shuffled Digits...............................................................
- Augmented Assignment Operators
- How the Code Works: Lines 11 to
- The sort() List Method
- The join() String Method
- How the Code Works: Lines 29 to
- Checking if a String Only has Numbers
- Finding out if the Player Wants to Play Again xv
- The Start of the Game
- String Interpolation
- How the Code Works: Lines 55 to
- Creating the Secret Number
- Getting the Player's Guess
- Getting the Clues for the Player's Guess
- Checking if the Player Won or Lost.....................................................................................
- Asking the Player to Play Again
- Summary: Getting Good at Bagels
- Cartesian Coordinates
- Grids and Cartesian Coordinates..............................................................................................
- Negative Numbers
- Math Tricks
- Trick 1: “A Minus Eats the Plus Sign on its Left”
- Trick 2: “Two Minuses Combine Into a Plus”
- Trick 3: The Commutative Property of Addition
- Absolute Values and the abs() Function
- Coordinate System of a Computer Monitor
- Summary: Using this Math in Games
- Sonar
- Sample Run
- Sonar's Source Code
- Designing the Program
- How the Code Works: Lines 1 to
- Drawing the Game Board
- Drawing the X-coordinates Along the Top
- Drawing the Rows of the Ocean
- Drawing the X-coordinates Along the Bottom
- Getting the State of a Row in the Ocean xvi
- How the Code Works: Lines 40 to
- Creating a New Game Board
- Creating the Random Treasure Chests
- Determining if a Move is Valid
- How the Code Works: Lines 64 to
- Placing a Move on the Board
- An Algorithm for Finding the Closest Treasure Chest
- The remove() List Method
- How the Code Works: Lines 94 to
- Getting the Player's Move
- Asking the Player to Play Again
- Printing the Game Instructions for the Player
- How the Code Works: Lines 165 to
- The Start of the Game
- Displaying the Game Status for the Player
- Getting the Player's Move
- Finding a Sunken Treasure Chest
- Checking if the Player has Won
- Checking if the Player has Lost
- Asking the Player to Play Again, and the sys.exit() Function..............................................
- Summary: Review of our Sonar Game
- Caesar Cipher
- About Cryptography
- The Caesar Cipher....................................................................................................................
- ASCII, and Using Numbers for Letters
- The chr() and ord() Functions
- Sample Run of Caesar Cipher
- Caesar Cipher's Source Code
- How the Code Works: Lines 1 to xvii
- Deciding to Encrypt or Decrypt
- Getting the Message from the Player
- Getting the Key from the Player
- Encrypt or Decrypt the Message with the Given Key..........................................................
- The isalpha() String Method.............................................................................................
- The isupper() and islower() String Methods
- How the Code Works: Lines 36 to
- Encrypting or Decrypting Each Letter
- The Start of the Program
- Brute Force...............................................................................................................................
- Adding the Brute Force Mode to Our Program
- Summary: Reviewing Our Caesar Cipher Program
- Reversi
- Sample Run
- Reversi's Source Code..............................................................................................................
- How the Code Works
- The Game Board Data Structure
- Importing Other Modules.....................................................................................................
- Drawing the Board Data Structure on the Screen
- Resetting the Game Board
- Setting Up the Starting Pieces
- Creating a New Game Board Data Structure
- Checking if a Move is Valid
- Checking Each of the Eight Directions
- Finding Out if There are Pieces to Flip Over
- Checking for Valid Coordinates
- Getting a List with All Valid Moves
- The bool() Function
- Getting the Score of the Game Board xviii
- Getting the Player's Tile Choice
- Determining Who Goes First
- Asking the Player to Play Again
- Placing Down a Tile on the Game Board
- Copying the Board Data Structure
- Determining if a Space is on a Corner
- Getting the Player's Move
- Getting the Computer's Move
- Corner Moves are the Best Moves
- Get a List of the Best Scoring Moves
- Simulate All Possible Moves on Duplicate Board Data Structures
- Printing the Scores to the Screen
- The Start of the Game
- Running the Player's Turn
- Handling the Quit or Hints Commands
- Make the Player's Move
- Running the Computer's Turn
- Drawing Everything on the Screen
- Ask the Player to Play Again
- Changing the drawBoard() Function..............................................................................
- Summary: Reviewing the Reversi Game
- AI Simulation
- Making the Computer Play Against Itself................................................................................
- How the AISim1.py Code Works
- Making the Computer Play Itself Several Times
- How the AISim2.py Code Works
- Percentages
- Division Evaluates to Floating Point
- The round() function xix
- Displaying the Statistics
- Comparing Different AI Algorithms........................................................................................
- How the AISim3.py Code Works
- Comparing the Random Algorithm Against the Regular Algorithm
- Comparing the Random Algorithm Against Itself
- Comparing the Regular Algorithm Against the CornersSideBest Algorithm
- Comparing the Regular Algorithm Against the Worst Algorithm
- Comparing the Regular Algorithm Against the WorstCorner Algorithm
- Comparing the Worst Algorithm Against the WorstCorner Algorithm
- Summary: Learning New Things by Running Simulation Experiments
- Graphics and Animation
- Installing Pygame.....................................................................................................................
- Hello World in Pygame
- Hello World's Source Code......................................................................................................
- Running the Hello World Program
- Importing the Pygame Module
- The pygame.init() Function
- Functions The pygame.display.set_mode() and pygame.display.set_caption()
- Colors in Pygame
- Fonts, and the pygame.font.SysFont() Function
- The render() Method for Font Objects
- Attributes
- Constructor Functions and the type() Function
- The fill() Method for Surface Objects...............................................................................
- The pygame.draw.polygon() Function
- The pygame.draw.line() Function xx
- The pygame.draw.circle() Function
- The pygame.draw.ellipse() Function
- The pygame.draw.rect() Function
- The pygame.PixelArray Data Type
- The blit() Method for Surface Objects...............................................................................
- The pygame.display.update() Function
- Events and the Game Loop
- The pygame.event.get() Function
- The pygame.quit() Function
- Animation
- The Animation Program's Source Code
- How the Animation Program Works
- Moving and Bouncing the Blocks
- Creating and Setting Up Pygame and the Main Window
- Setting Up Constant Variables for Direction
- Setting Up Constant Variables for Color
- Setting Up The Block Data Structures
- Running the Game Loop
- Moving Each Block
- Checking if the Block has Bounced
- Changing the Direction of the Bouncing Block
- Drawing the Blocks on the Window in Their New Positions
- Drawing the Window on the Screen
- Some Small Modifications
- Drawing as Fast as Possible
- Drawing Trails of Blocks
- Summary: Pygame Programming
- Collision Detection and Input