id
int64
0
25.6k
text
stringlengths
0
4.59k
10,500
five appendices using error messages you can expect to make some errors while coding idle provides information about the location and type of errors in several waysdepending on the kind of error to be most usefulyou want to be able to decode the error feedback idle developers keep updating error messages to make them more useful the versions shown below are for python to illustratei start from file that is purposefully incorrectexample program badexamplecode pyto show off debugging ideasx input("enter number" print(' more is {}format(yprint('now we are done! also have an initial documentation linefollowed by lots of blank linesso the popup window shown below does not obscure any code if try to run this codei get pop-up invalid syntax window indicates the syntax error was found by the interpreter in just trying to read the program never getting to execution after you click on okthe popup window goes awayand idle highlights where it detected that there was an erroryou should see the "pat the beginning of the last line with pink background highlight you should know that print statements are perfectly legal there does not seem to be an issue with the word print note carefully what said earlierthis is where the interpreter first noticed there was an errorthe actual error could be earlier it just was not clear that there was one yet the most common earlier place is the previous lineand illustrated the most common such error the interpreter did not find an error on the previous line because it did not
10,501
realize it was at the end of statement when can statement go on to the next linewhen there are unmatched grouping charactersmost commonly it is very easy to have unmatched parenthesesparticularly when there are many levels of pairs of parentheses recall that when you type in idle it shows you what closing parentheses match with here is the image just after added the correct final at the end of the previous linei did not show the progress in entering this program with its errorbut idle would have given clue if we back up to when the first incorrect print line was enteredright after the enter key is pressedyou would see note where the vertical bar cursor (|jumped tonot the beginning of the next linewhere you would put the next statement if you look where it is positioned relative to the previous lineit is just after the unmatched opening parenthesisthis is idle' conventionso if you are paying attention to the automatic cursor indentyou should realize there was an error with unmatched delimiters note that idle also should give you warning of the opposite errorif you add an excess close-parenthesisyou should hear beepindicating it was not expecting that character so now assume we have done this correction to the programadding the closing parenthesis if we try to run againanother syntax errorthis time at the end of the last lineand with more information about the error eol stands for "end of line"so it got all the way to the end of the line reading string literal the coloring also indicates thisgreen all the way to the end of the line what does string literal need at the enda final matching quote characterand we need closing parenthesisremembering our previous error suppose complete the line as print('now we are done!)' appendices
10,502
can now try to run again this time we do not get pop-up syntax error window this means the interpreter did not find any errors reading the program many errors are only found when running the programso execution starts in the shellleading to run-time error the program first prompts for numberand enter we see red error traceback we will discuss its various parts it shows the program line in this little short programit is easy to go back to the python source and locate the line idle also gives you help with this in generalthe next screen shows me right-clicking the mouse (or control-click on macon top of the red "line "where it is saying the error is this generates pop-up window the only allowed option is to select go to file/line and then the focus jumps to the window with the source codeand highlights the desired lineso we have the line with the execution error we still need to figure out what is going on the bottom line of the red traceback gave description of the errortypeerrorcan only concatenate str (not "int"to str think you could start by considering the implications of "concatenate"orsince it is type erroryou could look for the types it refers to let us start by looking at the types it refers to an int clearly we have there is something about string the other data is what is its typeof course the prompt in the previous line asks for numberbut what type is returned by the input functionalways stringlook at the expression again stringplus-signand number plus-sign after string means concatenationnot numeric addition as the error saysyou can only concatenate onto the first string with another stringnot an int we want numeric additionso we need two numbersand the string must be explicitly converted you might need to look that upbut you have an idea what you are looking forwe can use int as function to convert the string we do not need to add an extra line we can make start off as an intchanging the first line to using error messages
10,503
int(input("enter number")note that the error was suggesting fix that you do not wantending up with string concatenation when something does not make sensethe interpreter does not know what you mean it tries to make suggestion that is likely to be helpfulthough in this case it is wrong at least in this case it was suggesting something you should understand already we can go bit further in this casethough running the original first line by itself did not cause an errorlooking at the output aboveyou can see it is uglywith the prompt running into the user response this is logical error it is easy to correctchanging the ending of the first line prompt so we have int(input("enter number") print(' more is {}format( )print('now we are done!)'now run againone final logical error is the close-parenthesis in this output when debuggingi added required final quote character on the last linebut left an extra close-parenthesis in "fixingthe last line earlieri added another error am illustrating that this is unfortunately easy to dofinal codex int(input("enter number") print(' more is {}format( )print('now we are done!'final runso we have illustrated all three kinds of errorssyntax errors detected with pop-up window in idle before the program executesrun time errors causing red traceback sequence in the shell outputlogical errors that python does not findbut we need to note and troubleshoot in the source code when the results are not what we want appendices
10,504
chose common simple errorsso hopefully you would have been able to figure out the meaning of the error message that is lot to expect in general we are only gradually adding explanations of bits of python syntax you can easily make an error that the python interpreter guesses as being based on more advanced featureso the error message makes no sense to you even if you do not understand the error messageyou should get the information about where the error occurred hopefully concentrated look there will lead to you seeing the error and being able to correct it if you did not understand the original error messagethen there is further useful step after you do figure it out (with or without outside help)go back and consider the error message again after seeing what was actually wrongthe error message may make sense nowand that knowledge may be useful to speed up your understanding and your fix the next time you see that error message particularly as beginneryou can still hit brick wall some of the timeeven with partner you are also in course with an instructorthat is major reason am here ask for help if considering the information provided by idleplus little thoughtare not enoughnested calls in traceback in the previous example programthe execution error occured outside of any function call there are further useful features in an error tracebackwhen there are errors inside function calls we illustrateshowing the outputwith error tracebackfor silly example programshowtraceback py'''program with intended error to demonstrate traceback from nested call''def invminus ( )return /( - def main()print('this program is intended to cause an execution error 'print('ok call to invminus ( next:'print(invminus ( )print('bad call invminus ( next:'print(invminus ( )print("won' get to here!"main(note that the first call to invminus with parameter is fine /( - in the execution of the call invminus ( )we get an error traceback message the image below comes after the traceback is displayedand then just as the user uses the mouse to select the line where the error wasnote that after the title line in the traceback there are three indented lines starting with "file"not just one line as in the earlier program the bottom file line shows the line where the error occurredand we could jump to the sourcecontinuing from the step in the previous imagethe error takes place in functionand function can be called in many places with different parameters the further up lines in the traceback show the chain of function calls to reach that occurrence of the error the program calls main in the bottom line of the program (line first file line reference)and then main calls invminus twice we can tell which call caused the errorsince the traceback shows the call to invminus at line if you had any question of the context for any of the nested calls leading to the erroryou could also select previous file line with the mouseand jump to the calling line in the source using error messages
10,505
appendices
10,506
some special windows instructions while the python language changes slowlyoperating systems and setup methods change more rapidly with succeeding versions the attempt here is to keep all such information in one place for the windows operating system it may become out of date at any time last checked this on windows and windows with python versions will use python to mean the current version of pythonwith version number at least make sure you have the latest recommended version installed from read this section before doing any installation in particular note paragraph below with italics in it if the only option is to save itagreeand find it in your download folder and double click to execute it if you have an option to immediately run on downloadyou can choose that you are likely to get security message before running click run pay attentionbefore clicking on install nownote if there are check-boxes at the bottom of window you see make sure both are checkedabout the python launcher and to add python to environment variables the final screen that you reach in the installation links to more advanced references than we will want in this courseso probably skip them for now python now behaves differently if you installed previous version before (like mei could have missed something for someone installing python for the first time feel free for me to watch you while you share your screen in zoom if you install python without putting check mark on add python to environment variablesthen you can go back and fix it this is important for ch run the python installation script again since python is already there it looks different when it starts the first option is modifyclick on that just click next on the second screen on the following screen is where you make changeclick to put checkmark in front of the line sayingadd python to environment variables then click next/continue/finish whatever to just advance to the end you are encouraged to test if python did get added to the environment by starting idle as discussed on the next section starting idle shortcut if you want to start idle without starting filebut later deal with files in the examples folderthen one-step shortcut is to double click on the file idleonwindows cmd in the examples folder if this does not work (in windows)then go back and modify your python installationas discussed in the previous section if you want to do extensive idle work in another folderyou can copy idleonwindows cmd to there and use it file names in the file explorer by default windows does not display file extensions in file explorer windows you may have multiple files with the same base name but different extensions particularly if you want to attach one to an email or homework submissionthis can lead to problems some special windows instructions
10,507
you are strongly suggested to change the viewing default in file explorer to show extensions cgi instructions you can skip this until you are starting on cgi files opening cgi files in idle by convention the server programs that you will be writing end in cgithat is not an extension that is automatically associated with idle for editing if you want to open cgi file (or any other type but pyto edit (and never runfrom inside of idleit is possible to do this directly in many stepsbut it is easier to go indirectlystart py file you have in idle (like localcgiserver py)or if idleonwindows cmd is thereas in my www folderuse it to start idle to open cgi file from inside idleyou select open form the file menu like normallybut then notice the dropdown choice in the lower right of the file open window that probably shows python files py)change this file filter to all files *then all files in the current folder should be listednot grayed outand you can navigate to and choose the one you want saving new cgi file as with opening cgi fileset the format filter at the bottom of the dialog window to all files then enter the full file name with the cgi if you forget and do not change the file filtera pywill be added to your file name then you can rename it in file explorer running cgi scripts if you insist on doing cgi work in different foldercopy both startserver cmd and localcgiserver py as well as all related html and cgi files to that folderand then when you want to test your workstart the local server from there with startserver cmd at this point you can do all the web server based activities in there are number of stepsbe sure you carefully go through the list in the tutorial rememberhtml files calling cgi fileand cgi files used directly are only run in your web browser with url starting with localhost: /and only after you have local server running from the same folder otherwise nothing dynamic happens some special mac instructions while the python language changes slowlyoperating systems and setup methods change more rapidly with succeeding versions the attempt here is to keep all such information in one place for the mac os- operating system it may become out of date at any time will assume version of max osx of at least high sierra ( or laterupgrades are free appendices
10,508
versions will use python to mean the current version of pythonwith version number at least make sure you have the latest recommended version installed from click to execute editing by default in idle you will be working mostly with files ending in py python source files most of the time you will be editing them and running them in idleso the best default behavior when opening file with extension py is to have it open in idle if you can double click on py file in my examplesand idle opens as soon as you have installed python +great you should skip the rest of this section if idle did not openhere is how to change the default behavior in the finder go to file in my examples folder with the py extension and right click or control click on it select get info in the info window that pops upin the drop-down menu for open with:you want to see idle app on the top line (meaning it is already the defaultyou may possibly also see the version listed if you have several presumably you are going through this because you do not see idle app there you may see idle app lower down in the list of options then select it there if you did not see idle app in the drop-down list at allselect other window of apps pops up toward the bottom is check box for "always open withcheck it if you do not see python folder in the listjust below the bottom of the page change recommended applications to all applications now you should see python folder open it and select idle app the info window should become active again be sure that now under open withyou see idle app under the idle app you should see buttonchange all so that you never have to go through all these steps againbe sure to click that button confirmation window will pop up select continue now you can close the info windowand you should be able to open all py files directly in idle for editing by double clicking in the finder then if you should happen to want to directly run python file from the finder windowyou will need to select the file with control-click or right-click and select the latest python launcher for python running graphics (the graphics window likely comes up behind an unneeded console window you can close the console windowand click on the graphics window title bar to bring it to the front cgi instructions opening cgi files in idle by convention the server programs that you will be writing end in cgithat is not an extension that is automatically associated with idle for editing you will want to change the association do it the same way as the instructions above some special mac instructions
10,509
for getting py files to open in idle by defaultexcept choose cgi file in my www folderand go through the same procedure setupmaking cgi scripts executable complication on maclike any unix derived systemis that programs that you run must be explicitly marked executable (on windows it follows from the file extensionlike exe the examples/www folder may not have the cgi files marked executable (nor have several other technical things rightthe example program examples/www/cgifix py is used to give direct unix/mac/linux executability to cgi files for in the finder open your www directory you can open cgifix py in idle and run it note the comment that the file cgiserverscript was created this is used to lauch the local server importantparticularly if you later copy in cgi script from windows machineor if you create any new cgi script in the www directorymake sure it becomes executable (and possibly fix some other technical thingsby launching cgifix py again if you forget thisand the file is not executablenothing happens in the browser when you try to run itand the error message in the server window is very unhelpful it says file not found make sure you make new cgi files executable (with cgifix py)running it extra times does not hurt terminal use (optionalto use the hands-on python tutorialthe information above should be sufficient to get your mac usage going terminals are quite useful in other contextsthere are many things that can be done from such window that cannot be done from the finder or with an app if you would like bit more backgroundread on navigation os and unix (from which os is derivedhave concept of the current directory directory is the older term for folder from when there were not pictures of folders in graphical interface you start in your home directory my login id is anhso my home directory is /users/anh substitute your login id for your machine the slashes separate nested directories the top hard drive directory is /which contains the directory users which contains usershome directorieslike my anh shorthand in terminal for your home directory is the terminal shows system prompt when it is ready for user input the prompt can be set to show many things the end of the prompt is often before that is often some indication of your current directorylike for the home directory if you want to see the full name of the current directory enter the command pwd single commands are executed after you press the enter key you can list the contents of directory with the ls command unix tends to abbreviate words in commands if you use the ls command in your home directoryyou should see desktopdocumentsdownloadslisted to change directoryuse the cd command followed by the directory you would like to change to you can use the full name of the directory starting with /but more commonly you just indicate where to go relative to where you are now desktop is subdirectory of your home directoryso from the home directory you can just enter appendices
10,510
cd desktop here is sequence on my computer after starting terminal (skipping most of the output from lslast loginsat may : : on ttys anh@lucky (anh@lucky ):~pwd /users/anh anh@lucky (anh@lucky ):~ls desktop documents downloads anh@lucky (anh@lucky ):~cd desktop anh@lucky (anh@lucky ):~/desktoppwd /users/anh/desktop anh@lucky (anh@lucky ):~/desktopcd anh@lucky (anh@lucky ):~pwd /users/anh anh@lucky (anh@lucky ):~notice that the last use of the cd command used directory that stands for the parent directorythe directory containing the current directory if you unzipped examples zip from your desktopyou can go to the exaples with cd ~/desktop/examples alter this if you put your examples somewhere elseit is useful to be in the examples folder if you start idle from thereit is easy to open any of the example programs when scripts are directly called by the operating systemthey look for the proper interpreter to read them our scripts are set up to look for python to start regular python program from the current directorylike hello_you pyyou would enter command with python and the file namelike python hello_you py instead of shifting to separate shell as in idlethe output appears right in the terminal window html source markup the section web page basics (page compares html format with other document formats here we concentrate on htmlhypertext markup language use convenient plain text editorsublime text (free download at syntax of html sourcemuch as idle colors python syntax this is an advantage over kompozer unlike hybrid editors such as kompozerthe editor only shows the raw html textnot the way it looks in browser with plain text editor like thisyou have couple extra steps to look at the formatted viewyou need to save the fileand separately load it into browser if you make change to the html sourceand want to see what that changes in the browser viewthen you need to save the source file againand then get the browser to reload the page html source markup
10,511
mac users textedityou can also edit raw html with the included mac app texteditbut with several steps to change the defaults (the initial defaults are to show no html source since textedit does not do syntax coloringan editor like sublime text is likely betteras long as you do not mind doing one extra download if you do want to use textedit to see and edit html source open textedit click on help in the menu bar select textedit help page in the list that pops upselect "work with html documents follow the instructions in the section "always open html files in code-editing mode as beginneri suggest these settings in the last help section"change how html files are saved"in select the ccs style "no cssleave the defaults for document type and encoding in do not select preserve white space nowfor everyonewe get into the first simple examplethe raw html for hello html this file is in the examples sub-folder www hello simple page helloworldit is fine day you are encouraged to open it both in plain text editor like sublime text or mac textedit and in browser the other html files discussed hereare in the same folderand you are encouraged to open them in the same two ways with the html source text coloring in this tutorial the only text that you will see in browser' usual formatted view is what appears as black in the image everything else is markup markup tag names are boldfaceand colored dark blue most of the markup appears inside angle bracketsand most markup has both an opening and closing tagwith affected contents in betweenlike and in line the closing tag has right after the much of the markup is boilerplate am not going to explain it much in particular all the part through the opening tag for the bodyin lines - is standard for our very simple pagesexcept for the bit in blackinside the title markupon line the title text appears in the tab label in your browsernot inside the formatted page that appears in the browser the only parts you actually see on the page are inside the bodyhere the body contents are in lines - you are likely to want to start with heading line uses the markup to create main heading spaced the text in the body in strange wayto illustrate major feature of htmlit reformats if you change the window width that means the browser generally chooses the places to wrap to the next line in particular any amount of white spaceincluding newlines in your raw textare merely treated as place where there could be break to the next lineor it could just display as single space before the next word appendices
10,512
about this book hellothis book will teach you how to make graphical computer games with the pygame framework (also called the pygame libraryin the python programming language pygame makes it easy to create programs with graphics both python and the pygame framework can be downloaded for free from and this book to begin making your own games this book is an intermediate programming book if you are completely new to programmingyou can still try to follow along with the source code examples and figure out how programming works howeverit might be easier to learn how to program in python first --invent your own computer games with python|is book that is available completely for free from howeverif you already know how to program in python (or even some other languagesince python is so easy to pick upand want to start making games beyond just textthen this is the book for you the book starts with short introduction to how the pygame library works and the functions it provides then it provides the complete source code for some actual games and explains how the code worksso you can understand how actual game programs make use of pygame this book features seven different games that are clones of popular games that you've probably already played the games are lot more fun and interactive than the text-based games in --invent with python||but are still fairly short all of the programs are less than lines long this is pretty small when you consider that professional games you download or buy in store can be hundreds of thousands of lines long these games require an entire team of programmers and artists working with each other for months or years to make the website for this book is mentioned in this book can be downloaded for free from this websiteincluding this book itself programming is great creative activityso please share this book as widely as possible the creative commons license that this book is released under gives you the right to copy and duplicate this book as much as you want (as long as you don' charge money for itif you ever have questions about how these programs workfeel free to email me at al@inventwithpython com email questions to the authoral@inventwithpython com
10,513
iii table of contents who is this book fori about this book ii installing python and pygame what you should know before you begin downloading and installing python windows instructions mac os instructions ubuntu and linux instructions starting python installing pygame how to use this book the featured programs downloading graphics and sound files line numbers and spaces text wrapping in this book checking your code online more info links on pygame basics gui vs cli source code for hello world with pygame setting up pygame program game loops and game states pygame event event objects the quit event and pygame quit(function pixel coordinates
10,514
reminder about functionsmethodsconstructor functionsand functions in modules (and the difference between them surface objects and the window colors transparent colors pygame color objects rect objects primitive drawing functions pygame pixelarray objects the pygame display update(function animation frames per second and pygame time clock objects drawing images with pygame image load(and blit( fonts anti-aliasing playing sounds summary memory puzzle how to play memory puzzle nested for loops source code of memory puzzle credits and imports magic numbers are bad sanity checks with assert statements telling if number is even or odd crash early and crash often making the source code look pretty using constant variables instead of strings making sure we have enough icons tuples vs listsimmutable vs mutable email questions to the authoral@inventwithpython com
10,515
one item tuples need trailing comma converting between lists and tuples the global statementand why global variables are evil data structures and lists the --start game|animation the game loop the event handling loop checking which box the mouse cursor is over handling the first clicked box handling mismatched pair of icons handling if the player won drawing the game state to the screen creating the --revealed boxes|data structure creating the board data structurestep get all possible icons step shuffling and truncating the list of all icons step placing the icons on the board splitting list into list of lists different coordinate systems converting from pixel coordinates to box coordinates drawing the iconand syntactic sugar syntactic sugar with getting board space' icon' shape and color drawing the box cover handling the revealing and covering animation drawing the entire board drawing the highlight the --start game|animation revealing and covering the groups of boxes the --game won|animation telling if the player has won
10,516
why bother having main(function why bother with readability summaryand hacking suggestion slide puzzle how to play slide puzzle source code to slide puzzle second versesame as the first setting up the buttons being smart by using stupid code the main game loop clicking on the buttons sliding tiles with the mouse sliding tiles with the keyboard --equal to one of|trick with the in operator wasd and arrow keys actually performing the tile slide idle and terminating pygame programs checking for specific eventand posting events to pygame' event queue creating the board data structure not tracking the blank position making move by updating the board data structure when not to use an assertion getting not-so-random move converting tile coordinates to pixel coordinates converting from pixel coordinates to board coordinates drawing tile the making text appear on the screen drawing the board drawing the border of the board email questions to the authoral@inventwithpython com
10,517
vii drawing the buttons animating the tile slides the copy(surface method creating new puzzle animating the board reset time vs memory tradeoffs nobody cares about few bytes nobody cares about few million nanoseconds summary simulate how to play simulate source code to simulate the usual starting stuff setting up the buttons the main(function some local variables used in this program drawing the board and handling input checking for mouse clicks checking for keyboard presses the two states of the game loop figuring out if the player pressed the right buttons epoch time drawing the board to the screen same old terminate(function reusing the constant variables animating the button flash drawing the buttons animating the background change the game over animation
10,518
converting from pixel coordinates to buttons explicit is better than implicit wormy how to play wormy source code to wormy the grid the setup code the main(function separate rungame(function the event handling loop collision detection detecting collisions with the apple moving the worm the insert(list method drawing the screen drawing --press key|text to the screen the checkforkeypress(function the start screen rotating the start screen text rotations are not perfect deciding where the apple appears game over screens drawing functions don' reuse variable names tetromino how to play tetromino some tetromino nomenclature source code to tetromino the usual setup code email questions to the authoral@inventwithpython com
10,519
ix setting up timing constants for holding down keys more setup code setting up the piece templates splitting --line of code|across multiple lines the main(function the start of new game the game loop the event handling loop pausing the game using movement variables to handle user input checking if slide or rotation is valid finding the bottom moving by holding down the key letting the piece --naturally|fall drawing everything on the screen maketextobjs() shortcut function for making text the same old terminate(function waiting for key press event with the checkforkeypress(function showtextscreen() generic text screen function the checkforquit(function the calculatelevelandfallfreq(function generating pieces with the getnewpiece(function adding pieces to the board data structure creating new board data structure the isonboard(and isvalidposition(functions checking forand removingcomplete lines convert from board coordinates to pixel coordinates drawing box on the board or elsewhere on the screen drawing everything to the screen
10,520
drawing the score and level text drawing piece on the board or elsewhere on the screen drawing the --next|piece summary squirrel eat squirrel how to play squirrel eat squirrel the design of squirrel eat squirrel source code to squirrel eat squirrel the usual setup code describing the data structures the main(function the pygame transform flip(function more detailed game state than usual the usual text creation code cameras the --active area| keeping track of the location of things in the game world starting off with some grass the game loop checking to disable invulnerability moving the enemy squirrels removing the far away grass and squirrel objects when deleting items in listiterate over the list in reverse adding new grass and squirrel objects camera slackand moving the camera view drawing the backgroundgrasssquirrelsand health meter the event handling loop moving the playerand accounting for bounce collision detectioneat or be eaten email questions to the authoral@inventwithpython com
10,521
xi the game over screen winning drawing graphical health meter the same old terminate(function the mathematics of the sine function backwards compatibility with python version the getrandomvelocity(function finding place to add new squirrels and grass creating enemy squirrel data structures flipping the squirrel image creating grass data structures checking if outside the active area summary star pusher how to play star pusher source code to star pusher the initial setup data structures in star pusher the --game state|data structure the --map|data structure the --levels|data structure reading and writing text files text files and binary files writing to files reading from files about the star pusher map file format recursive functions stack overflows preventing stack overflows with base case
10,522
the flood fill algorithm drawing the map checking if the level is finished summary four extra games flippyan --othello|clone source code for flippy ink spilla --flood it|clone source code for ink spill four-in- -rowa --connect four|clone source code for four-in- -row gemgema --bejeweled|clone source code for gemgem summary glossary about the author email questions to the authoral@inventwithpython com
10,523
xiii this page intentionally left blank except for the above text and the above text and the above text and the above text and the above text and the above text and the above text and the above text and the above text traceback (most recent call last)file ""line in blankpage def blankpage()blankpage(runtimeerrormaximum recursion depth exceeded
10,524
email questions to the authoral@inventwithpython com
10,525
installing python and pygame what you should know before you begin it might help if you know bit about python programming (or how to program in another language besides pythonbefore you read through this bookhowever even if you haven' you can still read this book anyway programming isn' nearly as hard as people think it is if you ever run into some troubleyou can read the free book --invent your own computer games with python|online at invent with python wiki at you don' need to know how to use the pygame library before reading this book the next is brief tutorial on all of pygame' major features and functions just in case you haven' read the first book and already installed python and pygame on your computerthe installation instructions are in this if you already have installed both of these then you can skip this downloading and installing python before we can begin programming you'll need to install software called the python interpreter on your computer (you may need to ask an adult for help here the interpreter is program that understands the instructions that you'll write (or rathertype outin the python language without the interpreteryour computer won' be able to run your python programs we'll just refer to --the python interpreter|as --python|from now on the python interpreter software can be downloaded from the official website of the python programming languagedownload and install the python software the installation is little different depending on if your computer' operating system is windowsmac os xor linux os such as ubuntu you can also find videos online of people installing the python software on their computers at windows instructions when you get to --news||--documentation||--download||and so onclick on the download link to go to the
10,526
download pagethen look for the file called --python windows installer (windows binary -does not include source)|and click on its link to download python for windows double-click on the python- msi file that you've just downloaded to start the python installer (if it doesn' starttry right-clicking the file and choosing install once the installer starts upjust keep clicking the next button and just accept the choices in the installer as you go (no need to make any changeswhen the install is finishedclick finish mac os instructions mac os comes with python pre-installed by apple currentlypygame only supports python and not python howeverthe programs in this book work with both python and the python website also has some additional information about using python on mac at ubuntu and linux instructions pygame for linux also only supports python not python if your operating system is ubuntuyou can install python by opening terminal window (from the desktop click on applications accessories terminaland entering --sudo apt-get install python |then pressing enter you will need to enter the root password to install pythonso ask the person who owns the computer to type in this password if you do not know it you also need to install the idle software from the terminaltype in --sudo apt-get install idle|the root password is also needed to install idle (ask the owner of your computer to type in this password for youstarting python we will be using the idle software to type in our programs and run them idle stands for interactive development environment the development environment is software that makes it easy to write python programsjust like word processor software makes it easy to write books if your operating system is windows xpyou should be able to run python by clicking the start buttonthen selecting programspython idle (python guifor windows vista or windows just click the windows button in the lower left cornertype --idle|and select --idle (python gui)|if your operating system is max os xstart idle by opening the finder window and click on applicationsthen click python then click the idle icon email questions to the authoral@inventwithpython com
10,527
if your operating system is ubuntu or linuxstart idle by opening terminal window and then type --idle |and press enter you may also be able to click on applications at the top of the screenand then select programmingthen idle the window that appears when you first run idle is called the interactive shell shell is program that lets you type instructions into the computer the python shell lets you type python instructionsand the shell sends these instructions to the python interpreter to perform installing pygame pygame does not come with python like pythonpygame is available for free you will have to download and install pygamewhich is as easy as downloading and installing the python interpreter in web browsergo to the url link on the left side of the web site this book assumes you have the windows operating systembut pygame works the same for every operating system you need to download the pygame installer for your operating system and the version of python you have installed you do not want to download the --source|for pygamebut rather the pygame --binary|for your operating system for windowsdownload the pygamewin -py msi file (this is pygame for python on windows if you installed different version of python (such as or download the msi file for your version of python the current version of pygame at the time this book was written is if you see newer version on the websitedownload and install the newer pygame for mac os xdownload the zip or dmg file for the version of python you have and run it for linuxopen terminal and run --sudo apt-get install python-pygame|on windowsdouble click on the downloaded file to install pygame to check that pygame is install correctlytype the following into the interactive shellimport pygame
10,528
if nothing appears after you hit the enter keythen you know pygame has successfully been installed if the error importerrorno module named pygame appearsthen try to install pygame again (and make sure you typed import pygame correctlythis has five small programs that demonstrate how to use the different features that pygame provides in the last you will use these features for complete game written in python with pygame video tutorial of how to install pygame is available from this book' website at how to use this book --making games with python pygame|is different from other programming books because it focuses on the complete source code for several game programs instead of teaching you programming concepts and leaving it up to you to figure out how to make programs with those conceptsthis book shows you some programs and then explains how they are put together in generalyou should read these in order there are many concepts that are used over and over in these gamesand they are only explained in detail in the first game they appear in but if there is game you think is interestinggo ahead and jump to that you can always read the previous later if you got ahead of yourself the featured programs each focuses on single game program and explain how different parts of the code work it is very helpful to copy these programs by typing in the code line by line from this book howeveryou can also download the source code file from this book' website in web browsergo to the url file but typing in the code yourself really helps you learn the code better downloading graphics and sound files while you can just type in the code you read out of this bookyou will need to download the graphics and sound files used by the games in this book from sure that these image and sound files are located in the same folder as the py python file otherwise your python program will not be able to find these files line numbers and spaces when entering the source code yourselfdo not type the line numbers that appear at the beginning of each line for exampleif you see this in the bookemail questions to the authoral@inventwithpython com
10,529
number random randint( spam print('hello world!'you do not need to type the -- |on the left sideor the space that immediately follows it just type it like thisnumber random randint( spam print('hello world!'those numbers are only used so that this book can refer to specific lines in the code they are not part of the actual program aside from the line numbersbe sure to enter the code exactly as it appears notice that some of the lines don' begin at the leftmost edge of the pagebut are indented by four or eight or more spaces be sure to put in the correct number of spaces at the start of each line (since each character in idle is the same widthyou can count the number of spaces by counting the number of characters above or below the line you're looking at for example in the code belowyou can see that the second line is indented by four spaces because the four characters (--whil||on the line above are over the indented space the third line is indented by another four spaces (the four characters--if |are above the third line' indented space)while spam if number = print('hello'text wrapping in this book some lines of code are too long to fit on one line on the pages in this bookand the text of the code will wrap around to the next line when you type these lines into the file editorenter the code all on one line without pressing enter you can tell when new line starts by looking at the line numbers on the left side of the code for examplethe code below has only two lines of codeeven though the first line wraps around print('this is the first linexxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxx' print('this is the second linenot the third line '
10,530
checking your code online some of the programs in this book are little long although it is very helpful to learn python by typing out the source code for these programsyou may accidentally make typos that cause your programs to crash it may not be obvious where the typo is you can copy and paste the text of your source code to the online diff tool on the book' website the diff tool will show any differences between the source code in the book and the source code you've typed this is an easy way of finding any typos in your program copying and pasting text is very useful computer skillespecially for computer programming there is video tutorial on copying and pasting at this book' website at the online diff tool is at this web pagetutorial on how to use this tool on the book' website more info links on there is lot that you can learn about programming but you don' need to learn all of it now there are several times in this book where you might like to learn these additional details and explanationsbut if included them in this book then it would add many more pages if this largerheavier book accidentally fell on you the weight of these many additional pages would crush youresulting in death insteadi have included --more info|links in this book that you can follow on this book' website you do not have to read this additional information to understand anything in this bookbut it is there if you are curious these (and otherlinks have been shortened and begin with all of the information from these --more info|links can also be downloaded from even though this book is not dangerously heavyplease do not let it fall on you anyway email questions to the authoral@inventwithpython com
10,531
pygame basics just like how python comes with several modules like randommathor time that provide additional functions for your programsthe pygame framework includes several modules with functions for drawing graphicsplaying soundshandling mouse inputand other things this will cover the basic modules and functions that pygame provides and assumes you already know basic python programming if you have trouble with some of the programming conceptsyou can read through the --invent your own computer games with python|book online at the --invent with python|book also has few covering pygame you can read them online at once you learn more about pygameyou can view the other modules that pygame provides from the online documentation at gui vs cli the python programs that you can write with python' built-in functions only deal with text through the print(and input(functions your program can display text on the screen and let the user type in text from the keyboard this type of program has command line interfaceor cli (which is pronounced like the first part of --climb|and rhymes with --sky||these programs are somewhat limited because they can' display graphicshave colorsor use the mouse these cli programs only get input from the keyboard with the input(function and even then user must press enter before the program can respond to the input this means realtime (that iscontinuing to run code without waiting for the useraction games are impossible to make pygame provides functions for creating programs with graphical user interfaceor gui (pronounced--gooey||instead of text-based cliprograms with graphics-based gui can show window with images and colors source code for hello world with pygame our first program made with pygame is small program that makes window that says --hello world!|appear on the screen open new file editor window by clicking on idle' file menuthen new window type in the following code into idle' file editor and save it as blankpygame py then run the program by pressing or selecting run run module from the menu at the top of the file editor
10,532
rememberdo not type the numbers or the periods at the beginning of each line (that' just for reference in this book import pygamesys from pygame locals import pygame init( displaysurf pygame display set_mode(( ) pygame display set_caption('hello world!' while truemain game loop for event in pygame event get() if event type =quit pygame quit( sys exit( pygame display update(when you run this programa black window like this will appearyayyou've just made the world' most boring video gameit' just blank window with --hello world!|at the top of the window (in what is called the window' title barwhich holds the caption textbut creating window is the first step to making graphical games when you click on the button in the corner of the windowthe program will end and the window will disappear calling the print(function to make text appear in the window won' work because print(is function for cli programs the same goes for input(to get keyboard input from the user pygame uses other functions for input and output which are explained later in this for nowlet' look at each line in our --hello world|program in more detail setting up pygame program the first few lines of code in the hello world program are lines that will begin almost every program you write that uses pygame import pygamesys email questions to the authoral@inventwithpython com
10,533
line is simple import statement that imports the pygame and sys modules so that our program can use the functions in them all of the pygame functions dealing with graphicssoundand other features that pygame provides are in the pygame module note that when you import the pygame module you automatically import all the modules that are in the pygame module as wellsuch as pygame images and pygame mixer music there' no need to import these modules-inside-modules with additional import statements from pygame locals import line is also an import statement howeverinstead of the import modulename formatit uses the from modulename import format normally if you want to call function that is in moduleyou must use the modulename functionname(format after importing the module howeverwith from modulename import you can skip the modulename portion and simply use functionname((just like python' built-in functionsthe reason we use this form of import statement for pygame locals is because pygame locals contains several constant variables that are easy to identify as being in the pygame locals module without pygame locals in front of them for all other modulesyou generally want to use the regular import modulename format (there is more information about why you want to do this at pygame init(line is the pygame init(function callwhich always needs to be called after importing the pygame module and before calling any other pygame function you don' need to know what this function doesyou just need to know that it needs to be called first in order for many pygame functions to work if you ever see an error message like pygame errorfont not initializedcheck to see if you forgot to call pygame init(at the start of your program displaysurf pygame display set_mode(( )line is call to the pygame display set_mode(functionwhich returns the pygame surface object for the window (surface objects are described later in this notice that we pass tuple value of two integers to the function( this tuple tells the set_mode(function how wide and how high to make the window in pixels ( will make window with width of pixels and height of pixels
10,534
remember to pass tuple of two integers to set_mode()not just two integers themselves the correct way to call the function is like thispygame display set_mode(( ) function call like pygame display set_mode( will cause an error that looks like thistypeerrorargument must be -item sequencenot int the pygame surface object (we will just call them surface objects for shortreturned is stored in variable named displaysurf pygame display set_caption('hello world!'line sets the caption text that will appear at the top of the window by calling the pygame display set_caption(function the string value 'hello world!is passed in this function call to make that text appear as the captiongame loops and game states while truemain game loop for event in pygame event get()line is while loop that has condition of simply the value true this means that it never exits due to its condition evaluating to false the only way the program execution will ever exit the loop is if break statement is executed (which moves execution to the first line after the loopor sys exit((which terminates the programif loop like this was inside functiona return statement will also move execution out of the loop (as well as the function toothe games in this book all have these while true loops in them along with comment calling it the --main game loop| game loop (also called main loopis loop where the code does three things handles events updates the game state draws the game state to the screen the game state is simply way of referring to set of values for all the variables in game program in many gamesthe game state includes the values in the variables that tracks the player' health and positionthe health and position of any enemieswhich marks have been made on boardthe scoreor whose turn it is whenever something happens like the player email questions to the authoral@inventwithpython com
10,535
taking damage (which lowers their health value)or an enemy moves somewhereor something happens in the game world we say that the game state has changed if you've ever played game that let you savedthe --save state|is the game state at the point that you've saved it in most gamespausing the game will prevent the game state from changing since the game state is usually updated in response to events (such as mouse clicks or keyboard pressesor the passage of timethe game loop is constantly checking and re-checking many times second for any new events that have happened inside the main loop is code that looks at which events have been created (with pygamethis is done by calling the pygame event get(functionthe main loop also has code that updates the game state based on which events have been created this is usually called event handling pygame event event objects any time the user does one of several actions (they are listed later in this such as pressing keyboard key or moving the mouse on the program' windowa pygame event event object is created by the pygame library to record this --event|(this is type of object called event that exists in the event modulewhich itself is in the pygame module we can find out which events have happened by calling the pygame event get(functionwhich returns list of pygame event event objects (which we will just call event objects for shortthe list of event objects will be for each event that has happened since the last time the pygame event get(function was called (orif pygame event get(has never been calledthe events that have happened since the start of the program
10,536
while truemain game loop for event in pygame event get()line is for loop that will iterate over the list of event objects that was returned by pygame event get(on each iteration through the for loopa variable named event will be assigned the value of the next event object in this list the list of event objects returned from pygame event get(will be in the order that the events happened if the user clicked the mouse and then pressed keyboard keythe event object for the mouse click would be the first item in the list and the event object for the keyboard press would be second if no events have happenedthen pygame event get(will return blank list the quit event and pygame quit(function if event type =quitpygame quit(sys exit(event objects have member variable (also called attributes or propertiesnamed type which tells us what kind of event the object represents pygame has constant variable for each of possible types in the pygame locals modules line checks if the event object' type is equal to the constant quit remember that since we used the from pygame locals import form of the import statementwe only have to type quit instead of pygame locals quit if the event object is quit eventthen the pygame quit(and sys exit(functions are called the pygame quit(function is sort of the opposite of the pygame init(functionit runs code that deactivates the pygame library your programs should always call pygame quit(before they call sys exit(to terminate the program normally it doesn' really matter since python closes it when the program exits anyway but there is bug in idle that causes idle to hang if pygame program terminates before pygame quit(is called since we have no if statements that run code for other types of event objectthere is no eventhandling code for when the user clicks the mousepresses keyboard keysor causes any other type of event objects to be created the user can do things to create these event objects but it doesn' change anything in the program because the program does not have any event-handling code for these types of event objects after the for loop on line is done handling all the event objects that have been returned by pygame event get()the program execution continues to line pygame display update(email questions to the authoral@inventwithpython com
10,537
line calls the pygame display update(functionwhich draws the surface object returned by pygame display set_mode(to the screen (remember we stored this object in the displaysurf variablesince the surface object hasn' changed (for exampleby some of the drawing functions that are explained later in this the same black image is redrawn to the screen each time pygame display update(is called that is the entire program after line is donethe infinite while loop starts again from the beginning this program does nothing besides make black window appear on the screenconstantly check for quit eventand then redraws the unchanged black window to the screen over and over again let' learn how to make interesting things appear on this window instead of just blackness by learning about pixelssurface objectscolor objectsrect objectsand the pygame drawing functions pixel coordinates the window that the --hello world|program creates is just composed of little square dots on your screen called pixels each pixel starts off as black but can be set to different color imagine that instead of surface object that is pixels wide and pixels tallwe just had surface object that was pixels by pixels if that tiny surface was enlarged so that each pixel looks like square in gridand we added numbers for the and axisthen good representation of it could look something like thiswe can refer to specific pixel by using cartesian coordinate system each column of the xaxis and each row of the -axis will have an --address|that is an integer from to so that we can locate any pixel by specifying the and axis integers for examplein the above imagewe can see that the pixels at the xy coordinates ( )( )( )and ( have been painted blackthe pixel at ( has been painted graywhile all the other pixels are painted white xy coordinates are also called points if you've taken math class and learned about cartesian coordinatesyou might notice that the -axis starts at at the top and then increases going downrather than increasing as it goes up this is just how cartesian coordinates work in pygame (and almost every programming language
10,538
the pygame framework often represents cartesian coordinates as tuple of two integerssuch as ( or ( the first integer is the coordinate and the second is the coordinate (cartesian coordinates are covered in more detail in of --invent your own computer games with python|at reminder about functionsmethodsconstructor functionsand functions in modules (and the difference between themfunctions and methods are almost the same thing they can both be called to execute the code in them the difference between function and method is that method will always be attached to an object usually methods change something about that particular object (you can think of the attached object as sort of permanent argument passed to the methodthis is function call of function named foo()foo(this is method call of method also named foo()which is attached to an object stored in variable named duckieduckie foo( call to function inside of module may look like method call to tell the differenceyou need to look at the first name and see if it is the name of module or the name of variable that contains an object you can tell that sys exit(is call to function inside of modulebecause at the top of the program will be an import statement like import sys constructor function is the same thing as normal function callexcept that its return value is new object just by looking at source codea function and constructor function look the same constructor functions (also called simply --constructor|or sometimes --ctor|(--see-tor||for shortare just name given to functions that return new object but usually ctors start with capital letter this is why when you write your own programsyour function names should only begin with lowercase letter for examplepygame rect(and pygame surface(are both constructor functions inside the pygame module that return new rect and surface objects (these objects are described later here' an example of function calla method calland call to function inside moduleimport whammy fizzy(email questions to the authoral@inventwithpython com
10,539
egg wombat(egg bluhbluh(whammy spam(even though these names are all made upyou can tell which is function calla method calland call to function inside method the name whammy refers to modulesince you can see it is being imported on the first line the fizzy name has nothing before it and parentheses after itso you know it is function call wombat(is also function callin this case it is constructor function that returns an object (the capital letter that it starts with isn' guarantee that it' constructor function rather than regular functionbut it is safe bet the object is stored in variable named egg the egg bluhbluh(call is method callwhich you can tell because bluhbluh is attached to variable with an object in it meanwhilewhammy spam(is function callnot method call you can tell it is not method because the name whammy was imported as module earlier surface objects and the window surface objects are objects that represent rectangular image the pixels of the surface object can be changed by calling the pygame drawing functions (described later in this and then displayed on the screen the window bordertitle barand buttons are not part of the display surface object in particularthe surface object returned by pygame display set_mode(is called the display surface anything that is drawn on the display surface object will be displayed on the window when the pygame display update(function is called it is lot faster to draw on surface object (which only exists in the computer' memorythan it is to draw surface object to the computer screen computer memory is much faster to change than pixels on monitor often your program will draw several different things to surface object once you are done drawing everything on the display surface object for this iteration of the game loop (called framejust like still image on paused dvd is calledon surface objectit can be drawn to the screen the computer can draw frames very quicklyand our programs will often run around frames per second (that is fpsthis is called the --frame rate|and is explained later in this drawing on surface objects will be covered in the --primitive drawing functions|and --drawing images|sections later this
10,540
colors there are three primary colors of lightredgreen and blue (redblueand yellow are the primary colors for paints and pigmentsbut the computer monitor uses lightnot paint by combining different amounts of these three colors you can form any other color in pygamewe represent colors with tuples of three integers the first value in the tuple is how much red is in the color an integer value of means there is no red in this colorand value of means there is the maximum amount of red in the color the second value is for green and the third value is for blue these tuples of three integers used to represent color are often called rgb values because you can use any combination of to for each of the three primary colorsthis means pygame can draw , , different colors (that is colorshoweverif try to use number larger than or negative numberyou will get an error that looks like --valueerrorinvalid color argument|for examplewe will create the tuple ( and store it in variable named black with no amount of redgreenor bluethe resulting color is completely black the color black is the absence of any color the tuple ( for maximum amount of redgreenand blue to result in white the color white is the full combination of redgreenand blue the tuple ( represents the maximum amount of red but no amount of green and blueso the resulting color is red similarly( is green and ( is blue you can mix the amount of redgreenand blue to form other colors here are the rgb values for few common colorscolor aqua black blue fuchsia gray green lime maroon navy blue olive purple red silver teal white yellow rgb values ( ( ( ( ( ( ( ( ( email questions to the authoral@inventwithpython com
10,541
transparent colors when you look through glass window that has deep red tintall of the colors behind it have red shade added to them you can mimic this effect by adding fourth to integer value to your color values this value is known as the alpha value it is measure of how opaque (that isnot transparenta color is normally when you draw pixel onto surface objectthe new color completely replaces whatever color was already there but with colors that have an alpha valueyou can instead just add colored tint to the color that is already there for examplethis tuple of three integers is for the color green( but if we add fourth integer for the alpha valuewe can make this half transparent green color( an alpha value of is completely opaque (that isnot transparency at allthe colors ( and ( look exactly the same an alpha value of means the color is completely transparent if you draw any color that has an alpha value of to surface objectit will have no effectbecause this color is completely transparent and invisible in order to draw using transparent colorsyou must create surface object with the convert_alpha(method for examplethe following code creates surface object that transparent colors can be drawn onanothersurface displaysurf convert_alpha(once things have been drawn on the surface object stored in anothersurfacethen anothersurface can be --blitted|(that iscopiedto displaysurf so it will appear on the screen (see the --drawing images with pygame image load(and blit()|section later in this it' important to note that you cannot use transparent colors on surface objects not returned from convert_alpha(callincluding the display surface that was returned from pygame display set_mode(if we were to create color tuple to draw the legendary invisible pink unicornwe would use ( )which ends up looking completely invisible just like any other color that has for its alpha value it isafter allinvisible
10,542
(above is screenshot of drawing of the invisible pink unicorn pygame color objects you need to know how to represent color because pygame' drawing functions need way to know what color you want to draw with tuple of three or four integers is one way another way is as pygame color object you can create color objects by calling the pygame color(constructor function and passing either three or four integers you can store this color object in variables just like you can store tuples in variables try typing the following into the interactive shellimport pygame pygame color( ( mycolor pygame color( mycolor =( true any drawing function in pygame (which we will learn about in bitthat has parameter for color can have either the tuple form or color object form of color passed for it even though they are different data typesa color object is equal to tuple of four integers if they both represent the same color (just like how = will evaluate to truenow that you know how to represent colors (as pygame color object or tuple of three or four integers for redgreenblueand optionally alphaand coordinates (as tuple of two integers for and )let' learn about pygame rect objects so we can start using pygame' drawing functions rect objects pygame has two ways to represent rectangular areas (just like there are two ways to represent colorsthe first is tuple of four integers the coordinate of the top left corner email questions to the authoral@inventwithpython com
10,543
the coordinate of the top left corner the width (in pixelsof the rectangle then height (in pixelsof the rectangle the second way is as pygame rect objectwhich we will call rect objects for short for examplethe code below creates rect object with top left corner at ( that is pixels wide and pixels tallimport pygame spamrect pygame rect( spamrect =( true the handy thing about this is that the rect object automatically calculates the coordinates for other features of the rectangle for exampleif you need to know the coordinate of the right edge of the pygame rect object we stored in the spamrect variableyou can just access the rect object' right attributespamrect right the pygame code for the rect object automatically calculated that if the left edge is at the coordinate and the rectangle is pixels widethen the right edge must be at the coordinate if you reassign the right attributeall the other attributes are automatically recalculatedspam right spam left here' list of all the attributes that pygame rect objects provide (in our examplethe variable where the rect object is stored in variable named myrect)
10,544
attribute name description myrect left the int value of the -coordinate of the left side of the rectangle myrect right the int value of the -coordinate of the right side of the rectangle myrect top the int value of the -coordinate of the top side of the rectangle myrect bottom the int value of the -coordinate of the bottom side myrect centerx the int value of the -coordinate of the center of the rectangle myrect centery the int value of the -coordinate of the center of the rectangle myrect width the int value of the width of the rectangle myrect height the int value of the height of the rectangle myrect size tuple of two ints(widthheightmyrect topleft tuple of two ints(lefttopmyrect topright tuple of two ints(righttopmyrect bottomleft tuple of two ints(leftbottommyrect bottomright tuple of two ints(rightbottommyrect midleft tuple of two ints(leftcenterymyrect midright tuple of two ints(rightcenterymyrect midtop tuple of two ints(centerxtopmyrect midbottom tuple of two ints(centerxbottomprimitive drawing functions pygame provides several different functions for drawing different shapes onto surface object these shapes such as rectanglescirclesellipseslinesor individual pixels are often called drawing primitives open idle' file editor and type in the following programand save it as drawing py import pygamesys from pygame locals import email questions to the authoral@inventwithpython com
10,545
pygame init( set up the window displaysurf pygame display set_mode(( ) pygame display set_caption('drawing' set up the colors black white ( red ( green blue draw on the surface object displaysurf fill(white pygame draw polygon(displaysurfgreen(( )( )( )( )( )) pygame draw line(displaysurfblue( )( ) pygame draw line(displaysurfblue( )( ) pygame draw line(displaysurfblue( )( ) pygame draw circle(displaysurfblue( ) pygame draw ellipse(displaysurfred( ) pygame draw rect(displaysurfred( ) pixobj pygame pixelarray(displaysurf pixobj[ ][ black pixobj[ ][ black pixobj[ ][ black pixobj[ ][ black pixobj[ ][ black del pixobj run the game loop while true for event in pygame event get() if event type =quit pygame quit( sys exit( pygame display update(when this program is runthe following window is displayed until the user closes the window
10,546
notice how we make constant variables for each of the colors doing this makes our code more readablebecause seeing green in the source code is much easier to understand as representing the color green than ( is the drawing functions are named after the shapes they draw the parameters you pass these functions tell them which surface object to draw onwhere to draw the shape (and what size)in what colorand how wide to make the lines you can see how these functions are called in the drawing py programbut here is short description of each functionfill(colorthe fill(method is not function but method of pygame surface objects it will completely fill in the entire surface object with whatever color value you pass as for the color parameter pygame draw polygon(surfacecolorpointlistwidtha polygon is shape made up of only flat sides the surface and color parameters tell the function on what surface to draw the polygonand what color to make it the pointlist parameter is tuple or list of points (that istuple or list of two-integer tuples for xy coordinatesthe polygon is drawn by drawing lines between each point and the point that comes after it in the tuple then line is drawn from the last point to the first point you can also pass list of points instead of tuple of points the width parameter is optional if you leave it outthe polygon that is drawn will be filled injust like our green polygon on the screen is filled in with color if you do pass an integer value for the width parameteronly the outline of the polygon will be drawn the integer represents how many pixels width the polygon' outline will be passing for the width parameter will make skinny polygonwhile passing or or will make thicker polygons if you pass the integer for the width parameterthe polygon will be filled in (just like if you left the width parameter out entirelyall of the pygame draw drawing functions have optional width parameters at the endand they work the same way as pygame draw polygon()' width parameter probably better name for the width parameter would have been thicknesssince that parameter controls how thick the lines you draw are email questions to the authoral@inventwithpython com
10,547
pygame draw line(surfacecolorstart_pointend_pointwidththis function draws line between the start_point and end_point parameters pygame draw lines(surfacecolorclosedpointlistwidththis function draws series of lines from one point to the nextmuch like pygame draw polygon(the only difference is that if you pass false for the closed parameterthere will not be line from the last point in the pointlist parameter to the first point if you pass truethen it will draw line from the last point to the first pygame draw circle(surfacecolorcenter_pointradiuswidththis function draws circle the center of the circle is at the center_point parameter the integer passed for the radius parameter sets the size of the circle the radius of circle is the distance from the center to the edge (the radius of circle is always half of the diameter passing for the radius parameter will draw circle that has radius of pixels pygame draw ellipse(surfacecolorbounding_rectanglewidththis function draws an ellipse (which is like squashed or stretched circlethis function has all the usual parametersbut in order to tell the function how large and where to draw the ellipseyou must specify the bounding rectangle of the ellipse bounding rectangle is the smallest rectangle that can be drawn around shape here' an example of an ellipse and its bounding rectanglethe bounding_rectangle parameter can be pygame rect object or tuple of four integers note that you do not specify the center point for the ellipse like you do for the pygame draw circle(function pygame draw rect(surfacecolorrectangle_tuplewidththis function draws rectangle the rectangle_tuple is either tuple of four integers (for the xy coordinates of the top left cornerand the width and heightor pygame rect object can be passed instead if the rectangle_tuple has the same size for the width and heighta square will be drawn pygame pixelarray objects unfortunatelythere isn' single function you can call that will set single pixel to color (unless you call pygame draw line(with the same start and end pointthe pygame framework needs to run some code behind the scenes before and after drawing to surface object if it had to do this for every single pixel you wanted to setyour program would run much slower (by my quick testingdrawing pixels this way is two or three times slower insteadyou should create pygame pixelarray object (we'll call them pixelarray objects for shortof surface object and then set individual pixels creating pixelarray object of surface object will --lock|the surface object while surface object is lockedthe drawing
10,548
functions can still be called on itbut it cannot have images like png or jpg images drawn on it with the blit(method (the blit(method is explained later in this if you want to see if surface object is lockedthe get_locked(surface method will return true if it is locked and false if it is not the pixelarray object that is returned from pygame pixelarray(can have individual pixels set by accessing them with two indexes for exampleline ' pixobj[ ][ black will set the pixel at coordinate and coordinate to be black (remember that the black variable stores the color tuple ( )to tell pygame that you are finished drawing individual pixelsdelete the pixelarray object with del statement this is what line does deleting the pixelarray object will --unlock|the surface object so that you can once again draw images on it if you forget to delete the pixelarray objectthe next time you try to blit (that isdrawan image to the surface the program will raise an error that says--pygame errorsurfaces must not be locked during blit|the pygame display update(function after you are done calling the drawing functions to make the display surface object look the way you wantyou must call pygame display update(to make the display surface actually appear on the user' monitor the one thing that you must remember is that pygame display update(will only make the display surface (that isthe surface object that was returned from the call to pygame display set_mode()appear on the screen if you want the images on other surface objects to appear on the screenyou must --blit|them (that iscopy themto the display surface object with the blit(method (which is explained next in the --drawing images|sectionanimation now that we know how to get the pygame framework to draw to the screenlet' learn how to make animated pictures game with only stillunmoving images would be fairly dull (sales of my game --look at this rock|have been disappointing animated images are the result of drawing an image on the screenthen split second later drawing slightly different image on the screen imagine the program' window was pixels wide and pixel tallwith all the pixels white except for black pixel at it would look like thisemail questions to the authoral@inventwithpython com
10,549
if you changed the window so that was black and , was whiteit would look like thisto the userit looks like the black pixel has --moved|over to the left if you redrew the window to have the black pixel at it would continue to look like the black pixel is moving leftit may look like the black pixel is movingbut this is just an illusion to the computerit is just showing three different images that each just happen to have one black pixel consider if the three following images were rapidly shown on the screento the userit would look like the cat is moving towards the squirrel but to the computerthey're just bunch of pixels the trick to making believable looking animation is to have your program draw picture to the windowwait fraction of secondand then draw slightly different picture here is an example program demonstrating simple animation type this code into idle' file editor and save it as catanimation py it will also require the image file cat png to be in the same folder as the catanimation py file you can download this image from this code is available at
10,550
import pygamesys from pygame locals import pygame init( fps frames per second setting fpsclock pygame time clock( set up the window displaysurf pygame display set_mode(( ) pygame display set_caption('animation' white ( catimg pygame image load('cat png' catx caty direction 'right while truethe main game loop displaysurf fill(white if direction ='right' catx + if catx = direction 'down elif direction ='down' caty + if caty = direction 'left elif direction ='left' catx - if catx = direction 'up elif direction ='up' caty - if caty = direction 'right displaysurf blit(catimg(catxcaty) for event in pygame event get() if event type =quit pygame quit( sys exit( pygame display update(email questions to the authoral@inventwithpython com
10,551
fpsclock tick(fpslook at that animated cat gothis program will be much more of commercial success than my game--look at this rock different rock|frames per second and pygame time clock objects the frame rate or refresh rate is the number of pictures that the program draws per secondand is measured in fps or frames per second (on computer monitorsthe common name for fps is hertz many monitors have frame rate of hertzor frames per second low frame rate in video games can make the game look choppy or jumpy if the program has too much code to run to draw to the screen frequently enoughthen the fps goes down but the games in this book are simple enough that this won' be issue even on old computers pygame time clock object can help us make sure our program runs at certain maximum fps this clock object will ensure that our game programs don' run too fast by putting in small pauses on each iteration of the game loop if we didn' have these pausesour game program would run as fast as the computer could run it this is often too fast for the playerand as computers get faster they would run the game faster too call to the tick(method of clock object in the game loop can make sure the game runs at the same speed no matter how fast of computer it runs on the clock object is created on line of the catanimation py program fpsclock pygame time clock(the clock object' tick(method should be called at the very end of the game loopafter the call to pygame display update(the length of the pause is calculated based on how long it has been since the previous call to tick()which would have taken place at the end of the previous iteration of the game loop (the first time the tick(method is calledit doesn' pause at all in the animation programis it run on line as the last instruction in the game loop all you need to know is that you should call the tick(method once per iteration through the game loop at the end of the loop usually this is right after the call to pygame display update( fpsclock tick(fpstry modifying the fps constant variable to run the same program at different frame rates setting it to lower value would make the program run slower setting it to higher value would make the program run faster
10,552
drawing images with pygame image load(and blit(the drawing functions are fine if you want to draw simple shapes on the screenbut many games have images (also called spritespygame is able to load images onto surface objects from pngjpggifand bmp image files the differences between these image file formats is described at the image of the cat was stored in file named cat png to load this file' imagethe string 'cat pngis passed to the pygame image load(function the pygame image load(function call will return surface object that has the image drawn on it this surface object will be separate surface object from the display surface objectso we must blit (that iscopythe image' surface object to the display surface object blitting is drawing the contents of one surface onto another it is done with the blit(surface object method if you get an error message like --pygame errorcouldn' open cat png|when calling pygame image load()then make sure the cat png file is in the same folder as the catanimation py file before you run the program displaysurf blit(catimg(catxcaty)line of the animation program uses the blit(method to copy catimg to displaysurf there are two parameters for blit(the first is the source surface objectwhich is what will be copied onto the displaysurf surface object the second parameter is two-integer tuple for the and values of the topleft corner where the image should be blitted to if catx and caty were set to and and the width of catimg was and the height was this blit(call would copy this image onto displaysurf so that the top left corner of the catimg was at the xy coordinate ( and the bottom right corner' xy coordinate was at ( note that you cannot blit to surface that is currently --locked|(such as when pixelarray object has been made from it and not yet been deleted the rest of the game loop is just changing the catxcatyand direction variables so that the cat moves around the window there is also call to pygame event get(to handle the quit event fonts if you want to draw text to the screenyou could write several calls to pygame draw line(to draw out the lines of each letter this would be headache to type out all those email questions to the authoral@inventwithpython com
10,553
pygame draw line(calls and figure out all the xy coordinatesand probably wouldn' look very good the above message would take forty one calls to the pygame draw line(function to make insteadpygame provides some much simpler functions for fonts and creating text here is small hello world program using pygame' font functions type it into idle' file editor and save it as fonttext py import pygamesys from pygame locals import pygame init( displaysurf pygame display set_mode(( ) pygame display set_caption('hello world!' white ( green ( blue ( fontobj pygame font font('freesansbold ttf' textsurfaceobj fontobj render('hello world!'truegreenblue textrectobj textsurfaceobj get_rect( textrectobj center ( while truemain game loop displaysurf fill(white displaysurf blit(textsurfaceobjtextrectobj for event in pygame event get() if event type =quit pygame quit( sys exit( pygame display update(there are six steps to making text appear on the screen create pygame font font object (like on line create surface object with the text drawn on it by calling the font object' render(method (line create rect object from the surface object by calling the surface object' get_rect(method (line this rect object will have the width and height correctly set for the text that was renderedbut the top and left attributes will be
10,554
set the position of the rect object by changing one of its attributes on line we set the center of the rect object to be at blit the surface object with the text onto the surface object returned by pygame display set_mode((line call pygame display update(to make the display surface appear on the screen (line the parameters to the pygame font font(constructor function is string of the font file to useand an integer of the size of the font (in pointslike how word processors measure font sizeon line we pass 'freesansbold ttf(this is font that comes with pygameand the integer (for -point sized fontsee the parameters to the render(method call are string of the text to rendera boolean value to specify if we want anti-aliasing (explained later in this the color of the textand the color of the background if you want transparent backgroundthen simply leave off the background color parameter in the method call anti-aliasing anti-aliasing is graphics technique for making text and shapes look less blocky by adding little bit of blur to their edges it takes little more computation time to draw with anti-aliasingso although the graphics may look betteryour program may run slower (but only just littleif you zoom in on an aliased line and an anti-aliased linethey look like thisto make pygame' text use anti-aliasingjust pass true for the second parameter of the render(method the pygame draw aaline(and pygame draw aalines(functions have the same parameters as pygame draw line(and email questions to the authoral@inventwithpython com
10,555
pygame draw lines()except they will draw anti-aliased (smoothlines instead of aliased (blockylines playing sounds playing sounds that are stored in sound files is even simpler than displaying images from image files firstyou must create pygame mixer sound object (which we will call sound objects for shortby calling the pygame mixer sound(constructor function it takes one string parameterwhich is the filename of the sound file pygame can load wavmp or ogg files the difference between these audio file formats is explained at to play this soundcall the sound object' play(method if you want to immediately stop the sound object from playing call the stop(method the stop(method has no arguments here is some sample codesoundobj pygame mixer sound('beeps wav'soundobj play(import time time sleep( wait and let the sound play for second soundobj stop(you can download the beeps wav file from the program execution continues immediately after play(is calledit does not wait for the sound to finish playing before moving on to the next line of code the sound objects are good for sound effects to play when the player takes damageslashes swordor collects coin but your games might also be better if they had background music playing regardless of what was going on in the game pygame can only load one music file to play in the background at time to load background music filecall the pygame mixer music load(function and pass it string argument of the sound file to load this file can be wavmp or midi format to begin playing the loaded sound file as the background musiccall the pygame mixer music play(- function the - argument makes the background music forever loop when it reaches the end of the sound file if you set it to an integer or largerthen the music will only loop that number of times instead of looping forever the means to start playing the sound file from the beginning if you pass larger integer or floatthe music will begin playing that many seconds into the sound file for exampleif you pass for the second parameterthe sound file with begin playing at the point seconds in from the beginning
10,556
to stop playing the background music immediatelycall the pygame mixer music stop(function this function has no arguments here is some example code of the sound methods and functionsloading and playing sound effectsoundobj pygame mixer sound('beepingsound wav'soundobj play(loading and playing background musicpygame mixer music load(backgroundmusic mp 'pygame mixer music play(- some more of your code goes here pygame mixer music stop(summary this covers the basics of making graphical games with the pygame framework of coursejust reading about these functions probably isn' enough to help you learn how to make games using these functions the rest of the in this book each focus on the source code for smallcomplete game this will give you an idea of what complete game programs --look like||so you can then get some ideas for how to code your own game programs unlike the --invent your own computer games with python|bookthis book assumes that you know the basics of python programming if you have trouble remembering how variablesfunctionsloopsif-else statementsand conditions workyou can probably figure it out just by seeing what' in the code and how the program behaves but if you are still stuckyou can read the --invent with python|book (it' for people who are completely new to programmingfor free online at email questions to the authoral@inventwithpython com
10,557
memory puzzle how to play memory puzzle in the memory puzzle gameseveral icons are covered up by white boxes there are two of each icon the player can click on two boxes to see what icon is behind them if the icons matchthen those boxes remain uncovered the player wins when all the boxes on the board are uncovered to give the player hintthe boxes are quickly uncovered once at the beginning of the game nested for loops one concept that you will see in memory puzzle (and most of the games in this bookis the use of for loop inside of another for loop these are called nested for loops nested for loops are handy for going through every possible combination of two lists type the following into the interactive shellfor in [ ]for in [' '' '' ']print(xy
10,558
there are several times in the memory puzzle code that we need to iterate through every possible and coordinate on the board we'll use nested for loops to make sure that we get every combination note that the inner for loop (the for loop inside the other for loopwill go through all of its iterations before going to the next iteration of the outer for loop if we reverse the order of the for loopsthe same values will be printed but they will be printed in different order type the following code into the interactive shelland compare the order it prints values to the order in the previous nested for loop examplefor in [' '' '' ']for in [ ]print(xy source code of memory puzzle this source code can be downloaded from go ahead and first type in the entire program into idle' file editorsave it as memorypuzzle pyand run it if you get any error messageslook at the line number that is mentioned in the error email questions to the authoral@inventwithpython com
10,559
message and check your code for any typos you can also copy and paste your code into the web form at code in the book you'll probably pick up few ideas about how the program works just by typing it in once and when you're done typing it inyou can then play the game for yourself memory puzzle by al sweigart al@inventwithpython com released under "simplified bsdlicense import randompygamesys from pygame locals import fps frames per secondthe general speed of the program windowwidth size of window' width in pixels windowheight size of windowsheight in pixels revealspeed speed boxessliding reveals and covers boxsize size of box height width in pixels gapsize size of gap between boxes in pixels boardwidth number of columns of icons boardheight number of rows of icons assert (boardwidth boardheight = 'board needs to have an even number of boxes for pairs of matches xmargin int((windowwidth (boardwidth (boxsize gapsize)) ymargin int((windowheight (boardheight (boxsize gapsize)) gray ( navyblue white ( red ( green blue yellow ( orange ( purple ( cyan bgcolor navyblue lightbgcolor gray boxcolor white highlightcolor blue donut 'donut
10,560
square 'square diamond 'diamond lines 'lines oval 'oval allcolors (redgreenblueyelloworangepurplecyan allshapes (donutsquarediamondlinesoval assert len(allcolorslen(allshapes >boardwidth boardheight"board is too big for the number of shapes/colors defined def main() global fpsclockdisplaysurf pygame init( fpsclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) mousex used to store coordinate of mouse event mousey used to store coordinate of mouse event pygame display set_caption('memory game' mainboard getrandomizedboard( revealedboxes generaterevealedboxesdata(false firstselection none stores the (xyof the first box clicked displaysurf fill(bgcolor startgameanimation(mainboard while truemain game loop mouseclicked false displaysurf fill(bgcolordrawing the window drawboard(mainboardrevealedboxes for event in pygame event get()event handling loop if event type =quit or (event type =keyup and event key =k_escape) pygame quit( sys exit( elif event type =mousemotion mousexmousey event pos elif event type =mousebuttonup mousexmousey event pos mouseclicked true boxxboxy getboxatpixel(mousexmouseyemail questions to the authoral@inventwithpython com
10,561
if boxx !none and boxy !none the mouse is currently over box if not revealedboxes[boxx][boxy] drawhighlightbox(boxxboxy if not revealedboxes[boxx][boxyand mouseclicked revealboxesanimation(mainboard[(boxxboxy)] revealedboxes[boxx][boxytrue set the box as "revealed if firstselection =nonethe current box was the first box clicked firstselection (boxxboxy elsethe current box was the second box clicked check if there is match between the two icons icon shapeicon color getshapeandcolor(mainboardfirstselection[ ]firstselection[ ] icon shapeicon color getshapeandcolor(mainboardboxxboxy if icon shape !icon shape or icon color !icon color icons don' match re-cover up both selections pygame time wait( milliseconds sec coverboxesanimation(mainboard[(firstselection[ ]firstselection[ ])(boxxboxy)] revealedboxes[firstselection[ ]][firstselection [ ]false revealedboxes[boxx][boxyfalse elif haswon(revealedboxes)check if all pairs found gamewonanimation(mainboard pygame time wait( reset the board mainboard getrandomizedboard( revealedboxes generaterevealedboxesdata(false show the fully unrevealed board for second drawboard(mainboardrevealedboxes pygame display update( pygame time wait( replay the start game animation startgameanimation(mainboard firstselection none reset firstselection variable redraw the screen and wait clock tick pygame display update(
10,562
fpsclock tick(fps def generaterevealedboxesdata(val) revealedboxes [ for in range(boardwidth) revealedboxes append([valboardheight return revealedboxes def getrandomizedboard() get list of every possible shape in every possible color icons [ for color in allcolors for shape in allshapes icons append(shapecolor random shuffle(iconsrandomize the order of the icons list numiconsused int(boardwidth boardheight calculate how many icons are needed icons icons[:numiconsused make two of each random shuffle(icons create the board data structurewith randomly placed icons board [ for in range(boardwidth) column [ for in range(boardheight) column append(icons[ ] del icons[ remove the icons as we assign them board append(column return board def splitintogroupsof(groupsizethelist) splits list into list of listswhere the inner lists have at most groupsize number of items result [ for in range( len(thelist)groupsize) result append(thelist[ : groupsize] return result def lefttopcoordsofbox(boxxboxy) convert board coordinates to pixel coordinates left boxx (boxsize gapsizexmargin email questions to the authoral@inventwithpython com
10,563
top boxy (boxsize gapsizeymargin return (lefttop def getboxatpixel(xy) for boxx in range(boardwidth) for boxy in range(boardheight) lefttop lefttopcoordsofbox(boxxboxy boxrect pygame rect(lefttopboxsizeboxsize if boxrect collidepoint(xy) return (boxxboxy return (nonenone def drawicon(shapecolorboxxboxy) quarter int(boxsize syntactic sugar half int(boxsize syntactic sugar lefttop lefttopcoordsofbox(boxxboxyget pixel coords from board coords draw the shapes if shape =donut pygame draw circle(displaysurfcolor(left halftop half)half pygame draw circle(displaysurfbgcolor(left halftop half)quarter elif shape =square pygame draw rect(displaysurfcolor(left quartertop quarterboxsize halfboxsize half) elif shape =diamond pygame draw polygon(displaysurfcolor((left halftop)(left boxsize top half)(left halftop boxsize )(lefttop half)) elif shape =lines for in range( boxsize ) pygame draw line(displaysurfcolor(lefttop )(left itop) pygame draw line(displaysurfcolor(left itop boxsize )(left boxsize top ) elif shape =oval pygame draw ellipse(displaysurfcolor(lefttop quarterboxsizehalf) def getshapeandcolor(boardboxxboxy) shape value for xy spot is stored in board[ ][ ][
10,564
color value for xy spot is stored in board[ ][ ][ return board[boxx][boxy][ ]board[boxx][boxy][ def drawboxcovers(boardboxescoverage) draws boxes being covered/revealed "boxesis list of two-item listswhich have the spot of the box for box in boxes lefttop lefttopcoordsofbox(box[ ]box[ ] pygame draw rect(displaysurfbgcolor(lefttopboxsizeboxsize) shapecolor getshapeandcolor(boardbox[ ]box[ ] drawicon(shapecolorbox[ ]box[ ] if coverage only draw the cover if there is an coverage pygame draw rect(displaysurfboxcolor(lefttopcoverageboxsize) pygame display update( fpsclock tick(fps def revealboxesanimation(boardboxestoreveal) do the "box revealanimation for coverage in range(boxsize(-revealspeed revealspeed) drawboxcovers(boardboxestorevealcoverage def coverboxesanimation(boardboxestocover) do the "box coveranimation for coverage in range( boxsize revealspeedrevealspeed) drawboxcovers(boardboxestocovercoverage def drawboard(boardrevealed) draws all of the boxes in their covered or revealed state for boxx in range(boardwidth) for boxy in range(boardheight) lefttop lefttopcoordsofbox(boxxboxy if not revealed[boxx][boxy] draw covered box pygame draw rect(displaysurfboxcolor(lefttopboxsizeboxsize) else draw the (revealedicon shapecolor getshapeandcolor(boardboxxboxy drawicon(shapecolorboxxboxy email questions to the authoral@inventwithpython com
10,565
def drawhighlightbox(boxxboxy) lefttop lefttopcoordsofbox(boxxboxy pygame draw rect(displaysurfhighlightcolor(left top boxsize boxsize ) def startgameanimation(board) randomly reveal the boxes at time coveredboxes generaterevealedboxesdata(false boxes [ for in range(boardwidth) for in range(boardheight) boxes append(xy random shuffle(boxes boxgroups splitintogroupsof( boxes drawboard(boardcoveredboxes for boxgroup in boxgroups revealboxesanimation(boardboxgroup coverboxesanimation(boardboxgroup def gamewonanimation(board) flash the background color when the player has won coveredboxes generaterevealedboxesdata(true color lightbgcolor color bgcolor for in range( ) color color color color swap colors displaysurf fill(color drawboard(boardcoveredboxes pygame display update( pygame time wait( def haswon(revealedboxes) returns true if all the boxes have been revealedotherwise false for in revealedboxes if false in return false return false if any boxes are covered return true if __name__ ='__main__'
10,566
main(credits and imports memory puzzle by al sweigart al@inventwithpython com released under "simplified bsdlicense import randompygamesys from pygame locals import at the top of the program are comments about what the game iswho made itand where the user could find more information there' also note that the source code is freely copyable under --simplified bsd|license the simplified bsd license is more appropriate for software than the creative common license (which this book is released under)but they basically mean the same thingpeople are free to copy and share this game more info about licenses can be found at this program makes use of many functions in other modulesso it imports those modules on line line is also an import statement in the from (module nameimport formatwhich means you do not have to type the module name in front of it there are no functions in the pygame locals modulebut there are several constant variables in it that we want to use such as mousemotionkeyupor quit using this style of import statementwe only have to type mousemotion rather than pygame locals mousemotion magic numbers are bad fps frames per secondthe general speed of the program windowwidth size of window' width in pixels windowheight size of windowsheight in pixels revealspeed speed boxessliding reveals and covers boxsize size of box height width in pixels gapsize size of gap between boxes in pixels the game programs in this book use lot of constant variables you might not realize why they're so handy for exampleinstead of using the boxsize variable in our code we could just type the integer directly in the code but there are two reasons to use constant variables firstif we ever wanted to change the size of each box laterwe would have to go through the entire program and find and replace each time we typed by just using the boxsize constantwe only have to change line and the rest of the program is already up to date this is email questions to the authoral@inventwithpython com
10,567
much betterespecially since we might use the integer value for something else besides the size of the white boxesand changing that accidentally would cause bugs in our program secondit makes the code more readable go down to the next section and look at line this sets up calculation for the xmargin constantwhich is how many pixels are on the side of the entire board it is complicated looking expressionbut you can carefully piece out what it means line looks like thisxmargin int((windowwidth (boardwidth (boxsize gapsize)) but if line didn' use constant variablesit would look like thisxmargin int(( ( ( )) now it becomes impossible to remember what exactly the programmer intended to mean these unexplained numbers in the source code are often called magic numbers whenever you find yourself entering magic numbersyou should consider replacing them with constant variable instead to the python interpreterboth of the previous lines are the exact same but to human programmer who is reading the source code and trying to understand how it worksthe second version of line doesn' make much sense at allconstants really help the readability of source code of courseyou can go too far replacing numbers with constant variables look at the following codezero one two twoandthreequarters don' write code like that that' just silly sanity checks with assert statements boardwidth number of columns of icons boardheight number of rows of icons assert (boardwidth boardheight = 'board needs to have an even number of boxes for pairs of matches xmargin int((windowwidth (boardwidth (boxsize gapsize)) ymargin int((windowheight (boardheight (boxsize gapsize))
10,568
the assert statement on line ensures that the board width and height we've selected will result in an even number of boxes (since we will have pairs of icons in this gamethere are three parts to an assert statementthe assert keywordan expression whichif falseresults in crashing the program the third part (after the comma after the expressionis string that appears if the program crashes because of the assertion the assert statement with an expression basically says--the programmer asserts that this expression must be trueotherwise crash the program |this is good way of adding sanity check to your program to make sure that if the execution ever passes an assertion we can at least know that that code is working as expected telling if number is even or odd if the product of the board width and height is divided by two and has remainder of (the modulus operator evaluates what the remainder isthen the number is even even numbers divided by two will always have remainder of zero odd numbers divided by two will always have remainder of one this is good trick to remember if you need your code to tell if number is even or oddiseven somenumber = isodd somenumber ! in the above caseif the integer in somenumber was eventhen iseven will be true if it was oddthen isodd will be true crash early and crash oftenhaving your program crash is bad thing it happens when your program has some mistake in the code and cannot continue but there are some cases where crashing program early can avoid worse bugs later if the values we chose for boardwidth and boardheight that we chose on line and result in board with an odd number of boxes (such as if the width were and the height were )then there would always be one left over icon that would not have pair to be matched with this would cause bug later on in the programand it could take lot of debugging work to figure out that the real source of the bug is at the very beginning of the program in factjust for funtry commenting out the assertion so it doesn' runand then setting the boardwidth and boardheight constants both to odd numbers when you run the programit will immediately show an error happening on line in memorypuzzle pywhich is in getrandomizedboard(functiontraceback (most recent call last)email questions to the authoral@inventwithpython com
10,569
file " :\book svn\src\memorypuzzle py"line in main(file " :\book svn\src\memorypuzzle py"line in main mainboard getrandomizedboard(file " :\book svn\src\memorypuzzle py"line in getrandomizedboard columns append(icons[ ]indexerrorlist index out of range we could spend lot of time looking at getrandomizedboard(trying to figure out what' wrong with it before realizing that getrandomizedboard(is perfectly finethe real source of the bug was on line and where we set the boardwidth and boardheight constants the assertion makes sure that this never happens if our code is going to crashwe want it to crash as soon as it detects something is terribly wrongbecause otherwise the bug may not become apparent until much later in the program crash earlyyou want to add assert statements whenever there is some condition in your program that must alwaysalwaysalways be true crash oftenyou don' have to go overboard and put assert statements everywherebut crashing often with asserts goes long way in detecting the true source of bug crash early and crash often(in your code that is notsaywhen riding pony making the source code look pretty gray ( navyblue white ( red ( green blue yellow ( orange ( purple ( cyan bgcolor navyblue lightbgcolor gray boxcolor white highlightcolor blue remember that colors in pygame are represented by tuple of three integers from to these three integers represent the amount of redgreenand blue in the color which is why these
10,570
tuples are called rgb values notice the spacing of the tuples on lines to are such that the rgand integers line up in python the indentation (that isthe space at the beginning of the lineis needs to be exactbut the spacing in the rest of the line is not so strict by spacing the integers in the tuple outwe can clearly see how the rgb values compare to each other (more info on spacing and indentation is as it is nice thing to make your code more readable this waybut don' bother spending too much time doing it code doesn' have to be pretty to work at certain pointyou'll just be spending more time typing spaces than you would have saved by having readable tuple values using constant variables instead of strings donut 'donut square 'square diamond 'diamond lines 'lines oval 'ovalthe program also sets up constant variables for some strings these constants will be used in the data structure for the boardtracking which spaces on the board have which icons using constant variable instead of the string value is good idea look at the following codewhich comes from line if shape =donutthe shape variable will be set to one of the strings 'donut''square''diamond''lines'or 'ovaland then compared to the donut constant if we made typo when writing line for examplesomething like thisif shape =dunotthen python would crashgiving an error message saying that there is no variable named dunot this is good since the program has crashed on line when we check that line it will be easy to see that the bug was caused by typo howeverif we were using strings instead of constant variables and made the same typoline would look like thisif shape ='dunot'this is perfectly acceptable python codeso it won' crash at first when you run it howeverthis will lead to weird bugs later on in our program because the code does not immediately crash where the problem is causedit can be much harder to find it email questions to the authoral@inventwithpython com
10,571
making sure we have enough icons allcolors (redgreenblueyelloworangepurplecyan allshapes (donutsquarediamondlinesoval assert len(allcolorslen(allshapes >boardwidth boardheight"board is too big for the number of shapes/colors defined in order for our game program to be able to create icons of every possible color and shape combinationwe need to make tuple that holds all of these values there is also another assertion on line to make sure that there are enough color/shape combinations for the size of the board we have if there isn'tthen the program will crash on line and we will know that we either have to add more colors and shapesor make the board width and height smaller with colors and shapeswe can make (that is different icons and because we'll have pair of each iconthat means we can have board with up to (that is or spaces tuples vs listsimmutable vs mutable you might have noticed that the allcolors and allshapes variables are tuples instead of lists when do we want to use tuples and when do we want to use listsand what' the difference between them anywaytuples and lists are the same in every way except twotuples use parentheses instead of square bracketsand the items in tuples cannot be modified (but the items in lists can be modifiedwe often call lists mutable (meaning they can be changedand tuples immutable (meaning they cannot be changedfor an example of trying to change values in lists and tupleslook at the following codelistval [ tupleval ( listval[ 'hello!listval [ 'hello!' tupleval[ 'hello!traceback (most recent call last)file ""line in typeerror'tupleobject does not support item assignment tupleval ( tupleval[ notice that when we try to change the item at index in the tuplepython gives us an error message saying that tuple objects do not support --item assignment|
10,572
there is silly benefit and an important benefit to tuple' immutability the silly benefit is that code that uses tuples is slightly faster than code that uses lists (python is able to make some optimizations knowing that the values in tuple will never change but having your code run few nanoseconds faster is not important the important benefit to using tuples is similar to the benefit of using constant variablesit' sign that the value in the tuple will never changeso anyone reading the code later will be able to say-- can expect that this tuple will always be the same otherwise the programmer would have used list |this also lets future programmer reading your code say--if see list valuei know that it could be modified at some point in this program otherwisethe programmer who wrote this code would have used tuple |you can still assign new tuple value to variabletupleval ( tupleval ( the reason this code works is because the code isn' changing the ( tuple on the second line it is assigning an entirely new tuple ( to the tuplevaland overwriting the old tuple value you cannot howeveruse the square brackets to modify an item in the tuple strings are also an immutable data type you can use the square brackets to read single character in stringbut you cannot change single character in stringstrval 'hellostrval[ 'estrval[ 'xtraceback (most recent call last)file ""line in typeerror'strobject does not support item assignment one item tuples need trailing comma alsoone minor details about tuplesif you ever need to write code about tuple that has one value in itthen it needs to have trailing comma in itsuch as thisonevaluetuple ( email questions to the authoral@inventwithpython com
10,573
if you forget this comma (and it is very easy to forget)then python won' be able to tell the difference between this and set of parentheses that just change the order of operations for examplelook at the following two lines of codevariablea ( variableb ( the value that is stored in variablea is just the integer howeverthe expression for variableb' assignment statement is the single-item tuple value ( blank tuple values do not need comma in themthey can just be set of parentheses by themselves(converting between lists and tuples you can convert between list and tuple values just like you can convert between string and integer values just pass tuple value to the list(function and it will return list form of that tuple value orpass list value to the tuple(function and it will return tuple form of that list value try typing the following into the interactive shellspam ( spam list(spamspam [ spam tuple(spamspam ( the global statementand why global variables are evil def main() global fpsclockdisplaysurf pygame init( fpsclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) mousex used to store coordinate of mouse event mousey used to store coordinate of mouse event pygame display set_caption('memory game'this is the start of the main(functionwhich is where (oddly enoughthe main part of the game code is the functions called in the main(function will be explained later in this line is global statement the global statement is the global keyword followed by comma-delimited list of variable names these variable names are then marked as global
10,574
variables inside the main(functionthose names are not for local variables that might just happen to have the same name as global variables they are the global variables any values assigned to them in the main(function will persist outside the main(function we are marking the fpsclock and displaysurf variables as global because they are used in several other functions in the program (more info is at there are four simple rules to determine if variable is local or global if there is global statement for variable at the beginning of the functionthen the variable is global if the name of variable in function has the same name as global variable and the function never assigns the variable valuethen that variable is the global variable if the name of variable in function has the same name as global variable and the function does assign the variable valuethen that variable is local variable if there isn' global variable with the same name as the variable in the functionthen that variable is obviously local variable you generally want to avoid using global variables inside functions function is supposed to be like mini-program inside your program with specific inputs (the parametersand an output (the return valuebut function that reads and writes to global variables has additional inputs and output since the global variable could have been modified in many places before the function was calledit can be tricky to track down bug involving bad value set in the global variable having function as separate mini-program that doesn' use global variables makes it easier to find bugs in your codesince the parameters of the function are clearly known it also makes changing the code in function easiersince if the new function works with the same parameters and gives the same return valueit will automatically work with the rest of the program just like the old function basicallyusing global variables might make it easier to write your program but they generally make it harder to debug in the games in this bookglobal variables are mostly used for variables that would be global constants that never changebut need the pygame init(function called first since this happens in the main(functionthey are set in the main(function and must be global for other functions to see them but the global variables are used as constants and don' changeso they are less likely to cause confusing bugs if you don' understand thisdon' worry just write your code so that you pass in values to functions rather than have the functions read global variables as general rule email questions to the authoral@inventwithpython com
10,575
data structures and lists mainboard getrandomizedboard(revealedboxes generaterevealedboxesdata(falsethe getrandomizedboard(function returns data structure that represents the state of the board the generaterevealedboxesdata(function returns data structure that represents which boxes are coveredrespectively the return values of these functions are two dimensional ( dlistsor lists of lists list of lists of lists of values would be list another word for two or more dimensional lists is multidimensional list if we have list value stored in variable named spamwe could access value in that list with the square bracketssuch as spam[ to retrieve the third value in the list if the value at spam[ is itself listthen we could use another set of square brackets to retrieve value in that list this would look likefor examplespam[ ][ ]which would retrieve the fifth value in the list that is the third value in spam using the this notation of lists of lists makes it easy to map board to list value since the mainboard variable will store icons in itif we wanted to get the icon on the board at the position ( then we could just use the expression mainboard[ ][ since the icons themselves are stored as two-item tuples with the shape and colorthe complete data structure is list of list of two-item tuples whewhere' an small example say the board looked like thisthe corresponding data structure would bemainboard [[(donutblue)(linesblue)(squareorange)][(squaregreen)(donutblue)(diamondyellow)][(squaregreen)(ovalyellow)(squareorange)][(diamondyellow)(linesblue)(ovalyellow)](if your book is in black and whiteyou can see color version of the above picture at icon at the (xycoordinate on the board
10,576
meanwhilethe --revealed boxes|data structure is also listexcept instead of two-item tuples like the board data structureit has boolean valuestrue if the box at that xy coordinate is revealedand false if it is covered up passing false to the generaterevealedboxesdata(function sets all of the boolean values to false (this function is explained in detail later these two data structures are used to keep track of the state of the game board the "start gameanimation firstselection none stores the (xyof the first box clicked displaysurf fill(bgcolorstartgameanimation(mainboardline sets up variable called firstselection with the value none (none is the value that represents lack of value it is the only value of the data typenonetype more info at track if this was the first icon of the pair that was clicked on or the second icon if firstselection is nonethe click was on the first icon and we store the xy coordinates in the firstselection variable as tuple of two integers (one for the valuethe other for yon the second click the value will be this tuple and not nonewhich is how the program tracks that it is the second icon click line fills the entire surface with the background color this will also paint over anything that used to be on the surfacewhich gives us clean slate to start drawing graphics on if you've played the memory puzzle gameyou'll notice that at the beginning of the gameall of the boxes are quickly covered and uncovered randomly to give the player sneak peek at which icons are under which boxes this all happens in the startgameanimation(functionwhich is explained later in this it' important to give the player this sneak peek (but not long enough of peek to let the player easily memorize the icon locations)because otherwise they would have no clue where any icons are blindly clicking on the icons isn' as much fun as having little hint to go on the game loop while truemain game loop mouseclicked false displaysurf fill(bgcolordrawing the window drawboard(mainboardrevealedboxesemail questions to the authoral@inventwithpython com
10,577
the game loop is an infinite loop that starts on line that keeps iterating for as long as the game is in progress remember that the game loop handles eventsupdates the game stateand draws the game state to the screen the game state for the memory puzzle program is stored in the following variablesmainboard revealedboxes firstselection mouseclicked mousex mousey on each iteration of the game loop in the memory puzzle programthe mouseclicked variable stores boolean value that is true if the player has clicked the mouse during this iteration through the game loop (this is part of keeping track of the game state on line the surface is painted over with the background color to erase anything that was previously drawn on it the program then calls drawboard(to draw the current state of the board based on the board and --revealed boxes|data structures that we pass it (these lines of code are part of drawing and updating the screen remember that our drawing functions only draw on the in-memory display surface object this surface object will not actually appear on the screen until we call pygame display update()which is done at the end of the game loop on line the event handling loop k_escape) for event in pygame event get()event handling loop if event type =quit or (event type =keyup and event key =pygame quit(sys exit(elif event type =mousemotionmousexmousey event pos elif event type =mousebuttonupmousexmousey event pos mouseclicked true the for loop on line executes code for every event that has happened since the last iteration of the game loop this loop is called the event handling loop (which is different from the game loopalthough the event handling loop is inside of the game loopand iterates over the list of pygame event objects returned by the pygame event get(call
10,578
if the event object was either quit event or keyup event for the esc keythen the program should terminate otherwisein the event of mousemotion event (that isthe mouse cursor has movedor mousebuttonup event (that isa mouse button was pressed earlier and now the button was let up)the position of the mouse cursor should be stored in the mousex and mousey variables if this was mousebuttonup eventmouseclicked should also be set to true once we have handled all of the eventsthe values stored in mousexmouseyand mouseclicked will tell us any input that player has given us now we should update the game state and draw the results to the screen checking which box the mouse cursor is over boxxboxy getboxatpixel(mousexmouseyif boxx !none and boxy !nonethe mouse is currently over box if not revealedboxes[boxx][boxy]drawhighlightbox(boxxboxythe getboxatpixel(function will return tuple of two integers the integers represent the xy board coordinates of the box that the mouse coordinates are over how getboxatpixel(does this is explained later all we have to know for now is that if the mousex and mousey coordinates were over boxa tuple of the xy board coordinates are returned by the function and stored in boxx and boxy if the mouse cursor was not over any box (for exampleif it was off to the side of the board or in gap in between boxesthen the tuple (nonenoneis returned by the function and boxx and boxy will both have none stored in them we are only interested in the case where boxx and boxy do not have none in themso the next several lines of code are in the block following the if statement on line that checks for this case if execution has come inside this blockwe know the user has the mouse cursor over box (and maybe has also clicked the mousedepending on the value stored in mouseclickedthe if statement on line checks if the box is covered up or not by reading the value stored in revealedboxes[boxx][boxyif it is falsethen we know the box is covered whenever the mouse is over covered up boxwe want to draw blue highlight around the box to inform the player that they can click on it this highlighting is not done for boxes that are already uncovered the highlight drawing is handled by our drawhighlightbox(functionwhich is explained later if not revealedboxes[boxx][boxyand mouseclickedrevealboxesanimation(mainboard[(boxxboxy)]email questions to the authoral@inventwithpython com
10,579
"revealed revealedboxes[boxx][boxytrue set the box as on line we check if the mouse cursor is not only over covered up box but if the mouse has also been clicked in that casewe want to play the --reveal|animation for that box by calling our revealboxesanimation(function (which isas with all the other functions main(callsexplained later in this you should note that calling this function only draws the animation of the box being uncovered it isn' until line when we set revealedboxes[boxx][boxytrue that the data structure that tracks the game state is updated if you comment out line and then run the programyou'll notice that after clicking on box the reveal animation is playedbut then the box immediately appears covered up again this is because revealedboxes[boxx][boxyis still set to falseso on the next iteration of the game loopthe board is drawn with this box covered up not having line would cause quite an odd bug in our program handling the first clicked box if firstselection =nonethe current box was the first box clicked firstselection (boxxboxy elsethe current box was the second box clicked check if there is match between the two icons icon shapeicon color getshapeandcolor(mainboardfirstselection[ ]firstselection[ ] icon shapeicon color getshapeandcolor(mainboardboxxboxybefore the execution entered the game loopthe firstselection variable was set to none our program will interpret this to mean that no boxes have been clickedso if line ' condition is truethat means this is the first of the two possibly matching boxes that was clicked we want to play the reveal animation for the box and then keep that box uncovered we also set the firstselection variable to tuple of the box coordinates for the box that was clicked if this is the second box the player has clicked onwe want to play the reveal animation for that box but then check if the two icons under the boxes are matching the getshapeandcolor(function (explained laterwill retrieve the shape and color values of the icons (these values will be one of the values in the allcolors and allshapes tuples
10,580
handling mismatched pair of icons if icon shape !icon shape or icon color !icon color icons don' match re-cover up both selections pygame time wait( milliseconds sec coverboxesanimation(mainboard[(firstselection[ ]firstselection[ ])(boxxboxy)] revealedboxes[firstselection[ ]][firstselection [ ]false revealedboxes[boxx][boxyfalse the if statement on line checks if either the shapes or colors of the two icons don' match if this is the casethen we want to pause the game for milliseconds (which is the same as secondby calling pygame time wait( so that the player has chance to see that the two icons don' match then the --cover up|animation plays for both boxes we also want to update the game state to mark these boxes as not revealed (that iscovered uphandling if the player won elif haswon(revealedboxes)check if all pairs found gamewonanimation(mainboardpygame time wait( reset the board mainboard getrandomizedboard(revealedboxes generaterevealedboxesdata(falseshow the fully unrevealed board for second drawboard(mainboardrevealedboxespygame display update(pygame time wait( replay the start game animation startgameanimation(mainboardfirstselection none reset firstselection variable otherwiseif line ' condition was falsethen the two icons must be match the program doesn' really have to do anything else to the boxes at that pointit can just leave both boxes in the revealed state howeverthe program should check if this was the last pair of icons on the board to be matched this is done inside our haswon(functionwhich returns true if the board is in winning state (that isall of the boxes are revealedemail questions to the authoral@inventwithpython com
10,581
if that is the casewe want to play the --game won|animation by calling gamewonanimation()then pause slightly to let the player revel in their victoryand then reset the data structures in mainboard and revealedboxes to start new game line plays the --start game|animation again after thatthe program execution will just loop through the game loop as usualand the player can continue playing until they quit the program no matter if the two boxes were matching or notafter the second box was clicked line will set the firstselection variable back to none so that the next box the player clicks on will be interpreted as the first clicked box of pair of possibly matching icons drawing the game state to the screen redraw the screen and wait clock tick pygame display update(fpsclock tick(fpsat this pointthe game state has been updated depending on the player' inputand the latest game state has been drawn to the displaysurf display surface object we've reached the end of the game loopso we call pygame display update(to draw the displaysurf surface object to the computer screen line set the fps constant to the integer value meaning we want the game to run (at mostat frames per second if we want the program to run fasterwe can increase this number if we want the program to run slowerwe can decrease this number it can even be set to float value like which will run the program at half frame per secondthat isone frame per two seconds in order to run at frames per secondeach frame must be drawn in / th of second this means that pygame display update(and all the code in the game loop must execute in under milliseconds any modern computer can do this easily with plenty of time left over to prevent the program from running too fastwe call the tick(method of the pygame clock object in fpsclock to have to it pause the program for the rest of the milliseconds since this is done at the very end of the game loopit ensures that each iteration of the game loop takes (at least milliseconds if for some reason the pygame display update(call and the code in the game loop takes longer than millisecondsthen the tick(method will not wait at all and immediately return
10,582
've kept saying that the other functions would be explained later in the now that we've gone over the main(function and you have an idea for how the general program workslet' go into the details of all the other functions that are called from main(creating the "revealed boxesdata structure def generaterevealedboxesdata(val) revealedboxes [ for in range(boardwidth) revealedboxes append([valboardheight return revealedboxes the generaterevealedboxesdata(function needs to create list of lists of boolean values the boolean value will just be the one that is passed to the function as the val parameter we start the data structure as an empty list in the revealedboxes variable in order to make the data structure have the revealedboxes[ ][ystructurewe need to make sure that the inner lists represent the vertical columns of the board and not the horizontal rows otherwisethe data structure will have revealedboxes[ ][xstructure the for loop will create the columns and then append them to revealedboxes the columns are created using list replicationso that the column list has as many val values as the boardheight dictates creating the board data structurestep get all possible icons def getrandomizedboard() get list of every possible shape in every possible color icons [ for color in allcolors for shape in allshapes icons append(shapecolorthe board data structure is just list of lists of tupleswhere each tuple has two valuesone for the icon' shape and one for the icon' color but creating this data structure is little complicated we need to be sure to have exactly as many icons for the number of boxes on the board and also be sure there are two and only two icons of each type the first step to do this is to create list with every possible combination of shape and color recall that we have list of each color and shape in allcolors and allshapesso nested for loops on lines and will go through every possible shape for every possible color these are each added to the list in the icons variable on line email questions to the authoral@inventwithpython com
10,583
step shuffling and truncating the list of all icons random shuffle(iconsrandomize the order of the icons list numiconsused int(boardwidth boardheight calculate how many icons are needed icons icons[:numiconsused make two of each random shuffle(iconsbut rememberthere may be more possible combinations than spaces on the board we need to calculate the number of spaces on the board by multiplying boardwidth by boardheight then we divide that number by because we will have pairs of icons on board with spaceswe' only need different iconssince there will be two of each icon this number will be stored in numiconsused line uses list slicing to grab the first numiconsused number of icons in the list (if you've forgotten how list slicing workscheck out on line so it won' always be the same icons each game then this list is replicated by using the operator so that there are two of each of the icons this new doubled up list will overwrite the old list in the icons variable since the first half of this new list is identical to the last halfwe call the shuffle(method again to randomly mix up the order of the icons step placing the icons on the board create the board data structurewith randomly placed icons board [for in range(boardwidth)column [for in range(boardheight)column append(icons[ ]del icons[ remove the icons as we assign them board append(columnreturn board now we need to create list of lists data structure for the board we can do this with nested for loops just like the generaterevealedboxesdata(function did for each column on the boardwe will create list of randomly selected icons as we add icons to the columnon line we will then delete them from the front of the icons list on line this wayas the icons list gets shorter and shortericons[ will have different icon to add to the columns to picture this bettertype the following code into the interactive shell notice how the del statement changes the mylist list mylist ['cat''dog''mouse''lizard'
10,584
del mylist[ mylist ['dog''mouse''lizard'del mylist[ mylist ['mouse''lizard'del mylist[ mylist ['lizard'del mylist[ mylist [because we are deleting the item at the front of the listthe other items shift forward so that the next item in the list becomes the new --first|item this is the same way line works splitting list into list of lists def splitintogroupsof(groupsizethelist) splits list into list of listswhere the inner lists have at most groupsize number of items result [ for in range( len(thelist)groupsize) result append(thelist[ : groupsize] return result the splitintogroupsof(function (which will be called by the startgameanimation(functionsplits list into list of listswhere the inner lists have groupsize number of items in them (the last list could have less if there are less than groupsize items left over the call to range(on line uses the three-parameter form of range((if you are unfamiliar with this formtake look at length of the list is and the groupsize parameter is then range( len(thelist)groupsizeevaluates to range( this will give the variable the values and for the three iterations of the for loop the list slicing on line with thelist[ : groupsizecreates the lists that are added to the result list on each iteration where is and (and groupsize is )this list slicing expression would be thelist[ : ]then thelist[ : on the second iterationand then thelist[ : on the third iteration email questions to the authoral@inventwithpython com
10,585
note that even though the largest index of thelist would be in our examplethelist[ : won' raise an indexerror error even though is larger than it will just create list slice with the remaining items in the list list slicing doesn' destroy or change the original list stored in thelist it just copies portion of it to evaluate to new list value this new list value is the list that is appended to the list in the result variable on line so when we return result at the end of this functionwe are returning list of lists different coordinate systems def lefttopcoordsofbox(boxxboxy) convert board coordinates to pixel coordinates left boxx (boxsize gapsizexmargin top boxy (boxsize gapsizeymargin return (lefttopyou should be familiar with cartesian coordinate systems (if you' like refresher on this topicread coordinate systems one system of coordinates that is used in the memory puzzle game is for the pixel or screen coordinates but we will also be using another coordinate system for the boxes this is because it will be easier to use ( to refer to the th box from the left and rd from the top (remember that the numbers start with not instead of using the pixel coordinate of the box' top left corner( howeverwe need way to translate between these two coordinate systems here' picture of the game and the two different coordinate systems remember that the window is pixels wide and pixels tallso ( is the bottom right corner (because the top left corner' pixel is ( )and not ( )
10,586
the lefttopcoordsofbox(function will take box coordinates and return pixel coordinates because box takes up multiple pixels on the screenwe will always return the single pixel at the top left corner of the box this value will be returned as two-integer tuple the lefttopcoordsofbox(function will often be used when we need pixel coordinates for drawing these boxes converting from pixel coordinates to box coordinates def getboxatpixel(xy) for boxx in range(boardwidth) for boxy in range(boardheight) lefttop lefttopcoordsofbox(boxxboxy boxrect pygame rect(lefttopboxsizeboxsize if boxrect collidepoint(xy) return (boxxboxy return (nonenonewe will also need function to convert from pixel coordinates (which the mouse clicks and mouse movement events useto box coordinates (so we can find out over which box the mouse event happenedrect objects have collidepoint(method that you can pass and coordinates too and it will return true if the coordinates are inside (that iscollide withthe rect object' area email questions to the authoral@inventwithpython com
10,587
in order to find which box the mouse coordinates are overwe will go through each box' coordinates and call the collidepoint(method on rect object with those coordinates when collidepoint(returns truewe know we have found the box that was clicked on or moved over and will return the box coordinates if none of them return truethen the getboxatpixel(function will return the value (nonenonethis tuple is returned instead of simply returning none because the caller of getboxatpixel(is expecting tuple of two values to be returned drawing the iconand syntactic sugar def drawicon(shapecolorboxxboxy) quarter int(boxsize syntactic sugar half int(boxsize syntactic sugar lefttop lefttopcoordsofbox(boxxboxyget pixel coords from board coords the drawicon(function will draw an icon (with the specified shape and colorat the space whose coordinates are given in the boxx and boxy parameters each possible shape has different set of pygame drawing function calls for itso we must have large set of if and elif statements to differentiate between them (these statements are on lines to the and coordinates of the left and top edge of the box can be obtained by calling the lefttopcoordsofbox(function the width and height of the box are both set in the boxsize constant howevermany of the shape drawing function calls use the midpoint and quarter-point of the box as well we can calculate this and store it in the variables quarter and half we could just as easily have the code int(boxsize instead of the variable quarterbut this way the code becomes easier to read since it is more obvious what quarter means rather than int(boxsize such variables are an example of syntactic sugar syntactic sugar is when we add code that could have been written in another way (probably with less actual code and variables)but does make the source code easier to read constant variables are one form of syntactic sugar precalculating value and storing it in variable is another type of syntactic sugar (for examplein the getrandomizedboard(functionwe could have easily made the code on lines and line into single line of code but it' easier to read as two separate lines we don' need to have the extra quarter and half variablesbut having them makes the code easier to read code that is easy to read is easy to debug and upgrade in the future draw the shapes if shape =donut
10,588
pygame draw circle(displaysurfcolor(left halftop half)half pygame draw circle(displaysurfbgcolor(left halftop half)quarter elif shape =square pygame draw rect(displaysurfcolor(left quartertop quarterboxsize halfboxsize half) elif shape =diamond pygame draw polygon(displaysurfcolor((left halftop)(left boxsize top half)(left halftop boxsize )(lefttop half)) elif shape =lines for in range( boxsize ) pygame draw line(displaysurfcolor(lefttop )(left itop) pygame draw line(displaysurfcolor(left itop boxsize )(left boxsize top ) elif shape =oval pygame draw ellipse(displaysurfcolor(lefttop quarterboxsizehalf)each of the donutsquarediamondlinesand oval functions require different drawing primitive function calls to make syntactic sugar with getting board space' icon' shape and color def getshapeandcolor(boardboxxboxy) shape value for xy spot is stored in board[ ][ ][ color value for xy spot is stored in board[ ][ ][ return board[boxx][boxy][ ]board[boxx][boxy][ the getshapeandcolor(function only has one line you might wonder why we would want function instead of just typing in that one line of code whenever we need it this is done for the same reason we use constant variablesit improves the readability of the code it' easy to figure out what code like shapecolor getshapeandcolor(does but if you looked code like shapecolor board[boxx][boxy][ ]board[boxx][boxy][ ]it would be bit more difficult to figure out drawing the box cover def drawboxcovers(boardboxescoverage) draws boxes being covered/revealed "boxesis list of two-item listswhich have the spot of the box for box in boxesemail questions to the authoral@inventwithpython com
10,589
lefttop lefttopcoordsofbox(box[ ]box[ ] pygame draw rect(displaysurfbgcolor(lefttopboxsizeboxsize) shapecolor getshapeandcolor(boardbox[ ]box[ ] drawicon(shapecolorbox[ ]box[ ] if coverage only draw the cover if there is an coverage pygame draw rect(displaysurfboxcolor(lefttopcoverageboxsize) pygame display update( fpsclock tick(fpsthe drawboxcovers(function has three parametersthe board data structurea list of (xytuples for each box that should have the cover drawnand then the amount of coverage to draw for the boxes since we want to use the same drawing code for each box in the boxes parameterwe will use for loop on line so we execute the same code on each box in the boxes list inside this for loopthe code should do three thingsdraw the background color (to paint over anything that was there before)draw the iconthen draw however much of the white box over the icon that is needed the lefttopcoordsofbox(function will return the pixel coordinates of the top left corner of the box the if statement on line makes sure that if the number in coverage happens to be less than we won' call the pygame draw rect(function when the coverage parameter is there is no coverage at all when the coverage is set to there is pixel wide white box covering the icon the largest size we'll want the coverage set to is the number in boxsizewhere the entire icon is completely covered drawboxcovers(is going to be called from separate loop than the game loop because of thisit needs to have its own calls to pygame display update(and fpsclock tick(fpsto display the animation (this does mean that while inside this loopthere is no code being run to handle any events being generated that' finesince the cover and reveal animations only take second or so to play handling the revealing and covering animation def revealboxesanimation(boardboxestoreveal) do the "box revealanimation for coverage in range(boxsize(-revealspeed revealspeed) drawboxcovers(boardboxestorevealcoverage def coverboxesanimation(boardboxestocover) do the "box coveranimation
10,590
for coverage in range( boxsize revealspeedrevealspeed)drawboxcovers(boardboxestocovercoverageremember that an animation is simply just displaying different images for brief moments of timeand together they make it seem like things are moving on the screen the revealboxesanimation(and coverboxesanimation(only need to draw an icon with varying amount of coverage by the white box we can write single function called drawboxcovers(which can do thisand then have our animation function call drawboxcovers(for each frame of animation as we saw in the last sectiondrawboxcovers(makes call to pygame display update(and fpsclock tick(fpsitself to do thiswe'll set up for loop to make decreasing (in the case of revealboxesanimation()or increasing (in the case of coverboxesanimation()numbers for the converage parameter the amount that the coverage variable will decrease/increase by is the number in the revealspeed constant on line we set this constant to meaning that on each call to drawboxcovers()the white box will decrease/increase by pixels on each iteration if we increase this numberthen more pixels will be drawn on each callmeaning that the white box will decrease/increase in size faster if we set it to then the white box will only appear to decrease or increase by pixel on each iterationmaking the entire reveal or cover animation take longer think of it like climbing stairs if on each step you takeyou climbed one stairthen it would take normal amount of time to climb the entire staircase but if you climbed two stairs at time on each step (and the steps took just as long as before)you could climb the entire staircase twice as fast if you could climb the staircase stairs at timethen you would climb the entire staircase times as fast drawing the entire board def drawboard(boardrevealed) draws all of the boxes in their covered or revealed state for boxx in range(boardwidth) for boxy in range(boardheight) lefttop lefttopcoordsofbox(boxxboxy if not revealed[boxx][boxy] draw covered box pygame draw rect(displaysurfboxcolor(lefttopboxsizeboxsize) else draw the (revealedicon shapecolor getshapeandcolor(boardboxxboxyemail questions to the authoral@inventwithpython com
10,591
drawicon(shapecolorboxxboxythe drawboard(function makes call to drawicon(for each of the boxes on the board the nested for loops on lines and will loop through every possible and coordinate for the boxesand will either draw the icon at that location or draw white square instead (to represent covered up boxdrawing the highlight def drawhighlightbox(boxxboxy) lefttop lefttopcoordsofbox(boxxboxy pygame draw rect(displaysurfhighlightcolor(left top boxsize boxsize ) to help the player recognize that they can click on covered box to reveal itwe will make blue outline appear around box to highlight it this outline is drawn with call to pygame draw rect(to make rectangle with width of pixels the "start gameanimation def startgameanimation(board) randomly reveal the boxes at time coveredboxes generaterevealedboxesdata(false boxes [ for in range(boardwidth) for in range(boardheight) boxes append(xy random shuffle(boxes boxgroups splitintogroupsof( boxesthe animation that plays at the beginning of the game gives the player quick hint as to where all the icons are located in order to make this animationwe have to reveal and cover up groups of boxes one group after another to do thisfirst we'll create list of every possible space on the board the nested for loops on lines and will add (xytuples to list in the boxes variable we will reveal and cover up the first boxes in this listthen the next then the next after thatand so on howeversince the order of the (xytuples in boxes would be the same each timethen the same order of boxes would be displayed (try commenting out line and then running to program few times to see this effect to change up the boxes each time game startswe will call the random shuffle(function to randomly shuffle the order of the tuples in the boxes list then when we reveal and cover up
10,592
the first boxes in this list (and each group of boxes afterwards)it will be random group of boxes to get the lists of boxeswe call our splitintogroupsof(functionpassing and the list in boxes the list of lists that the function returns will be stored in variable named boxgroups revealing and covering the groups of boxes drawboard(boardcoveredboxesfor boxgroup in boxgroupsrevealboxesanimation(boardboxgroupcoverboxesanimation(boardboxgroupfirstwe draw the board since every value in coveredboxes is set to falsethis call to drawboard(will end up drawing only covered up white boxes the revealboxesanimation(and coverboxesanimation(functions will draw over the spaces of these white boxes the for loop will go through each of the inner lists in the boxgroups lists we pass these to revealboxesanimation()which will perform the animation of the white boxes being pulled away to reveal the icon underneath then the call to coverboxesanimation(will animate the white boxes expanding to cover up the icons then the for loop goes to the next iteration to animate the next set of boxes the "game wonanimation def gamewonanimation(board) flash the background color when the player has won coveredboxes generaterevealedboxesdata(true color lightbgcolor color bgcolor for in range( ) color color color color swap colors displaysurf fill(color drawboard(boardcoveredboxes pygame display update( pygame time wait( when the player has uncovered all of the boxes by matching every pair on the boardwe want to congratulate them by flashing the background color the for loop will draw the color in the color variable for the background color and then draw the board over it howeveron each iteration of the for loopthe values in color and color will be swapped with each other email questions to the authoral@inventwithpython com
10,593
on line this way the program will alternate between drawing two different background colors remember that this function needs to call pygame display update(to actually make the displaysurf surface appear on the screen telling if the player has won def haswon(revealedboxes) returns true if all the boxes have been revealedotherwise false for in revealedboxes if false in return false return false if any boxes are covered return true the player has won the game when all of the icon pairs have been matched since the --revealed|data structure gets values in it set to true as icons have been matchedwe can simply loop through every space in revealedboxes looking for false value if even one false value is in revealedboxesthen we know there are still unmatched icons on the board note that because revealedboxes is list of liststhe for loop on line will set the inner list as the values of but we can use the in operator to search for false value in the entire inner list this way we don' need to write an additional line of code and have two nested for loops like thisfor in revealedboxesfor in revealedboxes[ ]if false =revealedboxes[ ][ ]return false why bother having main(function if __name__ ='__main__' main(it may seem pointless to have main(functionsince you could just put that code in the global scope at the bottom of the program insteadand the code would run the exact same howeverthere are two good reasons to put them inside of main(function firstthis lets you have local variables whereas otherwise the local variables in the main(function would have to become global variables limiting the number of global variables is good way to keep the code simple and easier to debug (see the --why global variables are evil|section in this
10,594
secondthis also lets you import the program so that you can call and test individual functions if the memorypuzzle py file is in the :\python folderthen you can import it from the interactive shell type the following to test out the splitintogroupsof(and getboxatpixel(functions to make sure they return the correct return valuesimport memorypuzzle memorypuzzle splitintogroupsof( [ , , , , , , , , , ][[ ][ ][ ][ ]memorypuzzle getboxatpixel( (nonenonememorypuzzle getboxatpixel( ( when module is importedall of the code in it is run if we didn' have the main(functionand had its code in the global scopethen the game would have automatically started as soon as we imported itwhich really wouldn' let us call individual functions in it that' why the code is in separate function that we have named main(then we check the built-in python variable __name__ to see if we should call the main(function or not this variable is automatically set by the python interpreter to the string '__main__if the program itself is being run and 'memorypuzzleif it is being imported this is why the main(function is not run when we executed the import memorypuzzle statement in the interactive shell this is handy technique for being able to import the program you are working on from the interactive shell and make sure individual functions are returning the correct values by testing them one call at time why bother with readabilitya lot of the suggestions in this haven' been about how to write programs that computers can run so much as how to write programs that programmers can read you might not understand why this is important after allas long as the code workswho cares if it is hard or easy for human programmers to readhoweverthe important thing to realize about software is that it is rarely ever left alone when you are creating your own gamesyou will rarely be --done|with the program you will always get new ideas for game features you want addor find new bugs with the program because of thisit is important that your program is readable so that you can look at the code and understand it and understanding the code is the first step to changing it to add more code or fix bugs as an examplehere is an obfuscated version of the memory puzzle program that was made entirely unreadable if you type it in (or download it from email questions to the authoral@inventwithpython com
10,595
as the code at the beginning of this but if there was bug with this codeit would be impossible to read the code and understand what' going onmuch less fix the bug the computer doesn' mind code as unreadable as this it' all the same to it import randompygamesys from pygame locals import def hhh()global ab pygame init( pygame time clock( pygame display set_mode(( ) pygame display set_caption('memory game' (hh (falseh none fill(( ) (iwhile truee false fill(( ) (ihhfor eee in pygame event get()if eee type =quit or (eee type =keyup and eee key =k_escape)pygame quit(sys exit(elif eee type =mousemotionjk eee pos elif eee type =mousebuttonupjk eee pos true bbee (jkif bb !none and ee !noneif not hh[bb][ee] (bbeeif not hh[bb][eeand eo( [(bbee)]hh[bb][eetrue if =noneh (bbeeelseqfff (ih[ ] [ ]rggg (ibbee
10,596
if ! or fff !gggpygame time wait( ( [( [ ] [ ])(bbee)]hh[ [ ]][ [ ]false hh[bb][eefalse elif ii(hh)jj(ipygame time wait( (hh (falsef(ihhpygame display update(pygame time wait( (ih none pygame display update( tick( def (ccc)hh [for in range( )hh append([ccc return hh def ()rr [for tt in (( )( )( )( )( )( )( ))for ss in (' '' '' '' '' ')rr append(ssttrandom shuffle(rrrr rr[: random shuffle(rrbbb [for in range( ) [for in range( ) append(rr[ ]del rr[ bbb append(vreturn bbb def (vvuu)ww [for in range( len(uu)vv)ww append(uu[ : vv]return ww def aa(bbee)return (bb ee def (xy)email questions to the authoral@inventwithpython com
10,597
for bb in range( )for ee in range( )ooddd aa(bbeeaaa pygame rect(ooddd if aaa collidepoint(xy)return (bbeereturn (nonenonedef (ssttbbee)ooddd aa(bbeeif ss =' 'pygame draw circle(btt(oo ddd ) pygame draw circle( ( )(oo ddd ) elif ss =' 'pygame draw rect(btt(oo ddd )elif ss =' 'pygame draw polygon(btt((oo ddd)(oo ddd )(oo ddd )(ooddd ))elif ss =' 'for in range( )pygame draw line(btt(ooddd )(oo iddd)pygame draw line(btt(oo iddd )(oo ddd )elif ss =' 'pygame draw ellipse(btt(ooddd )def (bbbbbee)return bbb[bb][ee][ ]bbb[bb][ee][ def dd(bbbboxesgg)for box in boxesooddd aa(box[ ]box[ ]pygame draw rect( ( )(ooddd )sstt (bbbbox[ ]box[ ] (ssttbox[ ]box[ ]if gg pygame draw rect( ( )(oodddgg )pygame display update( tick( def (bbbcc)for gg in range( (- - )dd(bbbccggdef (bbbff)for gg in range( )dd(bbbffggdef (bbbpp)for bb in range( )for ee in range( )ooddd aa(bbeeif not pp[bb][ee]pygame draw rect( ( )(ooddd )
10,598
elsesstt (bbbbbeew(ssttbbeedef (bbee)ooddd aa(bbeepygame draw rect( ( )(oo ddd ) def (bbb)mm (falseboxes [for in range( )for in range( )boxes append(xyrandom shuffle(boxeskk ( boxesf(bbbmmfor nn in kko(bbbnnp(bbbnndef jj(bbb)mm (truett ( tt ( for in range( )tt tt tt tt fill(tt (bbbmmpygame display update(pygame time wait( def ii(hh)for in hhif false in ireturn false return true if __name__ ='__main__'hhh(never write code like this if you program like this while facing the mirror in bathroom with the lights turned offthe ghost of ada lovelace will come out of the mirror and throw you into the jaws of jacquard loom summaryand hacking suggestion this covers the entire explanation of how the memory puzzle program works read over the and the source code again to understand it better many of the other game programs in this book make use of the same programming concepts (like nested for loopssyntactic sugaremail questions to the authoral@inventwithpython com
10,599
and different coordinate systems in the same programso they won' be explained again to keep this book short one idea to try out to understand how the code works is to intentionally break it by commenting out random lines doing this to some of the lines will probably cause syntactic error that will prevent the script from running at all but commenting out other lines will result in weird bugs and other cool effects try doing this and then figure out why program has the bugs it does this is also the first step in being able to add your own secret cheats or hacks to the program by breaking the program from what it normally doesyou can learn how to change it to do something neat effect (like secretly giving you hints on how to solve the puzzlefeel free to experiment you can always save copy of the unchanged source code in different file if you want to play the regular game again in factif you' like some practice fixing bugsthere are several versions of this game' source code that have small bugs in them you can download these buggy versions from and why the program is acting that way