Invent Your Own Computer Games with Python

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

Invent Your Own Computer Games with Python will teach you how to make computer games using the popular Python programming language—even if you’ve never programmed before! Begin by building classic games like Hangman, Guess the Number, and Tic-Tac-Toe, and then work your way up to more advanced games, like a text-based treasure hunting game and an animated collision-dodging game with sound effects. Along the way, you’ll learn key programming and math concepts that will help you take your game programming to the next level. Learn how to: –Combine loops, variables, and flow control statements into real working programs –Choose the right data structures for the job, such as lists, dictionaries, and tuples –Add graphics and animation to your games with the pygame module –Handle keyboard and mouse input –Program simple artificial intelligence so you can play against the computer –Use cryptography to convert text messages into secret code –Debug your programs and find common errors As you work through each game, you’ll build a solid foundation in Python and an understanding of computer science fundamentals. What new game will you create with the power of Python? The projects in this book are compatible with Python 3.

Author(s): Al Sweigart
Edition: 4
Publisher: No Starch Press
Year: 2016

Language: English
Pages: 376

Title Page
Copyright Page
About the Author
About the Technical Reviewer
Brief Contents
Contents in Detail
Acknowledgments
Introduction
Who Is This Book For?
About This Book
How to Use This Book
Line Numbers and Indentation
Long Code Lines
Downloading and Installing Python
Starting IDLE
Finding Help Online
Chapter 1: The Interactive Shell
Some Simple Math
Integers and Floating-Point Numbers
Expressions
Evaluating Expressions
Syntax Errors
Storing Values in Variables
Summary
Chapter 2: Writing Programs
String Values
String Concatenation
Writing Programs in IDLE’s File Editor
Creating the Hello World Program
Saving Your Program
Running Your Program
How the Hello World Program Works
Comments for the Programmer
Functions: Mini-Programs Inside Programs
The End of the Program
Naming Variables
Summary
Chapter 3: Guess the Number
Sample Run of Guess the Number
Source Code for Guess the Number
Importing the random Module
Generating Random Numbers with the random.randint() Function
Welcoming the Player
Flow Control Statements
Using Loops to Repeat Code
Grouping with Blocks
Looping with for Statements
Getting the Player’s Guess
Converting Values with the int(), float(), and str() Functions
The Boolean Data Type
Comparison Operators
Checking for True or False with Conditions
Experimenting with Booleans, Comparison Operators, and Conditions
The Difference Between = and ==
if Statements
Leaving Loops Early with the break Statement
Checking Whether the Player Won
Checking Whether the Player Lost
Summary
Chapter 4: A Joke-Telling Program
Sample Run of Jokes
Source Code for Jokes
How the Code Works
Escape Characters
Single and Double Quotes
The print() Function’s end Keyword Parameter
Summary
Chapter 5: Dragon Realm
How to Play Dragon Realm
Sample Run of Dragon Realm
Flowchart for Dragon Realm
Source Code for Dragon Realm
Importing the random and time Modules
Functions in Dragon Realm
def Statements
Calling a Function
Where to Put Function Definitions
Multiline Strings
How to Loop with while Statements
Boolean Operators
The and Operator
The or Operator
The not Operator
Evaluating Boolean Operators
Return Values
Global Scope and Local Scope
Function Parameters
Displaying the Game Results
Deciding Which Cave Has the Friendly Dragon
The Game Loop
Calling the Functions in the Program
Asking the Player to Play Again
Summary
Chapter 6: Using the Debugger
Types of Bugs
The Debugger
Starting the Debugger
Stepping Through the Program with the Debugger
Finding the Bug
Setting Breakpoints
Using Breakpoints
Summary
Chapter 7: Designing Hangman with Flowcharts
How to Play Hangman
Sample Run of Hangman
ASCII Art
Designing a Program with a Flowchart
Creating the Flowchart
Branching from a Flowchart Box
Ending or Restarting the Game
Guessing Again
Offering Feedback to the Player
Summary
Chapter 8: Writing the Hangman Code
Source Code for Hangman
Importing the random Module
Constant Variables
The Lists Data Type
Accessing Items with Indexes
List Concatenation
The in Operator
Calling Methods
The reverse() and append() List Methods
The split() String Method
Getting a Secret Word from the Word List
Displaying the Board to the Player
The list() and range() Functions
List and String Slicing
Displaying the Secret Word with Blanks
Getting the Player’s Guess
The lower() and upper() String Methods
Leaving the while Loop
elif Statements
Making Sure the Player Entered a Valid Guess
Asking the Player to Play Again
Review of the Hangman Functions
The Game Loop
Calling the displayBoard() Function
Letting the Player Enter Their Guess
Checking Whether the Letter Is in the Secret Word
Checking Whether the Player Won
Handling an Incorrect Guess
Checking Whether the Player Lost
Ending or Resetting the Game
Summary
Chapter 9: Extending Hangman
Adding More Guesses
The Dictionary Data Type
Getting the Size of Dictionaries with len()
The Difference Between Dictionaries and Lists
The keys() and values() Dictionary Methods
Using Dictionaries of Words in Hangman
Randomly Choosing from a List
Deleting Items from Lists
Multiple Assignment
Printing the Word Category for the Player
Summary
Chapter 10: Tic-Tac-Toe
Sample Run of Tic-Tac-Toe
Source Code for Tic-Tac-Toe
Designing the Program
Representing the Board as Data
Strategizing with the Game AI
Importing the random Module
Printing the Board on the Screen
Letting the Player Choose X or O
Deciding Who Goes First
Placing a Mark on the Board
List References
Using List References in makeMove()
Checking Whether the Player Won
Duplicating the Board Data
Checking Whether a Space on the Board Is Free
Letting the Player Enter a Move
Short-Circuit Evaluation
Choosing a Move from a List of Moves
The None Value
Creating the Computer’s AI
Checking Whether the Computer Can Win in One Move
Checking Whether the Player Can Win in One Move
Checking the Corner, Center, and Side Spaces (in That Order)
Checking Whether the Board Is Full
The Game Loop
Choosing the Player’s Mark and Who Goes First
Running the Player’s Turn
Running the Computer’s Turn
Asking the Player to Play Again
Summary
Chapter 11: The Bagels Deduction Game
Sample Run of Bagels
Source Code for Bagels
Flowchart for Bagels
Importing random and Defining getSecretNum()
Shuffling a Unique Set of Digits
Changing List Item Order with the random.shuffle() Function
Getting the Secret Number from the Shuffled Digits
Augmented Assignment Operators
Calculating the Clues to Give
The sort() List Method
The join() String Method
Checking Whether a String Has Only Numbers
Starting the Game
String Interpolation
The Game Loop
Getting the Player’s Guess
Getting the Clues for the Player’s Guess
Checking Whether the Player Won or Lost
Asking the Player to Play Again
Summary
Chapter 12: The Cartesian Coordinate System
Grids and Cartesian Coordinates
Negative Numbers
The Coordinate System of a Computer Screen
Math Tricks
Trick 1: A Minus Eats the Plus Sign on Its Left
Trick 2: Two Minuses Combine into a Plus
Trick 3: Two Numbers Being Added Can Swap Places
Absolute Values and the abs() Function
Summary
Chapter 13: Sonar Treasure Hunt
Sample Run of Sonar Treasure Hunt
Source Code for Sonar Treasure Hunt
Designing the Program
Importing the random, sys, and math Modules
Creating a New Game Board
Drawing the Game Board
Drawing the X-Coordinates Along the Top of the Board
Drawing the Ocean
Printing a Row in the Ocean
Drawing the X-Coordinates Along the Bottom of the Board
Creating the Random Treasure Chests
Determining Whether a Move Is Valid
Placing a Move on the Board
Finding the Closest Treasure Chest
Removing Values with the remove() List Method
Getting the Player’s Move
Printing the Game Instructions for the Player
The Game Loop
Displaying the Game Status for the Player
Handling the Player’s Move
Finding a Sunken Treasure Chest
Checking Whether the Player Won
Checking Whether the Player Lost
Terminating the Program with the sys.exit() Function
Summary
Chapter 14: Caesar Cipher
Cryptography and Encryption
How the Caesar Cipher Works
Sample Run of Caesar Cipher
Source Code for Caesar Cipher
Setting the Maximum Key Length
Deciding to Encrypt or Decrypt the Message
Getting the Message from the Player
Getting the Key from the Player
Encrypting or Decrypting the Message
Finding Passed Strings with the find() String Method
Encrypting or Decrypting Each Letter
Starting the Program
The Brute-Force Technique
Adding the Brute-Force Mode
Summary
Chapter 15: The Reversegam Game
How to Play Reversegam
Sample Run of Reversegam
Source Code for Reversegam
Importing Modules and Setting Up Constants
The Game Board Data Structure
Drawing the Board Data Structure on the Screen
Creating a Fresh Board Data Structure
Checking Whether a Move Is Valid
Checking Each of the Eight Directions
Finding Out Whether There Are Tiles to Flip Over
Checking for Valid Coordinates
Getting a List with All Valid Moves
Calling the bool() Function
Getting the Score of the Game Board
Getting the Player’s Tile Choice
Determining Who Goes First
Placing a Tile on the Board
Copying the Board Data Structure
Determining Whether a Space Is on a Corner
Getting the Player’s Move
Getting the Computer’s Move
Strategizing with Corner Moves
Getting a List of the Highest-Scoring Moves
Printing the Scores to the Screen
Starting the Game
Checking for a Stalemate
Running the Player’s Turn
Running the Computer’s Turn
The Game Loop
Asking the Player to Play Again
Summary
Chapter 16: Reversegam AI Simulation
Making the Computer Play Against Itself
Sample Run of Simulation 1
Source Code for Simulation 1
Removing the Player Prompts and Adding a Computer Player
Making the Computer Play Itself Several Times
Sample Run of Simulation 2
Source Code for Simulation 2
Keeping Track of Multiple Games
Commenting Out print() Function Calls
Using Percentages to Grade the AIs
Comparing Different AI Algorithms
Source Code for Simulation 3
How the AIs Work in Simulation 3
Comparing the AIs
Summary
Chapter 17: Creating Graphics
Installing pygame
Hello World in pygame
Sample Run of pygame Hello World
Source Code for pygame Hello World
Importing the pygame Module
Initializing pygame
Setting Up the pygame Window
Tuples
Surface Objects
Setting Up Color Variables
Writing Text on the pygame Window
Using Fonts to Style Text
Rendering a Font Object
Setting the Text Location with Rect Attributes
Filling a Surface Object with a Color
pygame’s Drawing Functions
Drawing a Polygon
Drawing a Line
Drawing a Circle
Drawing an Ellipse
Drawing a Rectangle
Coloring Pixels
The blit() Method for Surface Objects
Drawing the Surface Object to the Screen
Events and the Game Loop
Getting Event Objects
Exiting the Program
Summary
Chapter 18: Animating Graphics
Sample Run of the Animation Program
Source Code for the Animation Program
Moving and Bouncing the Boxes
Setting Up the Constant Variables
Constant Variables for Direction
Constant Variables for Color
Setting Up the Box Data Structures
The Game Loop
Handling When the Player Quits
Moving Each Box
Bouncing a Box
Drawing the Boxes on the Window in Their New Positions
Drawing the Window on the Screen
Summary
Chapter 19: Collision Detection
Sample Run of the Collision Detection Program
Source Code for the Collision Detection Program
Importing the Modules
Using a Clock to Pace the Program
Setting Up the Window and Data Structures
Setting Up Variables to Track Movement
Handling Events
Handling the KEYDOWN Event
Handling the KEYUP Event
Teleporting the Player
Adding New Food Squares
Moving the Player Around the Window
Drawing the Player on the Window
Checking for Collisions
Drawing the Food Squares on the Window
Summary
Chapter 20: Using Sounds and Images
Adding Images with Sprites
Sound and Image Files
Sample Run of the Sprites and Sounds Program
Source Code for the Sprites and Sounds Program
Setting Up the Window and the Data Structure
Adding a Sprite
Changing the Size of a Sprite
Setting Up the Music and Sounds
Adding Sound Files
Toggling the Sound On and Off
Drawing the Player on the Window
Checking for Collisions
Drawing the Cherries on the Window
Summary
Chapter 21: A Dodger Game with Sounds and Images
Review of the Basic pygame Data Types
Sample Run of Dodger
Source Code for Dodger
Importing the Modules
Setting Up the Constant Variables
Defining Functions
Ending and Pausing the Game
Keeping Track of Baddie Collisions
Drawing Text to the Window
Initializing pygame and Setting Up the Window
Setting Up Font, Sound, and Image Objects
Displaying the Start Screen
Starting the Game
The Game Loop
Handling Keyboard Events
Handling Mouse Movement
Adding New Baddies
Moving the Player’s Character and the Baddies
Implementing the Cheat Codes
Removing the Baddies
Drawing the Window
Drawing the Player’s Score
Drawing the Player’s Character and Baddies
Checking for Collisions
The Game Over Screen
Modifying the Dodger Game
Summary
Index
Resources
The Electronic Frontier Foundation (EFF)
Don’t Just Play Games—Make Them!