id
int64
0
25.6k
text
stringlengths
0
4.59k
7,700
line is the first line beyond the while-block that started on line this code is executed when the execution breaks out of that while loop from line or at this pointthe game is over now the program should print the board and scores and determine who won the game getscoreofboard(will return dictionary with keys 'xand 'oand values of both playersscores by checking if the player' score is greater thanless thanor equal to the computer' scoreyou can know if the player wonlostor tiedrespectively ask the player to play again if not playagain()break call the playagain(functionwhich returns true if the player typed in that they want to play another game if playagain(returns falsethe not operator makes the if statement' condition truethe execution breaks out of the while loop that started on line since there are no more lines of code after this while-blockthe program terminates otherwiseplayagain(has returned true (making the if statement' condition false)and so execution loops back to the while statement on line and new game board is created changing the drawboard(function the board you draw for the reversi game is large but you could change the drawboard(function' code to draw out much smaller boardwhile keeping the rest of the game code the same the newsmaller board would look like this + xox xxxxx ox ooo +you have points the computer has points enter your moveor type quit to end the gameor hints to turn off/on hints here is the code for this new drawboard(functionstarting at line you can also download this code from post questions to
7,701
def drawboard(board) this function prints out the board that it was passed returns none hline ++ print( ' print(hline for in range( ) print('% |( + )end='' for in range( ) print(board[ ][ ]end='' print('|' print(hlinesummary the ai may seem almost unbeatablebut this isn' because the computer is smart the strategy it follows is simplemove on the corner if you canotherwise make the move that will flip over the most tiles we could do thatbut it would be slow to figure out how many tiles would be flipped for every possible valid move we could make but calculating this for the computer is simple the computer isn' smarter than usit' just much fasterthis game is similar to sonar because it makes use of grid for board it is also like the tic tac toe game because there' an ai that plans out the best move for it to take this only introduced one new conceptthat empty listsblank stringsand the integer all evaluate to false in the context of condition other than thatthis game used programming concepts you already knewyou don' have to know much about programming to create interesting games howeverthis game is stretching how far you can get with ascii art the board took up almost the entire screen to drawand the game didn' have any color later in this bookwe will learn how to create games with graphics and animationnot just text we will do this using module called pygamewhich adds new functions and features to python so that we can break away from using only text and keyboard input
7,702
reversi ai simulation topics covered in this simulations percentages pie charts integer division the round(function "computer vs computergames the reversi ai algorithm was simplebut it beats me almost every time play it this is because the computer can process instructions fastso checking each possible position on the board and selecting the highest scoring move is easy for the computer it would take long time for me to find the best move this way the reversi program in had two functionsgetplayermove(and getcomputermove(which both returned the move selected as two-item list like [xythe both also had the same parametersthe game board data structure and which tile they were getplayermove(decided which [xymove to return by letting the player type in the coordinates getcomputermove(decided which [xymove to return by running the reversi ai algorithm what happens when we replace the call to getplayermove(with call to getcomputermove()then the player never types in moveit is decided for themthe computer is playing against itselfwe will make three new programseach based on the reversi program in the last aisim py will be made by making changes to reversi py aisim py will be made by making changes to aisim py aisim py will be made by making changes to aisim py you can either type these changes in yourselfor download them from the book' website at the url post questions to
7,703
making the computer play against itself save the old reversi py file as aisim py by clicking on file save asand then entering aisim py for the file name and clicking ok this will create copy of our reversi source code as new file that you can make changes towhile leaving the original reversi game the same (you may want to play it againchange the following code in aisim py move getplayermove(mainboardplayertileto this (the change is in bold) move getcomputermove(mainboardplayertilenow run the program notice that the game still asks you if you want to be or obut it won' ask you to enter any moves when you replaced getplayermove()you no longer call any code that takes this input from the player you still press enter after the original computer' moves (because of the input('press enter to see the computer\' move 'on line )but the game plays itselflet' make some other changes to aisim py all of the functions you defined for reversi can stay the same but replace the entire main section of the program (line and onto look like the following code some of the code has remainedbut most of it has been altered but all of the lines before line are the same as in reversi in the last you can also avoid typing in the code by downloading the source from the url if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at aisim py print('welcome to reversi!' while true reset the board and game mainboard getnewboard( resetboard(mainboard if whogoesfirst(='player' turn ' else turn ' print('the turn will go first ' while true drawboard(mainboard
7,704
scores getscoreofboard(mainboard print(' has % points has % points(scores[' ']scores[' ']) input('press enter to continue ' if turn =' ' ' turn othertile ' xy getcomputermove(mainboard' ' makemove(mainboard' 'xy else ' turn othertile ' xy getcomputermove(mainboard' ' makemove(mainboard' 'xy if getvalidmoves(mainboardothertile=[] break else turn othertile display the final score drawboard(mainboard scores getscoreofboard(mainboard print(' scored % points scored % points (scores[' ']scores[' ']) if not playagain() sys exit(how the aisim py code works the aisim py program is the same as the original reversi programexcept that the call to getplayermove(has been replaced with call to getcomputermove(there have been some other changes to the text that is printed to the screen to make the game easier to follow when you run the aisim py programall you can do is press enter for each turn until the game ends run through few games and watch the computer play itself since both the and players are using the same algorithmit really is just matter of luck to see who wins the player will win half the timeand the player will win half the time post questions to
7,705
making the computer play itself several times but what if we created new algorithmthen we could set this new ai against the one implemented in getcomputermove()and see which one is better let' make some changes to the source code do the following to make aisim py click on file save as save this file as aisim py so that you can make changes without affecting aisim py (at this pointaisim py and aisim py will have the same code make changes to aisim py and save that file (aisim py will have the new changes and aisim py will have the originalunchanged code add the following code the additions are in boldand some lines have been removed when you are done changing the filesave it as aisim py if this is confusingyou can always download the aisim py source code from the book' website at aisim py if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at aisim py print('welcome to reversi!' xwins owins ties numgames int(input('enter number of games to run') for game in range(numgames) print('game #% :(game)end=' reset the board and game mainboard getnewboard( resetboard(mainboard if whogoesfirst(='player' turn ' else turn ' while true if turn =' ' ' turn
7,706
othertile ' xy getcomputermove(mainboard' ' makemove(mainboard' 'xy else ' turn othertile ' xy getcomputermove(mainboard' ' makemove(mainboard' 'xy if getvalidmoves(mainboardothertile=[] break else turn othertile display the final score scores getscoreofboard(mainboard print(' scored % points scored % points (scores[' ']scores[' ']) if scores[' 'scores[' '] xwins + elif scores[' 'scores[' '] owins + else ties + numgames float(numgames xpercent round(((xwins numgames ) opercent round(((owins numgames ) tiepercent round(((ties numgames ) print(' wins % games (% %%) wins % games (% %%)ties for % games (% %%of % games total (xwinsxpercentowinsopercenttiestiepercentnumgames)how the aisim py code works you have added the variables xwinsowinsand ties to lines to to keep track of how many times winso winsand when they tie lines to increment these variables at the end of each gamebefore it loops back to start new game you have removed most of the print(function calls from the programas well as the calls to drawboard(when you run aisim pyit asks you how many games you want to run now that you've taken out the call to drawboard(and replace the while trueloop with for game in range(numgames)loopyou can run number of games without stopping for the user to type anything here is sample run of ten of computer vs computer reversi gamespost questions to
7,707
welcome to reversienter number of games to run game # scored points scored points game # scored points scored points game # scored points scored points game # scored points scored points game # scored points scored points game # scored points scored points game # scored points scored points game # scored points scored points game # scored points scored points game # scored points scored points wins games ( %) wins games ( %)ties for games ( %of games total because the algorithms include randomnessyour run won' have the exact numbers as above printing things out to the screen slows the computer downbut now that you have removed that codethe computer can run an entire game of reversi in about second or two think about it each time the program printed out one of those lines with the final scoreit ran through an entire game (which is about fifty or sixty moveseach move carefully checked to be the one that gets the most pointspercentages figure - pie chart with % % %and portions percentages are portion of total amountand range from to if you had of pieyou would have the entire pie if you had of pieyou wouldn' have any pie at all of the pie would be half of the pie pie is common image to use for percentages in fact
7,708
there' kind of chart called pie chart which shows how much of the full total certain portion is figure - is pie chart with % % %and portions below notice that adds up to % whole pie we can calculate the percentage with division to get percentagedivide the part you have by the totaland then multiply by one hundred for exampleif won out of gamesyou would calculate the expression which would evaluate to multiply this by to get percentage (in this case %notice that if won out of gamesyou could calculate the percentage with which would also evaluate to when you multiply by to get the percentageyou get winning out of games is the same percentage (that isthe same portionas winning out of games division evaluates to floating point it is important to note that when you use the division operatorthe expression will always evaluate to floating point number for examplethe expression will evaluate to the floating point value not to the integer value this is important to rememberbecause adding an integer to floating point value with the addition operator will also always evaluate to floating point value for example will evaluate to the floating point value and not to the integer try entering the following code into the interactive shellspam spam spam spam spam notice that in the above examplethe data type of the value stored in spam is always floating point value you can pass the floating point value to the int(functionwhich will return an integer form of the floating point value but this will always round the floating point value down for examplethe expressions int( )int( )and int( will all evaluate to and never the round(function the round(function will round float number to the nearest whole float number try entering the following into the interactive shellpost questions to
7,709
round( round( round( round( round( the round(function also has an optional parameterwhere you can specify to what place you want to round the number to for examplethe expression round( evaluates to and round( evaluates to displaying the statistics numgames float(numgames xpercent round(((xwins numgames ) opercent round(((owins numgames ) tiepercent round(((ties numgames ) print(' wins % games (% %%) wins % games (% %%)ties for % games (% %%of % games total (xwinsxpercentowinsopercenttiestiepercentnumgames)the code at the bottom of the program will show the user how many wins and hadhow many ties there wereand how what percentages these make up statisticallythe more games you runthe more accurate your percentages will be for finding the best ai algorithm if you only ran ten gamesand won three of themthen it would seem that ' algorithm only wins of the time howeverif you run hundredor even thousand gamesthen you may find that ' algorithm wins closer to (that ishalfof the games to find the percentagesdivide the number of wins or ties by the total number of games then multiply the result by howeveryou may end up with number like so pass this number to the round(function with the second parameter of to limit the precision to two decimal placesso it will return float like instead (which is much more readablelet' try another experiment run aisim py againbut this time have it run hundred gamessample run of aisim py welcome to reversienter number of games to run
7,710
game # scored points scored points game # scored points scored points game # scored points scored points game # scored points scored points skipped for brevity game # scored points scored points game # scored points scored points game # scored points scored points game # scored points scored points wins games ( %) wins games ( %)ties for games ( %of games total depending on how fast your computer isthis run might have taken about couple minutes you can see that the results of all one hundred games still evens out to about fifty-fiftybecause both and are using the same algorithm to win comparing different ai algorithms let' add some new functions with new algorithms but first click on file save asand save this file as aisim py before the print('welcome to reversi!'lineadd these functions in the following source code listing aisim py if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at aisim py def getrandommove(boardtile) return random move return random choicegetvalidmoves(boardtile def isonside(xy) return = or = or = or == def getcornersidebestmove(boardtile) return corner moveor side moveor the best move possiblemoves getvalidmoves(boardtile randomize the order of the possible moves random shuffle(possiblemoves post questions to
7,711
always go for corner if available for xy in possiblemoves if isoncorner(xy) return [xy if there is no cornerreturn side move for xy in possiblemoves if isonside(xy) return [xy return getcomputermove(boardtile def getsidebestmove(boardtile) return corner moveor side moveor the best move possiblemoves getvalidmoves(boardtile randomize the order of the possible moves random shuffle(possiblemoves return side moveif available for xy in possiblemoves if isonside(xy) return [xy return getcomputermove(boardtile def getworstmove(boardtile) return the move that flips the least number of tiles possiblemoves getvalidmoves(boardtile randomize the order of the possible moves random shuffle(possiblemoves go through all the possible moves and remember the best scoring move worstscore for xy in possiblemoves dupeboard getboardcopy(board makemove(dupeboardtilexy score getscoreofboard(dupeboard)[tile if score worstscore worstmove [xy worstscore score return worstmove
7,712
def getcornerworstmove(boardtile) return cornera spaceor the move that flips the least number of tiles possiblemoves getvalidmoves(boardtile randomize the order of the possible moves random shuffle(possiblemoves always go for corner if available for xy in possiblemoves if isoncorner(xy) return [xy return getworstmove(boardtile print('welcome to reversi!'how the aisim py code works lot of these functions are similar to one anotherand some of them use the new isonside(function here' review of the new algorithms we've madefunction getrandommove(table - functions used for our reversi ai description randomly choose valid move to make getcornersidebestmove(take corner move if available if there' no cornertake space on the side if no sides are availableuse the regular getcomputermove(algorithm getsidebestmove(take side space if there' one available if notthen use the regular getcomputermove(algorithm this means side spaces are chosen before corner spaces getworstmove(take the space that will result in the fewest tiles being flipped getcornerworstmove(take corner spaceif available if notuse the getworstmove(algorithm post questions to
7,713
comparing the random algorithm against the regular algorithm now the only thing to do is replace one of the getcomputermove(calls in the main part of the program with one of the new functions then you can run several games and see how often one algorithm wins over the other firstlet' replace ' algorithm with the one in getcomputermove(with getrandommove(on line xy getrandommove(mainboard' 'when you run the program with hundred games nowit will look something like thiswelcome to reversienter number of games to run game # scored points scored points game # scored points scored points game # scored points scored points skipped for brevity game # scored points scored points game # scored points scored points game # scored points scored points wins games ( %) wins games ( %)ties for games ( %of games total wowx won far more often than did that means that the algorithm in getcomputermove((take any available cornersotherwise take the space that flips the most tileswins more games than the algorithm in getrandommove((which makes moves randomlythis makes sensebecause making intelligent choices is usually better than just choosing things at random comparing the random algorithm against itself what if we changed ' algorithm to also use the algorithm in getrandommove()let' find out by changing ' function call on line from getcomputermove(to getrandommove(and running the program again welcome to reversienter number of games to run game # scored points scored points game # scored points scored points skipped for brevity game # scored points scored points
7,714
game # scored points scored points wins games ( %) wins games ( %)ties for games ( %of games total as you can seewhen both players are making random movesthey each win about of the time (in the above caseo happen to get lucky and won little bit more than half of the time just like moving on the corner spaces is good idea because they cannot be flippedmoving on the side spaces may also be good idea on the sidethe tile has the edge of the board and isn' as out in the open as the other pieces the corners are still preferable to the side spacesbut moving on the sides (even when there' move that can flip more piecesmay be good strategy comparing the regular algorithm against the cornerssidebest algorithm change ' algorithm on line to use getcomputermove((the original algorithmand ' algorithm on line to use getcornersidebestmove((which first tries to move on cornerthen tries to move on side spaceand then takes the best remaining move)and let' run hundred games to see which is better try changing the function calls and running the program again welcome to reversienter number of games to run game # scored points scored points game # scored points scored points skipped for brevity game # scored points scored points game # scored points scored points wins games ( %) wins games ( %)ties for games ( %of games total wowthat' unexpected it seems that choosing the side spaces over space that flips more tiles is bad strategy to use the benefit of the side space isn' greater than the cost of flipping fewer of the opponent' tiles can we be sure of these resultslet' run the program againbut this time play one thousand games this may take few minutes for your computer to run (but it would take weeks for you to do this by hand!try changing the function calls and running the program again welcome to reversienter number of games to run game # scored points scored points game # scored points scored points post questions to
7,715
skipped for brevity game # scored points scored points game # scored points scored points wins games ( %) wins games ( %)ties for games ( %of games total the more accurate statistics from the thousand-games run are about the same as the statistics from the hundred-games run it seems that choosing the move that flips the most tiles is better idea than choosing side move comparing the regular algorithm against the worst algorithm now set the player' algorithm on line to use getcomputermove(and the player' algorithm on line to getworstmove((which makes the move that flips over the least number of tiles)and run hundred games try changing the function calls and running the program again welcome to reversienter number of games to run game # scored points scored points game # scored points scored points skipped for brevity game # scored points scored points game # scored points scored points wins games ( %) wins games ( %)ties for games ( %of games total whoathe algorithm in getworstmove()which always chose the move that flips the fewest tileswill almost always lose to the regular algorithm this isn' really surprising at all (in factit' surprising that this strategy wins even of the time!comparing the regular algorithm against the worstcorner algorithm how about when we replace getworstmove(on line with getcornerworstmove()this is the same algorithm except it takes any available corner pieces before taking the worst move try changing the function calls and running the program again welcome to reversienter number of games to run game # scored points scored points game # scored points scored points skipped for brevity
7,716
game # scored points scored points game # scored points scored points wins games ( %) wins games ( %)ties for games ( %of games total the getcornerworstmove(still loses most of the gamesbut it seems to win few more games than getworstmove(( compared to %does taking the corner spaces when they are available really make differencecomparing the worst algorithm against the worstcorner algorithm you can check by setting ' algorithm to getworstmove(and ' algorithm to getcornerworstmove()and then running the program try changing the function calls and running the program again welcome to reversienter number of games to run game # scored points scored points game # scored points scored points skipped for brevity game # scored points scored points game # scored points scored points wins games ( %) wins games ( %)ties for games ( %of games total yeseven when otherwise making the worst moveit does seem like taking the corners results in many more wins while you've found out that going for the sides makes you lose more oftengoing for the corners is always good idea summary this didn' really cover gamebut it modeled various strategies for reversi if we thought that taking side moves in reversi was good ideawe would have to spend weekseven monthscarefully playing games of reversi by hand and writing down the results but if we know how to program computer to play reversithen we can have the computer play reversi using these strategies for us if you think about ityou'll realize that the computer is executing millions of lines of our python program in secondsyour experiments with the simulation of reversi can help you learn more about playing reversi in real life in factthis would make good science fair project your problem can be which set of moves leads to the most wins against other sets of movesand make hypothesis about which is post questions to
7,717
the best strategy after running several simulationsyou can determine which strategy works best with programming you can make science fair project out of simulation of any board gameand it is all because you know how to instruct the computer to do itstep by stepline by line you can speak the computer' languageand get it to do large amounts of data processing and number crunching for you that' all for the text-based games in this book games that only use text can be funeven though they're simple but most modern games use graphicssoundand animation to make much more exciting looking games for the rest of the in this bookwe will learn how to create games with graphics by using python module called pygame
7,718
graphics and animation topics covered in this installing pygame colors and fonts in pygame aliased and anti-aliased graphics attributes the pygame font fontpygame surfacepygame rectand pygame pixelarray data types constructor functions pygame' drawing functions the blit(method for surface objects events animation so farall of our games have only used text text is displayed on the screen as outputand the player types in text from the keyboard as input just using text makes programming easy to learn but in this we'll make some more exciting games with advanced graphics and sound using the pygame module and teaches you how to use pygame to make games with graphicsanimationmouse inputand sound in these we'll write source code for simple programs that are not games but demonstrate the pygame concepts we've learned the game in will use all these concepts together to create game installing pygame pygame doesn' come with python like pythonpygame is free to download in web browsergo to the url operating system and version of python open the installer file after downloading itand follow the instructions until pygame has finished installing to check that pygame installed correctlytype the following into the interactive shellimport pygame post questions to
7,719
if nothing appears after you hit the enter keythen you know pygame was successfully installed if the error importerrorno module named pygame appearstry to install pygame again (and make sure you typed import pygame correctlyfigure - the pygame org website the pygame website at several other game programs made with pygame figure - shows the pygame website hello world in pygame the first pygame program is new "hello world!program like you created at the beginning of the book this timeyou'll use pygame to make "hello world!appear in graphical window instead of as text pygame doesn' work well with the interactive shell because of thisyou can only write pygame programs and cannot send instructions to pygame one at time through the interactive shell pygame programs also do not use the input(function there is no text input and output insteadthe program displays output in window by drawing graphics and text to the window pygame program' input comes from the keyboard and the mouse through things called events events are explained in the next source code of hello world type in the following code into the file editorand save it as pygamehelloworld py if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at
7,720
pygamehelloworld py import pygamesys from pygame locals import set up pygame pygame init( set up the window windowsurface pygame display set_mode(( ) pygame display set_caption('hello world!' set up the colors black ( white ( red ( green ( blue ( set up fonts basicfont pygame font sysfont(none set up the text text basicfont render('hello world!'truewhiteblue textrect text get_rect( textrect centerx windowsurface get_rect(centerx textrect centery windowsurface get_rect(centery draw the white background onto the surface windowsurface fill(white draw green polygon onto the surface pygame draw polygon(windowsurfacegreen(( )( )( )( )( )) draw some blue lines onto the surface pygame draw line(windowsurfaceblue( )( ) pygame draw line(windowsurfaceblue( )( ) pygame draw line(windowsurfaceblue( )( ) draw blue circle onto the surface pygame draw circle(windowsurfaceblue( ) draw red ellipse onto the surface pygame draw ellipse(windowsurfacered( ) draw the text' background rectangle onto the surface post questions to
7,721
pygame draw rect(windowsurfacered(textrect left textrect top textrect width textrect height ) get pixel array of the surface pixarray pygame pixelarray(windowsurface pixarray[ ][ black del pixarray draw the text onto the surface windowsurface blit(texttextrect draw the window onto the screen pygame display update( run the game loop while true for event in pygame event get() if event type =quit pygame quit( sys exit(running the hello world program when you run this programyou should see new window appear which looks like figure - what is nice about using window instead of console is that the text can appear anywhere in the windownot just after the previous text you have printed the text can be any color and size the window is like blank painting canvasand you can draw whatever you like on it importing the pygame module let' go over each of these lines of code and find out what they do import pygamesys from pygame locals import
7,722
figure - the "hello worldprogram first you need to import the pygame module so you can call pygame' functions you can import several modules on the same line by delimiting the module names with commas line imports both the pygame and sys modules the second line imports the pygame locals module this module contains many constant variables that you'll use with pygame such as quit or k_escape (explained laterhoweverusing the form from modulename import you can import the pygame locals module but not have to type pygame locals in front of the module' constants if you have from sys import instead of import sys in your programyou could call exit(instead of sys exit(in your code but most of the time it is better to use the full function name so you know which module the function is in the pygame init(function set up pygame pygame init(all pygame programs must call the pygame init(after importing the pygame module but before calling any other pygame functions this perform' pygame' necessary initialization steps tuples tuple values are similar to listsexcept they use parentheses instead of square brackets alsolike stringstuples cannot be modified for exampletry entering the following into the interactive shellspam ('life''universe''everything' post questions to
7,723
spam[ 'lifespam[ spam[ : ('universe''everything'the pygame display set_mode(and pygame display set_caption(functions set up the window windowsurface pygame display set_mode(( ) pygame display set_caption('hello world!'line creates gui window by calling the set_mode(method in the pygame display module (the display module is module inside the pygame module even the pygame module has its own modules! pixel is the tiniest dot on your computer screen single pixel on your screen can light up into any color all the pixels on your screen work together to display all the pictures you see to create window pixels wide and pixels highuse the tuple ( for the first parameter to pygame display set_mode(there are three parameters to the set_mode(method the first is tuple of two integers for the width and height of the windowin pixels the second and third options are advanced options that are beyond the scope of this book just pass and for themrespectively the set_mode(function returns pygame surface object (which we will call surface objects for shortobjects is just another name for value of data type that has methods for examplestrings are objects in python because they have data (the string itselfand methods (such as lower(and split()the surface object represents the window variables store references to objects just like they store reference for lists and dictionaries the references section in explains references rgb colors set up the colors black ( white ( red ( green ( blue (
7,724
table - colors and their rgb values color rgb values black blue ( gray green lime ( purple ( red teal ( white ( yellow there are three primary colors of lightredgreen and blue by combining different amounts of these three colors (which is what your computer screen does)you can form any other color in pygametuples of three integers are the data structures that represent color these are called rgb color values the first value in the tuple is how much red is in the color value of means there' no red in this colorand value of means there' maximum amount of red in the color the second value is for green and the third value is for blue these three integers form an rgb tuple for examplethe tuple ( has no amount of redgreenor blue the resulting color is completely black the tuple ( has maximum amount of redgreenand blueresulting in white 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 get any shade of any color table - has some common colors and their rgb values the web page several more tuple values for different colors fontsand the pygame font sysfont(function set up fonts basicfont pygame font sysfont(none post questions to
7,725
figure - examples of different fonts font is complete set of lettersnumberssymbolsand characters drawn in single style figure - shows the same sentence printed in different fonts in our earlier gameswe only told python to print text the colorsizeand font that was used to display this text was completely determined by your operating system the python program couldn' change the font howeverpygame can draw text in any font on your computer line creates pygame font font object (called font objects for shortby calling the pygame font sysfont(function the first parameter is the name of the fontbut we will pass the none value to use the default system font the second parameter is the size of the font (which is measured in units called pointsthe render(method for font objects set up the text text basicfont render('hello world!'truewhiteblue textrect text get_rect(figure - an enlarged view of an aliased line and an anti-aliased line
7,726
the font object that you've stored in the basicfont variable has method called render(this method will return surface object with the text drawn on it the first parameter to render(is the string of the text to draw the second parameter is boolean for whether or not you want anti-aliasing on line pass true to use anti-aliasing anti-aliasing blurs your text slightly to make it look smoother figure - shows what line (with enlarged pixelslooks like with and without antialiasing attributes textrect centerx windowsurface get_rect(centerx textrect centery windowsurface get_rect(centery the pygame rect data type (called rect for shortrepresent rectangular areas of certain size and location to create new rect object call the function pygame rect(the parameters are integers for the xy coordinates of the top left cornerfollowed by the width and heightall in pixels the function name with the parameters looks like thispygame rect(lefttopwidthheightjust like methods are functions that are associated with an objectattributes are variables that are associated with an object the rect data type has many attributes that describe the rectangle they represent table - is list of attributes of rect object named myrect the great thing about rect objects is that if you modify any of these attributesall the other attributes will automatically modify themselves also for exampleif you create rect object that is pixels wide and pixels highand has the top left corner at the coordinates ( )then the -coordinate of the right side will automatically be set to (because howeverif you change the left attribute with the line myrect left then pygame will automatically change the right attribute to (because every other attribute for that rect object is also updated the get_rect(methods for pygame font font and pygame surface objects notice that both the font object (stored in the text variable on line and the surface object (stored in windowsurface variable on line both have method called get_rect(technicallythese are two different methods but the programmers of pygame gave them the same name because they both do the same thing and return rect objects that represent the size and position of the font or surface object post questions to
7,727
the module you import is pygameand inside the pygame module are the font and surface modules inside those modules are the font and surface data types the pygame programmers made the modules begin with lowercase letterand the data types begin with an uppercase letter this makes it easier to distinguish the data types and the modules constructor functions create pygame rect object by calling function named pygame rect(the pygame rect(function has the same name as the pygame rect data type functions that have the same name as their data type and create objects or values of this data type are called constructor functions the fill(method for surface objects draw the white background onto the surface windowsurface fill(whiteyou want to fill the entire surface stored in windowsurface with the color white the fill(function will completely cover the entire surface with the color you pass as the parameter (in this casethe white variable is set to the value ( an important thing to know about pygame is that the window on the screen won' change when you call the fill(method or any of the other drawing functions these will change the surface objectbut the surface object won' be drawn on the screen until the pygame display update(function is called this is because modifying the surface object in the computer' memory is much faster than modifying the image on the screen it is much more efficient to draw onto the screen once after all of the drawing functions have drawn to the surface pygame' drawing functions the pygame draw polygon(function draw green polygon onto the surface pygame draw polygon(windowsurfacegreen(( )( )( )( )( )) polygon is multisided shape with straight line sides circles and ellipses are not polygons figure - has some examples of polygons
7,728
pygame rect attribute myrect left table - rect attributes description integer value of the -coordinate of the left side of the rectangle myrect right integer value of the -coordinate of the right side of the rectangle myrect top integer value of the -coordinate of the top side of the rectangle myrect bottom integer value of the -coordinate of the bottom side of the rectangle myrect centerx integer value of the -coordinate of the center of the rectangle myrect centery integer value of the -coordinate of the center of the rectangle myrect width integer value of the width of the rectangle myrect height integer value of the height of the rectangle myrect size tuple of two integers(widthheightmyrect topleft tuple of two integers(lefttopmyrect topright tuple of two integers(righttopmyrect bottomleft tuple of two integers(leftbottommyrect bottomright tuple of two integers(rightbottommyrect midleft tuple of two integers(leftcenterymyrect midright tuple of two integers(rightcenterymyrect midtop tuple of two integers(centerxtopmyrect midbottom tuple of two integers(centerxbottomfigure - examples of polygons post questions to
7,729
the pygame draw polygon(function can draw any polygon shape you give it the parametersin orderarethe surface object to draw the polygon on the color of the polygon tuple of tuples that represents the xy coordinates of the points to draw in order the last tuple will automatically connect to the first tuple to complete the shape optionallyan integer for the width of the polygon lines without thisthe polygon will be filled in line draws green pentagon on the surface object the pygame draw line(function draw some blue lines onto the surface pygame draw line(windowsurfaceblue( )( ) pygame draw line(windowsurfaceblue( )( ) pygame draw line(windowsurfaceblue( )( ) the parametersin orderarethe surface object to draw the line on the color of the line tuple of two integers for the xy coordinate of one end of the line tuple of two integers for the xy coordinates of the other end of the line optionallyan integer for the width of the line if you pass for the widththe line will be four pixels thick if you do not specify the width parameterit will take on the default value of the three pygame draw line(calls on lines and draw the blue "zon the surface object the pygame draw circle(function draw blue circle onto the surface pygame draw circle(windowsurfaceblue( ) the parametersin orderare
7,730
the surface object to draw the circle on the color of the circle tuple of two integers for the xy coordinate of the center of the circle an integer for the radius (that isthe sizeof the circle optionallyan integer for the width width of means that the circle will be filled in line draws blue circle on the surface object the pygame draw ellipse(function draw red ellipse onto the surface pygame draw ellipse(windowsurfacered( ) the pygame draw ellipse(function is similar to the pygame draw circle(function the parametersin orderarethe surface object to draw the ellipse on the color of the ellipse tuple of four integers is passed for the lefttopwidthand height of the ellipse optionallyan integer for the width width of means that the circle will be filled in line draws red ellipse on the surface object the pygame draw rect(function draw the text' background rectangle onto the surface pygame draw rect(windowsurfacered(textrect left textrect top textrect width textrect height )the pygame draw rect(function will draw rectangle the third parameter is tuple of four integers for the lefttopwidthand height of the rectangle instead of tuple of four integers for the third parameteryou can also pass rect object on line you want the rectangle you draw to be pixels around all the sides of the text this is why you want the drawn rectangle' left and top to be the left and top of textrect minus (rememberyou subtract because coordinates decrease as you go left and up and the width and post questions to
7,731
height are equal to the width and height of the textrect plus (because the left and top were moved back pixelsso you need to make up for that spacethe pygame pixelarray data type get pixel array of the surface pixarray pygame pixelarray(windowsurface pixarray[ ][ black line creates pygame pixelarray object (called pixelarray object for shortthe pixelarray object is list of lists of color tuples that represents the surface object you passed it line passes windowsurface to the pygame pixelarray(callso assigning black to pixarray[ ][ on line will change the pixel at the coordinates ( to be black pixel pygame will automatically modify the windowsurface object with this change the first index in the pixelarray object is for the -coordinate the second index is for the ycoordinate pixelarray objects make it easy to set individual pixels on pixelarray object to specific color del pixarray creating pixelarray object from surface object will lock that surface object locked means that no blit(function calls (described nextcan be made on that surface object to unlock the surface objectyou must delete the pixelarray object with the del operator if you forget to delete the pixelarray objectyou'll get an error message that says pygame errorsurfaces must not be locked during blit the blit(method for surface objects draw the text onto the surface windowsurface blit(texttextrectthe blit(method will draw the contents of one surface object onto another surface object line will draw the "hello world!surface object in text and draws it to the surface object stored in the windowsurface variable the second parameter to blit(specifies where on the windowsurface surface the text surface should be drawn pass the rect object you got from calling text get_rect(on line
7,732
the pygame display update(function draw the window onto the screen pygame display update(in pygamenothing is actually drawn to the screen until the pygame display update(function is called this is because drawing to the screen is slow compared to drawing on the surface objects in the computer' memory you do not want to update to the screen after each drawing function is calledbut only update the screen once after all the drawing functions have been called events and the game loop in previous gamesall of the programs print everything immediately until they reach input(function call at that pointthe program stops and waits for the user to type something in and press enter but pygame programs are constantly running through loop called the game loop in this programall the lines of code in the game loop execute about hundred times second the game loop is loop that constantly checks for new eventsupdates the state of the windowand draws the window on the screen events are objects of the pygame event event data type that are generated by pygame whenever the user presses keyclicks or moves the mouseor makes some other event occur (these events are listed on table - run the game loop while trueline is the start of the game loop the condition for the while statement is set to true so that it loops forever the only time the loop exits is if an event causes the program to terminate the pygame event get(function for event in pygame event get()if event type =quitcalling pygame event get(retrieves any new pygame event event objects (called event objects for shortthat have been generated since the last call to pygame event get(these events are returned as list of event objects all event objects have an attribute called type which tell us what type of event it is (in this we only deal with the quit types of event the other types of events are covered in the next post questions to
7,733
line has for loop to iterate over each event object in the list returned by pygame event get(if the type attribute of the event is equal to the constant variable quitthen you know the user has closed the window and wants to terminate the program pygame generates the quit event (which was imported from the pygame locals modulewhen the user clicks on the close button (usually an xof the program' window it is also generated if the computer is shutting down and tries to terminate all the running programs for whatever reason the quit event was generatedyou should terminate the program the pygame quit(function pygame quit(sys exit(if the quit event has been generatedthe program should call both pygame quit(and sys exit(this has been the simple "hello world!program from pygame we've covered many new topics that we didn' have to deal with in our previous games even though the code is more complicatedthe pygame programs can also be much more fun than text games let' learn how to create games with animated graphics that move animation in this program we have several different blocks bouncing off of the edges of the window the blocks are different colors and sizes and move only in diagonal directions to animate the blocks (that ismake them look like they are movingwe will move the blocks few pixels over on each iteration through the game loop this will make it look like the blocks are moving around the screen source code of the animation program type the following program into the file editor and save it as animation py if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at animation py import pygamesystime from pygame locals import set up pygame
7,734
pygame init( set up the window windowwidth windowheight windowsurface pygame display set_mode((windowwidthwindowheight) pygame display set_caption('animation' set up direction variables downleft downright upleft upright movespeed set up the colors black ( red ( green ( blue ( set up the block data structure {'rect':pygame rect( )'color':red'dir':upright {'rect':pygame rect( )'color':green'dir':upleft {'rect':pygame rect( )'color':blue'dir':downleft blocks [ run the game loop while true check for the quit event for event in pygame event get() if event type =quit pygame quit( sys exit( draw the black background onto the surface windowsurface fill(black for in blocks move the block data structure if ['dir'=downleft ['rect'left -movespeed ['rect'top +movespeed if ['dir'=downright ['rect'left +movespeed ['rect'top +movespeed post questions to
7,735
if ['dir'=upleftb['rect'left -movespeed ['rect'top -movespeed if ['dir'=uprightb['rect'left +movespeed ['rect'top -movespeed check if the block has move out of the window if ['rect'top block has moved past the top if ['dir'=upleftb['dir'downleft if ['dir'=uprightb['dir'downright if ['rect'bottom windowheightblock has moved past the bottom if ['dir'=downleftb['dir'upleft if ['dir'=downrightb['dir'upright if ['rect'left block has moved past the left side if ['dir'=downleftb['dir'downright if ['dir'=upleftb['dir'upright if ['rect'right windowwidthblock has moved past the right side if ['dir'=downrightb['dir'downleft if ['dir'=uprightb['dir'upleft draw the block onto the surface pygame draw rect(windowsurfaceb['color'] ['rect']draw the window onto the screen pygame display update(time sleep(
7,736
figure - an altered screenshot of the animation program how the animation program works in this programwe will have three different colored blocks moving around and bouncing off the walls to do thiswe need to first consider how we want the blocks to move moving and bouncing the blocks each block will move in one of four diagonal directions when the block hits the side of the windowit should bounce off the side and move in new diagonal direction the blocks will bounce as shown figure - the new direction that block moves after it bounces depends on two thingswhich direction it was moving before the bounce and which wall it bounced off of there are total of eight possible ways block can bouncetwo different ways for each of the four walls for exampleif block is moving down and rightand then bounces off of the bottom edge of the windowwe want the block' new direction to be up and right we can represent the blocks with rect object to represent the position and size of the blocka tuple of three integers to represent the color of the blockand an integer to represent which of the four diagonal directions the block is currently moving on each iteration in the game loopadjust the and position of the block in the rect object alsoin each iteration draw all the blocks on the screen at their current position as the program execution iterates over the game loopthe blocks will gradually move across the screen so that it looks like they are smoothly moving and bouncing around on their own post questions to
7,737
figure - the diagram of how blocks will bounce creating and setting up pygame and the main window import pygamesystime from pygame locals import set up pygame pygame init( set up the window windowwidth windowheight windowsurface pygame display set_mode((windowwidthwindowheight) in this programyou'll see that the size of the window' width and height is used for more than just the call to set_mode(use constant variables so that if you ever want to change the size of the windowyou only have to change lines and since the window width and height never change during the program' executiona constant variable is good idea pygame display set_caption('animation'line sets the window' caption to 'animationby calling pygame display set_caption(setting up constant variables for direction set up direction variables downleft
7,738
downright upleft upright we will use the keys on the number pad of the keyboard to remind us which belongs to which direction this is similar to the tic tac toe game is down and left is down and right is up and leftand is up and right howeverit may be hard to remember thisso instead use constant variables instead of these integer values you could have used any value you wanted for these directions instead of using constant variable for exampleyou could use the string 'downleftto represent the down and left diagonal direction howeverif you ever mistype the 'downleftstring (for exampleas 'fownleft')python would not recognize that you meant to type 'downleftinstead of 'downleftthis bug would cause your program to behave strangelybut the program would not crash but if you use constant variablesand accidentally type the variable name fownleft instead of the name downleftpython would notice that there' no such variable named fownleft and crash the program with an error this would still be pretty bad bugbut at least you would know about it immediately and could fix it movespeed use constant variable to determine how fast the blocks should move value of here means that each block will move pixels on each iteration through the game loop setting up constant variables for color set up the colors black ( red ( green ( blue ( lines to set up constant variables for the colors rememberpygame uses tuple of three integer values for the amounts of redgreenand blue called an rgb value the integers are from to the use of constant variables is for readability the computer doesn' care if you use variable named green for the color green it is easier to know that green stands for the color greenrather than ( post questions to
7,739
setting up the block data structures set up the block data structure {'rect':pygame rect( )'color':red'dir':uprightset up dictionary as data structure that represents each block / introduced dictionaries the dictionary will have the keys of 'rect(with rect object for value)'color(with tuple of three integers for value)and 'dir(with one of the direction constant variables for valuethe variable will store one of these block data structures this block has its top left corner located at an -coordinate of and -coordinate of it has width of pixels and height of pixels its color is red and its direction is set to upright {'rect':pygame rect( )'color':green'dir':upleft {'rect':pygame rect( )'color':blue'dir':downleftline and creates two more similar data structures for blocks that are different sizespositionscolorsand directions blocks [ line put all of these data structures in listand store the list in variable named blocks the blocks variable stores list blocks[ would be the dictionary data structure in blocks[ ]['color'would be the 'colorkey in so the expression blocks[ ]['color'would evaluate to ( this way you can refer to any of the values in any of the block data structures by starting with blocks running the game loop run the game loop while true check for the quit event for event in pygame event get() if event type =quit pygame quit( sys exit(
7,740
inside the game loopthe blocks will move around the screen in the direction that they are going and bounce if they have hit side there is also code to draw all of the blocks to the windowsurface surface and call pygame display update(the for loop to check all of the events in the list returned by pygame event get(is the same as in our "hello world!program draw the black background onto the surface windowsurface fill(blackfirstline fills the entire surface with black so that anything previously drawn on the surface is erased moving each block for in blocksnextthe code must update the position of each blockso iterate over the blocks list inside the loopyou'll refer to the current block as simply so it will be easy to type move the block data structure if ['dir'=downleftb['rect'left -movespeed ['rect'top +movespeed if ['dir'=downrightb['rect'left +movespeed ['rect'top +movespeed if ['dir'=upleftb['rect'left -movespeed ['rect'top -movespeed if ['dir'=uprightb['rect'left +movespeed ['rect'top -movespeed the new value to set the left and top attributes to depends on the block' direction if the direction of the block (which is stored in the 'dirkeyis either downleft or downrightyou want to increase the top attribute if the direction is upleft or uprightyou want to decrease the top attribute if the direction of the block is downright or uprightyou want to increase the left attribute if the direction is downleft or upleftyou want to decrease the left attribute post questions to
7,741
change the value of these attributes by the integer stored in movespeed movespeed stores how many pixels over blocks move on each iteration of the game loopand was set on line checking if the block has bounced check if the block has move out of the window if ['rect'top block has moved past the top if ['dir'=upleftb['dir'downleft if ['dir'=uprightb['dir'downright after lines to move the blockcheck if the block has gone past the edge of the window if it hasyou want to "bouncethe block in the code this means set new value for the block' 'dirkey the block will move in the new direction on the next iteration of the game loop this makes it look like the block has bounced off the side of the window on line ' if statementthe block has moved past the top edge of the window if the block' rect object' top attribute is less than in that casechange the direction based on what direction the block was moving (either upleft or uprightchanging the direction of the bouncing block look at the bouncing diagram earlier in this to move past the top edge of the windowthe block had to either be moving in the upleft or upright directions if the block was moving in the upleft directionthe new direction (according to the bounce diagramwill be downleft if the block was moving in the upright directionthe new direction will be downright if ['rect'bottom windowheightblock has moved past the bottom if ['dir'=downleftb['dir'upleft if ['dir'=downrightb['dir'upright lines to handles if the block has moved past the bottom edge of the window they check if the bottom attribute (not the top attributeis greater than the value in windowheight remember that the -coordinates start at at the top of the window and increase to windowheight at the bottom the rest of the code changes the direction based on what the bounce diagram in figure - says
7,742
if ['rect'left block has moved past the left side if ['dir'=downleftb['dir'downright if ['dir'=upleftb['dir'upright if ['rect'right windowwidthblock has moved past the right side if ['dir'=downrightb['dir'downleft if ['dir'=uprightb['dir'upleft lines to are similar to lines to but checks if the left side of the block has moved to the left of the left edge of the window rememberthe -coordinates start at on the left edge of the window and increase to windowwidth on the right edge of the window drawing the blocks on the window in their new positions draw the block onto the surface pygame draw rect(windowsurfaceb['color'] ['rect']now that the blocks have movedthey should be drawn in their new positions on the windowsurface surface by calling the pygame draw rect(function pass windowsurface because it is the surface object to draw the rectangle on pass the ['color'because it is the color of the rectangle pass ['rect'because it is the rect object with the position and size of the rectangle to draw line is the last line of the for loop if you wanted to add new blocksyou only have to modify the blocks list on line and the rest of the code still works drawing the window on the screen draw the window onto the screen pygame display update(time sleep( after each of the blocks in the blocks list has been drawncall pygame display update(so that the windowsurface surface is draw on the screen post questions to
7,743
after this linethe execution loops back to the start of the game loop and begin the process all over again this waythe blocks are constantly moving littlebouncing off the wallsand being drawn on the screen in their new positions the call to the time sleep(function is there because the computer can movebounceand draw the blocks so fast that if the program ran at full speedall the blocks would look like blur (try commenting out the time sleep( line and running the program to see this this call to time sleep(will stop the program for secondsor milliseconds drawing trails of blocks comment out line (the windowsurface fill(blacklineby adding to the front of the line now run the program without the call to windowsurface fill(black)you don' black out the entire window before drawing the rectangles in their new position the trails of rectangles appear because the old rectangles drawn in previous iterations through the game loop aren' blacked out anymore remember that the blocks are not really moving on each iteration through the game loopthe code redraws the entire window with new blocks that are located few pixels over each time summary this has presented whole new way of creating computer programs the previous programs would stop and wait for the player to enter text howeverin our animation programthe program is constantly updating the data structures of things without waiting for input from the player remember in our hangman and tic tac toe games we had data structures that would represent the state of the boardand these data structures would be passed to drawboard(function to be displayed on the screen our animation program is similar the blocks variable holds list of data structures representing blocks to be drawn to the screenand these are drawn to the screen inside the game loop but without calls to input()how do we get input from the playerin our next we will cover how programs can know when the player presses keys on the keyboard we will also learn of concept called collision detection
7,744
collision detection and keyboard/mouse input topics covered in this collision detection don' modify list while iterating over it keyboard input in pygame mouse input in pygame collision detection is figuring when two things on the screen have touched (that iscollided witheach other for exampleif the player touches an enemy they may lose health or the program needs to know when the player touches coin so that they automatically pick it up collision detection can help determine if the game character is standing on solid ground or if there' nothing but empty air underneath them in our gamescollision detection will determine if two rectangles are overlapping each other or not our next example program will cover this basic technique later in this we'll look at how our pygame programs can accept input from the user through the keyboard and the mouse it' bit more complicated than calling the input(function like we did for our text programs but using the keyboard is much more interactive in gui programs and using the mouse isn' even possible in our text games these two concepts will make your games more excitingsource code of the collision detection program much of this code is similar to the animation programso the explanation of the moving and bouncing code is skipped (see the animation program in for that bouncer will bounce around the window list of rect objects will represent food squares on each iteration through the game loopthe program will read each rect object in the list and draw green square on the window every forty iterations through the game loop we will add new rect object to the list so that the screen constantly has new food squares in it post questions to
7,745
the bouncer is represented by dictionary the dictionary has key named 'rect(whose value is pygame rect objectand key named 'dir(whose value is one of the constant direction variables like we had in last animation programas the bouncer bounces around the windowwe check if it collides with any of the food squares if it doeswe delete that food square so that it will no longer be drawn on the screen this will make it look like the bouncer "eatsthe food squares in the window type the following into new file and save it as collisiondetection py if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at collisiondetection py import pygamesysrandom from pygame locals import def dorectsoverlap(rect rect ) for ab in [(rect rect )(rect rect )] check if ' corners are inside if ((ispointinsiderect( lefta topb)or (ispointinsiderect( lefta bottomb)or (ispointinsiderect( righta topb)or (ispointinsiderect( righta bottomb))) return true return false def ispointinsiderect(xyrect) if ( rect leftand ( rect topand ( rect bottom) return true else return false set up pygame pygame init( mainclock pygame time clock( set up the window windowwidth windowheight windowsurface pygame display set_mode((windowwidthwindowheight) pygame display set_caption('collision detection'
7,746
set up direction variables downleft downright upleft upright movespeed set up the colors black ( green ( white ( set up the bouncer and food data structures foodcounter newfood foodsize bouncer {'rect':pygame rect( )'dir':upleft foods [ for in range( ) foods append(pygame rect(random randint( windowwidth foodsize)random randint( windowheight foodsize)foodsizefoodsize) run the game loop while true check for the quit event for event in pygame event get() if event type =quit pygame quit( sys exit( foodcounter + if foodcounter >newfood add new food foodcounter foods append(pygame rect(random randint( windowwidth foodsize)random randint( windowheight foodsize)foodsizefoodsize) draw the black background onto the surface windowsurface fill(black move the bouncer data structure if bouncer['dir'=downleft bouncer['rect'left -movespeed bouncer['rect'top +movespeed if bouncer['dir'=downright bouncer['rect'left +movespeed post questions to
7,747
bouncer['rect'top +movespeed if bouncer['dir'=upleftbouncer['rect'left -movespeed bouncer['rect'top -movespeed if bouncer['dir'=uprightbouncer['rect'left +movespeed bouncer['rect'top -movespeed check if the bouncer has move out of the window if bouncer['rect'top bouncer has moved past the top if bouncer['dir'=upleftbouncer['dir'downleft if bouncer['dir'=uprightbouncer['dir'downright if bouncer['rect'bottom windowheightbouncer has moved past the bottom if bouncer['dir'=downleftbouncer['dir'upleft if bouncer['dir'=downrightbouncer['dir'upright if bouncer['rect'left bouncer has moved past the left side if bouncer['dir'=downleftbouncer['dir'downright if bouncer['dir'=upleftbouncer['dir'upright if bouncer['rect'right windowwidthbouncer has moved past the right side if bouncer['dir'=downrightbouncer['dir'downleft if bouncer['dir'=uprightbouncer['dir'upleft draw the bouncer onto the surface pygame draw rect(windowsurfacewhitebouncer['rect']check if the bouncer has intersected with any food squares for food in foods[:]if dorectsoverlap(bouncer['rect']food)foods remove(fooddraw the food for in range(len(foods))pygame draw rect(windowsurfacegreenfoods[ ]draw the window onto the screen
7,748
pygame display update(mainclock tick( the program will look like figure - the the bouncer square will bounce around the window when it collides with the green food squares they will disappear from the screen figure - an altered screenshot of the collision detection program importing the modules import pygamesysrandom from pygame locals import the collision detection program imports the same things as the animation program in the last along with the random module the collision detection algorithm def dorectsoverlap(rect rect )to do collision detectionyou need function that can determine if two rectangles collide with each other or not figure - shows colliding and non-colliding rectangles figure - examples of colliding rectangles (leftand rectangles that don' collide (rightpost questions to
7,749
dorectsoverlap(is passed two pygame rect objects the function will return true if they do and false if they don' there is simple rule to follow to determine if rectangles collide look at each of the four corners on both rectangles if at least one of these eight corners is inside the other rectanglethen you know that the two rectangles have collided you can use this fact to determine if dorectsoverlap(returns true or false for ab in [(rect rect )(rect rect )]check if ' corners are inside if ((ispointinsiderect( lefta topb)or (ispointinsiderect( lefta bottomb)or (ispointinsiderect( righta topb)or (ispointinsiderect( righta bottomb)))return true lines to check if one rectangle' corners are inside another later you will create function called ispointinsiderect(that returns true if the xy coordinates of the point are inside the rectangle call this function for each of the eight cornersand if any of these calls return truethe or operators will make the entire condition true the parameters for dorectsoverlap(are rect and rect first check if rect ' corners are inside rect then check if rect ' corners are in rect you don' need to repeat the code that checks all four corners for both rect and rect insteaduse and on lines to the for loop on line uses multiple assignment on the first iterationa is set to rect and is set to rect on the second iteration through the loopit is the oppositea is set to rect and is set to rect return false line never returns truethen none of the eight corners checked are in the other rectangle in that casethe rectangles didn' collide and line returns false determining if point is inside rectangle def ispointinsiderect(xyrect) if ( rect leftand ( rect topand ( rect bottom) return true the ispointinsiderect(function is called from dorectsoverlap(the ispointinsiderect(function will return true if the xy coordinates passed are located inside the pygame rect object passed as the third parameter otherwisethis function returns false
7,750
figure - is an example picture of rectangle and several points the points and the corners of the rectangle are labeled with coordinates point is inside the rectangle if the following four things are truethe point' -coordinate is greater than the -coordinate of the rectangle' left side the point' -coordinate is less than the -coordinate of the rectangle' right side the point' -coordinate is greater than the -coordinate of the rectangle' top side the point' -coordinate is less than the -coordinate of the rectangle' bottom side if any of those parts are falsethen the point is outside the rectangle line combines all four of these conditions into the if statement' condition with and operators figure - example of coordinates inside and outside of rectangle the ( )( and ( points are inside the rectangleand all the others are outside elsereturn false this function is called from the dorectsoverlap(function to see if any of the corners in the two pygame rect objects are inside each other these two functions give you the power to do collision detection between two rectangles the pygame time clock object and tick(method much of lines to do the same things that the animation program in the last didinitialize pygameset windowheight and windowwidthand assign the color and direction constants howeverline is new mainclock pygame time clock(post questions to
7,751
in the previous animation programa call to time sleep( would slow down the program so that the program doesn' run too fast the problem with time sleep()is that might be too much of pause on slow computers and not enough of pause on fast computers pygame time clock object can pause an appropriate amount of time on any computer line calls mainclock tick( inside the game loop this call to the clock object' tick(method waits enough time so that it runs at about iterations secondno matter what the computer' speed is this ensures that the game never runs faster than you expect call to tick(should only appear once in the game loop setting up the window and data structures set up the bouncer and food data structures foodcounter newfood foodsize lines to set up few variables for the food blocks that appear on the screen foodcounter will start at the value newfood at and foodsize at bouncer {'rect':pygame rect( )'dir':upleftline sets up new data structure called bouncer bouncer is dictionary with two keys the 'rectkey has pygame rect object that represents the bouncer' size and position the 'dirkey has direction that the bouncer is currently moving the bouncer will move the same way the blocks did in ' animation program foods [ for in range( ) foods append(pygame rect(random randint( windowwidth foodsize)random randint( windowheight foodsize)foodsizefoodsize)the program will keep track of every food square with list of rect objects in foods lines and create twenty food squares randomly placed around the screen you can use the random randint(function to come up with random xy coordinates on line we will call the pygame rect(constructor function to return new pygame rect object it will represent the position and size of the food square the first two parameters for pygame rect(are the xy coordinates of the top left corner you want the random coordinate to be between and the size of the window minus the size of the food square if you had the random
7,752
coordinate between and the size of the windowthen the food square might be pushed outside of the window altogetherlike in figure - figure - for by rectanglehaving the top left corner at ( in by window would place the rectangle outside of the window to be insidethe top left corner should be at ( instead the third parameter for pygame rect(is tuple that contains the width and height of the food square both the width and height is the value in the foodsize constant drawing the bouncer on the screen lines to cause the bouncer to move around the window and bounce off of the edges of the window this code is similar to lines to of the animation program in the last so the explanation will be skipped draw the bouncer onto the surface pygame draw rect(windowsurfacewhitebouncer['rect']after moving the bouncerline draws it in its new position the windowsurface passed for the first parameter tells python which surface object to draw the rectangle on the white variablewhich has ( stored in itwill tell python to draw white rectangle the rect object stored in the bouncer dictionary at the 'rectkey tells the position and size of the rectangle to draw colliding with the food squares check if the bouncer has intersected with any food squares for food in foods[:]post questions to
7,753
before drawing the food squarescheck if the bouncer has overlapped any of the food squares if it hasremove that food square from the foods list this waypython won' draw any food squares that the bouncer has "eatenon each iteration through the for loopthe current food square from the foods (plurallist is in the variable food (singulardon' add to or delete from list while iterating over it notice that there' slight difference with this for loop if you look carefully at line it isn' iterating over foods but actually over foods[:remember how slices work foods[: evaluates to copy of the list with the items from the start and up to (but not includingthe item at index foods[ :evaluates to copy of the list with the items from index to the end of the list foods[:will give you copy of the list with the items from the start to the end basicallyfoods[:creates new list with copy of all the items in foods this is shorter way to copy list thansaywhat the getboardcopy(function does in the previous tic tac toe game you cannot add or remove items from list while you are iterating over it python can lose track of what the next value of food variable should be if the size of the foods list is always changing think of how difficult it would be to count the number of jelly beans in jar while someone was adding or removing jelly beans but if you iterate over copy of the list (and the copy never changes)adding or removing items from the original list won' be problem removing the food squares if dorectsoverlap(bouncer['rect']food)foods remove(foodline is where dorectsoverlap(comes in handy if the bouncer and the current food square two rectangles overlapthen dorectsoverlap(will return true and line removes the overlapping food square from the foods list drawing the food squares on the screen draw the food for in range(len(foods))pygame draw rect(windowsurfacegreenfoods[ ]
7,754
the code on lines and are similar to how we drew the white square for the player line loops through each food square in the foods list line draws the food square onto the windowsurface surface this program was similar to the bouncing program in the previous except now the bouncing square will "eatother squares it passes over them these past few programs are interesting to watchbut the user doesn' get to control anything in the next programwe will learn how to get input from the keyboard source code of the keyboard input program start new file and type in the following codethen save it as pygameinput py if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at pygameinput py import pygamesysrandom from pygame locals import set up pygame pygame init( mainclock pygame time clock( set up the window windowwidth windowheight windowsurface pygame display set_mode((windowwidthwindowheight) pygame display set_caption('input' set up the colors black ( green ( white ( set up the player and food data structure foodcounter newfood foodsize player pygame rect( foods [ for in range( ) foods append(pygame rect(random randint( windowwidth foodsize)random randint( windowheight foodsize)foodsizefoodsize) set up movement variables post questions to
7,755
moveleft false moveright false moveup false movedown false movespeed run the game loop while true check for events for event in pygame event get() if event type =quit pygame quit( sys exit( if event type =keydown change the keyboard variables if event key =k_left or event key =ord(' ') moveright false moveleft true if event key =k_right or event key =ord(' ') moveleft false moveright true if event key =k_up or event key =ord(' ') movedown false moveup true if event key =k_down or event key =ord(' ') moveup false movedown true if event type =keyup if event key =k_escape pygame quit( sys exit( if event key =k_left or event key =ord(' ') moveleft false if event key =k_right or event key =ord(' ') moveright false if event key =k_up or event key =ord(' ') moveup false if event key =k_down or event key =ord(' ') movedown false if event key =ord(' ') player top random randint( windowheight player height player left random randint( windowwidth player width
7,756
if event type =mousebuttonup foods append(pygame rect(event pos[ ]event pos[ ]foodsizefoodsize) foodcounter + if foodcounter >newfood add new food foodcounter foods append(pygame rect(random randint( windowwidth foodsize)random randint( windowheight foodsize)foodsizefoodsize) draw the black background onto the surface windowsurface fill(black move the player if movedown and player bottom windowheight player top +movespeed if moveup and player top player top -movespeed if moveleft and player left player left -movespeed if moveright and player right windowwidth player right +movespeed draw the player onto the surface pygame draw rect(windowsurfacewhiteplayer check if the player has intersected with any food squares for food in foods[:] if player colliderect(food) foods remove(food draw the food for in range(len(foods)) pygame draw rect(windowsurfacegreenfoods[ ] draw the window onto the screen pygame display update( mainclock tick( this program is almost identical to the collision detection program but in this programthe bouncer only moves around when the user holds down the arrow keys on the keyboard you can also click anywhere in the window and create new food objects in additionthe esc key will quit the program and the "xkey will teleport the player to random place on the screen post questions to
7,757
setting up the window and data structures starting at line the code sets up some variables that track the movement of the bouncer set up movement variables moveleft false moveright false moveup false movedown false the four variables have boolean values to keep track of which of the arrow keys are being held down for examplewhen the user pushes the left arrow key on their keyboardmoveleft is set to true when they let go of the keymoveleft is set back to false lines to are identical to code in the previous pygame programs these lines handle the start of the game loop and what to do when the user quits the program we'll skip the explanation for this code here since we have already covered it in the last events and handling the keydown event the code to handle the key press and key release events start on line at the start of the programthey are all set to false if event type =keydownpygame has an event type called keydown this is one of the other events that pygame can generate brief list of the events that could be returned by pygame event get(is in table table - events and when they are generated
7,758
event type quit description generated when the user closes the window keydown generated when the user presses down key has key attribute that tells which key was pressed also has mod attribute that tells if the shiftctrlaltor other keys were held down when this key was pressed keyup generated when the user releases key has key and mod attribute that are similar to those for keydown mousemotion generated whenever the mouse moves over the window has pos attribute that returns tuple (xyfor the coordinates of where the mouse is in the window the rel attribute also returns (xytuplebut it gives coordinates relative since the last mousemotion event for exampleif the mouse moves left by four pixels from ( to ( )then rel will be the tuple value (- the buttons attribute returns tuple of three integers the first integer in the tuple is for the left mouse buttonthe second integer for the middle mouse button (if there' middle mouse button)and the third integer is for the right mouse button these integers will be if they are not being pressed down when the mouse moved and if they are pressed down mousebuttondown generated when mouse button is pressed down in the window this event has pos attribute which is an (xytuple for the coordinates of where the mouse was when the button was pressed there is also button attribute which is an integer from to that tells which mouse button was pressedexplained in table - mousebuttonup generated when the mouse button is released this has the same attributes as mousebuttondown post questions to
7,759
table - the button attribute values and mouse button value of button mouse button left button middle button right button scroll wheel moved up scroll wheel moved down setting the four keyboard variables change the keyboard variables if event key =k_left or event key =ord(' ')moveright false moveleft true if event key =k_right or event key =ord(' ')moveleft false moveright true if event key =k_up or event key =ord(' ')movedown false moveup true if event key =k_down or event key =ord(' ')moveup false movedown true if the event type is keydownthen the event object will have key attribute that tells which key was pressed down line compares this attribute to k_leftwhich is the pygame locals constant that represents the left arrow key on the keyboard lines to do similar checks for each of the other arrow keysk_leftk_rightk_upk_down when one of these keys is pressed downset the corresponding movement variable to true alsoset the movement variable of the opposite direction to false for examplethe program executes lines and when the left arrow key has been pressed in this caseset moveleft to true and moveright to false (even though moveright might already be falseset it to false just to be sureon line in event key can either be equal to k_left or ord(' 'the value in event key is set to the integer ordinal value of the key that was pressed on the keyboard (there is no ordinal
7,760
value for the arrow keyswhich is why we use the constant variable k_left you can use the ord(function to get the ordinal value of any single character to compare it with event key by executing the code on lines and if the keystroke was either k_left or ord(' ')you make the left arrow key and the key do the same thing the wasand keys are all used as alternates for changing the movement variables the wasd (pronounced "wazz-dee"keys let you use your left hand the arrow keys can be pressed with your right hand figure - the wasd keys can be programmed to do the same thing as the arrow keys handling the keyup event if event type =keyupwhen the user releases the key that they are holding downa keyup event is generated if event key =k_escapepygame quit(sys exit(if the key that the user released was the esc keythen terminate the program rememberin pygame you must call the pygame quit(function before calling the sys exit(function lines to will set movement variable to false if that direction' key was let go if event key =k_left or event key =ord(' ')moveleft false if event key =k_right or event key =ord(' ')moveright false if event key =k_up or event key =ord(' ')moveup false if event key =k_down or event key =ord(' ')movedown false teleporting the player if event key =ord(' ')post questions to
7,761
player height player width player top random randint( windowheight player left random randint( windowwidth you can also add teleportation to the game if the user presses the "xkeythen lines and will set the position of the user' square to random place on the window this will give the user the ability to teleport around the window by pushing the "xkey although they can' control where they will teleportit' completely random handling the mousebuttonup event foodsize)if event type =mousebuttonupfoods append(pygame rect(event pos[ ]event pos[ ]foodsizemouse input is handled by events just like keyboard input is the mousebuttonup event occurs when the user releases the mouse button after clicking it the pos attribute in the event object is set to tuple of two integers for the xy coordinates for where the mouse cursor was at the time of the click on line the -coordinate is stored in event pos[ and the -coordinate is stored in event pos[ line creates new rect object to represent new food and place it where the mousebuttonup event occurred by adding new rect object to the foods listthe code will display new food square is displayed on the screen moving the player around the screen move the player if movedown and player bottom windowheightplayer top +movespeed if moveup and player top player top -movespeed if moveleft and player left player left -movespeed if moveright and player right windowwidthplayer right +movespeed you've set the movement variables (movedownmoveupmoveleftand moverightto true or false depending on what keys the user has pressed now move the player' square (which is represented by the pygame rect object stored in playerby adjusting xy coordinates of player
7,762
if movedown is set to true (and the bottom of the player' square isn' below the bottom edge of the window)then line moves the player' square down by adding movespeed to the player' current top attribute lines to do the same thing for the other three directions the colliderect(method check if the player has intersected with any food squares for food in foods[:]if player colliderect(food)foods remove(foodin the previous collision detection programthe dorectsoverlap(function to check if one rectangle had collided with another that function was included in this book so you could understand how the code behind collision detection works in this programyou can use the collision detection function that comes with pygame the colliderect(method for pygame rect objects is passed another pygame rect object as an argument and returns true if the two rectangles collide and false if they do not mainclock tick( the rest of the code is similar to the code in the input and collision detection programs summary this introduced the concept of collision detectionwhich is in many graphical games detecting collisions between two rectangles is easycheck if the four corners of either rectangle are within the other rectangle this is such common thing to check for that pygame provides its own collision detection method named colliderect(for pygame rect objects the first several games in this book were text-based the program output was text printed to the screen and the input was text typed by the user on the keyboard but graphical programs can accept keyboard and mouse inputs furthermorethese programs can respond to single keystrokes when the user pushes down or lets up single key the user doesn' have to type in an entire response and press enter this allows for immediate feedback and much more interactive games post questions to
7,763
sounds and images topics covered in this sound and image files drawing sprites the pygame image load(function the pygame mixer sound data type the pygame mixer music module in the last two we've learned how to make gui programs that have graphics and can accept input from the keyboard and mouse we've also learned how to draw different shapes in this we will learn how to show pictures and images (called spritesand play sounds and music in our games sprite is name for single two-dimensional image that is used as part of the graphics on the screen figure - shows some example sprites figure - some examples of sprites figure - shows being used in complete scene
7,764
figure - an example of complete scenewith sprites drawn on top of background the sprite images are drawn on top of background notice that you can flip the sprite image horizontally so that the sprites are facing the other way you can draw the same sprite image multiple times on the same window you can also resize the sprites to be larger or smaller than the original sprite image the background image can be considered one large sprite the next program will demonstrate how to play sounds and draw sprites using pygame sound and image files sprites are stored in image files on your computer there are several different image formats that pygame can use you can tell what format an image file uses by looking at the end of the file name (after the last periodthis is called the file extension for examplethe file player png is in the png format the image formats pygame supports include bmppngjpgand gif you can download images from your web browser on most web browsersyou have to rightclick on the image in the web page and select save from the menu that appears remember where on the hard drive you saved the image file copy this downloaded image file into the same folder as you python program' py file you can also create your own images with drawing program like ms paint or tux paint the sound file formats that pygame supports are midwavand mp you can download sound effects from the internet just like image files they must be in one of these three formats if post questions to
7,765
your computer has microphoneyou can also record sounds and make your own wav files to use in your games sprites and sounds program this program is the same as the keyboard and mouse input program from the last howeverin this program we will use sprites instead of plain looking squares we will use sprite of little person instead of the white player squareand sprite of cherries instead of the green food squares we also play background music and sound effect when the player sprite eats one of the cherry sprites source code of the sprites and sounds program if you know how to use graphics software such as photoshop or ms paintyou can draw your own images if you don' know how to use these programsyou can download graphics from websites and use those image files instead the same applies for music and sound files you can also find images on websites or images from digital camera you can download the image and sound files from this book' website at if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at spritesandsounds py import pygamesystimerandom from pygame locals import set up pygame pygame init( mainclock pygame time clock( set up the window windowwidth windowheight windowsurface pygame display set_mode((windowwidthwindowheight) pygame display set_caption('sprites and sound' set up the colors black ( set up the block data structure player pygame rect( playerimage pygame image load('player png'
7,766
playerstretchedimage pygame transform scale(playerimage( ) foodimage pygame image load('cherry png' foods [ for in range( ) foods append(pygame rect(random randint( windowwidth )random randint( windowheight ) ) foodcounter newfood set up keyboard variables moveleft false moveright false moveup false movedown false movespeed set up music pickupsound pygame mixer sound('pickup wav' pygame mixer music load('background mid' pygame mixer music play(- musicplaying true run the game loop while true check for the quit event for event in pygame event get() if event type =quit pygame quit( sys exit( if event type =keydown change the keyboard variables if event key =k_left or event key =ord(' ') moveright false moveleft true if event key =k_right or event key =ord(' ') moveleft false moveright true if event key =k_up or event key =ord(' ') movedown false moveup true if event key =k_down or event key =ord(' ') moveup false movedown true if event type =keyup if event key =k_escapepost questions to
7,767
pygame quit( sys exit( if event key =k_left or event key =ord(' ') moveleft false if event key =k_right or event key =ord(' ') moveright false if event key =k_up or event key =ord(' ') moveup false if event key =k_down or event key =ord(' ') movedown false if event key =ord(' ') player top random randint( windowheight player height player left random randint( windowwidth player width if event key =ord(' ') if musicplaying pygame mixer music stop( else pygame mixer music play(- musicplaying not musicplaying if event type =mousebuttonup foods append(pygame rect(event pos[ event pos[ ) foodcounter + if foodcounter >newfood add new food foodcounter foods append(pygame rect(random randint( windowwidth )random randint( windowheight ) ) draw the black background onto the surface windowsurface fill(black move the player if movedown and player bottom windowheight player top +movespeed if moveup and player top player top -movespeed if moveleft and player left player left -movespeed if moveright and player right windowwidth player right +movespeed
7,768
draw the block onto the surface windowsurface blit(playerstretchedimageplayer check if the block has intersected with any food squares for food in foods[:] if player colliderect(food) foods remove(food player pygame rect(player leftplayer topplayer width player height playerstretchedimage pygame transform scale(playerimage(player widthplayer height) if musicplaying pickupsound play( draw the food for food in foods windowsurface blit(foodimagefood draw the window onto the screen pygame display update( mainclock tick( figure - an altered screenshot of the sprites and sounds game setting up the window and the data structure most of the code in this program is the same as the collision detection program in the previous we'll focus only on the parts that add sprites and sound pygame display set_caption('sprites and sound'post questions to
7,769
firstlet' set the caption of the title bar to string that describes this program on line pass the string 'sprites and soundto the pygame display set_caption(function set up the block data structure player pygame rect( playerimage pygame image load('player png' playerstretchedimage pygame transform scale(playerimage( ) foodimage pygame image load('cherry png'we are going to use three different variables to represent the playerunlike the previous programs that just used one the player variable on line will store rect object that keeps track of where and how big the player is the player variable doesn' contain the player' imageonly the player' size and location at the beginning of the programthe top left corner of the player is located at ( and the player will have height and width of pixels to start the second variable on line that represents the player is playerimage the pygame image load(function is passed string of the filename of the image to load the return value is surface object that has the graphics in the image file drawn on its surface we store this surface object inside of playerimage the third variable is explained in the next section the pygame transform scale(function on line we will use new function in the pygame transform module the pygame transform scale(function can shrink or enlarge sprite the first argument is pygame surface object with the image drawn on it the second argument is tuple for the new width and height of the image in the first argument the pygame transform scale(function returns pygame surface object with the image drawn at new size we will store the original image in the playerimage variable but the stretched image in the playerstretchedimage variable on line we call pygame image load(again to create surface object with the cherry image drawn on it be sure you have the player png and cherry png files in the same directory as the spritesandsounds py fileotherwise pygame won' be able to find them and will give an error setting up the music and sounds set up music pickupsound pygame mixer sound('pickup wav' pygame mixer music load('background mid'
7,770
pygame mixer music play(- musicplaying true next you need to load the sound files there are two modules for sound in pygame the pygame mixer module can play short sound effects during the game the pygame mixer music module can play background music call the pygame mixer sound(constructor function to create pygame mixer sound object (called sound object for shortthis object has play(method that when called will play the sound effect when called line calls pygame mixer music load(to load the background music line calls pygame mixer music play(to start playing the background music the first parameter tells pygame how many times to play the background music after the first time we play it so passing will cause pygame to play the background music times - is special valueand passing it for the first parameter makes the background music repeat forever the second parameter to pygame mixer music play(is the point in the sound file to start playing passing will play the background music starting from the beginning passing for the second parameter will start the background music two and half seconds from the beginning finallythe musicplaying variable will have boolean value that tells the program if it should play the background music and sound effects or not it' nice to give the player the option to run the program without the sound playing toggling the sound on and off if event key =ord(' ')if musicplayingpygame mixer music stop(elsepygame mixer music play(- musicplaying not musicplaying the key will turn the background music on or off if musicplaying is set to truethen the background music is currently playing and we should stop the music by calling pygame mixer music stop(if musicplaying is set to falsethen the background music isn' currently playing and should be started by calling pygame mixer music play(finallyno matter whatwe want to toggle the value in musicplaying toggling boolean value means to set to the opposite of its current value the line musicplaying not musicplaying sets the variable to false if it is currently true or sets it to true if it is currently false think of post questions to
7,771
toggling as what happens when you flip light switch on or offtoggling the light switch sets it to the opposite setting drawing the player on the window draw the block onto the surface windowsurface blit(playerstretchedimageplayerremember that the value stored in playerstretchedimage is surface object line draws the sprite of the player onto the window' surface object (which is stored in windowsurfacethe second parameter to the blit(method is rect object that specifies where on the surface object the sprite should be blitted the rect object stored in player is what keeps track of the position of the player in the window checking if the player has collided with cherries if player colliderect(food) foods remove(food player pygame rect(player leftplayer topplayer width player height playerstretchedimage pygame transform scale(playerimage(player widthplayer height) if musicplaying pickupsound play(this code is similar to the code in the previous programs but there are couple of new lines call the play(method on the sound object stored in the pickupsound variable but only do this if musicplaying is set to true (which means that the sound is turned onwhen the player eats one of the cherriesthe size of the player increases by two pixels in height and width on line new rect object that is pixels larger than the old rect object will be the new value of player while the rect object represents the position and size of the playerthe image of the player is stored in playerstretchedimage as surface object create new stretched image by calling pygame transform scale(be sure to pass the original surface object in playerimage and not playerstretchedimage stretching an image often distorts it little if you keep restretching stretched image over and overthe distortions add up quickly but by stretching the original image to the new sizeyou only distort the image once this is why you pass playerimage as the first argument for pygame transform scale(
7,772
draw the cherries on the window draw the food for food in foodswindowsurface blit(foodimagefoodin the previous programsyou called the pygame draw rect(function to draw green square for each rect object stored in the foods list howeverin this program you want to draw the cherry sprites instead call the blit(method and pass the surface object stored in foodimage (this is the surface object with the image of cherries drawn on it the food variable (which contains each of the rect objects in foods on each iteration through the for looptells the blit(method where to draw the foodimage summary this game has added images and sound to your games the images (called spriteslook much better than the simple shape drawing used in the previous programs the game presented in this also has music playing in the background while also playing sound effects sprites can be scaled (that isstretchedto larger or smaller size this way we can display sprites at any size we want this will come in handy in the game presented in the next now that we know how to create windowdisplay sprites and drawing primitivescollect keyboard and mouse inputplay soundsand implement collision detectionwe are now ready to create graphical game in pygame the next brings all of these elements together for our most advanced game yet post questions to
7,773
dodger topics covered in this the pygame fullscreen flag pygame constant variables for keyboard keys the move_ip()rect method the pygame mouse set_pos(function implementing cheat codes modifying the dodger game the last three went over the pygame module and demonstrated how to use its many features in this we'll use that knowledge to create graphical game called dodger the dodger game has the player control small person (which we call the player' characterwho must dodge whole bunch of baddies that fall from the top of the screen the longer the player can keep dodging the baddiesthe higher the score they will get just for funwe'll also add some cheat modes to the game if the player holds down the "xkeyevery baddie' speed is reduced to super slow rate if the player holds down the "zkeythe baddies will reverse their direction and travel up the screen instead of downwards review of the basic pygame data types let' review some of the basic data types used in pygamepygame rect rect objects represent rectangular space' location and size the location can be determined by the rect object' topleft attribute (or the toprightbottomleftand bottomright attributesthese corner attributes are tuple of integers for the xand -coordinates the size can be determined by the width and height attributeswhich are integers of how many pixels long or high the rectangle area is rect objects have colliderect(method to check if they are colliding with another rect object pygame surface surface objects are areas of colored pixels surface objects represent rectangular imagewhile rect objects only represent rectangular space and location surface objects have blit(method that is used to draw the image on one surface object onto another surface object the surface object returned by the
7,774
pygame display set_mode(function is special because anything drawn on that surface object is displayed on the user' screen when pygame display update(is called pygame event event the pygame event module generates event objects whenever the user provides keyboardmouseor another kind of input the pygame event get(function returns list of these event objects you can check what type of event the event object is by checking its type attribute quitkeydownand mousebuttonup are examples of some event types pygame font font the pygame font module has the font data type which represents the typeface used for text in pygame the arguments to pass to pygame font sysfont(are string of the font name and an integer of the font size however it is common to pass none for the font name to get the default system font pygame time clock the clock object in the pygame time module is helpful for keeping our games from running as fast as possible the clock object has tick(methodwhich we pass how many frames per second (fpswe want the game to run at the higher the fpsthe faster the game runs type in the following code and save it to file named dodger py this game also requires some other image and sound fileswhich you can download from the url source code of dodger you can download this code from the url this code incompare the code you typed to the book' code with the online diff tool at import pygamerandomsys from pygame locals import windowwidth windowheight textcolor ( backgroundcolor ( fps baddieminsize baddiemaxsize baddieminspeed baddiemaxspeed addnewbaddierate playermoverate def terminate()post questions to
7,775
pygame quit( sys exit( def waitforplayertopresskey() while true for event in pygame event get() if event type =quit terminate( if event type =keydown if event key =k_escapepressing escape quits terminate( return def playerhashitbaddie(playerrectbaddies) for in baddies if playerrect colliderect( ['rect']) return true return false def drawtext(textfontsurfacexy) textobj font render(text textcolor textrect textobj get_rect( textrect topleft (xy surface blit(textobjtextrect set up pygamethe windowand the mouse cursor pygame init( mainclock pygame time clock( windowsurface pygame display set_mode((windowwidthwindowheight) pygame display set_caption('dodger' pygame mouse set_visible(false set up fonts font pygame font sysfont(none set up sounds gameoversound pygame mixer sound('gameover wav' pygame mixer music load('background mid' set up images playerimage pygame image load('player png' playerrect playerimage get_rect( baddieimage pygame image load('baddie png' show the "startscreen drawtext('dodger'fontwindowsurface(windowwidth )(windowheight )
7,776
drawtext('press key to start 'fontwindowsurface(windowwidth (windowheight pygame display update( waitforplayertopresskey( topscore while true set up the start of the game baddies [ score playerrect topleft (windowwidth windowheight moveleft moveright moveup movedown false reversecheat slowcheat false baddieaddcounter pygame mixer music play(- while truethe game loop runs while the game part is playing score + increase score for event in pygame event get() if event type =quit terminate( if event type =keydown if event key =ord(' ') reversecheat true if event key =ord(' ') slowcheat true if event key =k_left or event key =ord(' ') moveright false moveleft true if event key =k_right or event key =ord(' ') moveleft false moveright true if event key =k_up or event key =ord(' ') movedown false moveup true if event key =k_down or event key =ord(' ') moveup false movedown true if event type =keyup if event key =ord(' ') reversecheat false score if event key =ord(' ')post questions to
7,777
slowcheat false score if event key =k_escape terminate( if event key =k_left or event key =ord(' ') moveleft false if event key =k_right or event key =ord(' ') moveright false if event key =k_up or event key =ord(' ') moveup false if event key =k_down or event key =ord(' ') movedown false if event type =mousemotion if the mouse movesmove the player where the cursor is playerrect move_ip(event pos[ playerrect centerxevent pos[ playerrect centery add new baddies at the top of the screenif needed if not reversecheat and not slowcheat baddieaddcounter + if baddieaddcounter =addnewbaddierate baddieaddcounter baddiesize random randint(baddieminsizebaddiemaxsize newbaddie {'rect'pygame rect(random randint( windowwidth-baddiesize) baddiesizebaddiesizebaddiesize) 'speed'random randint(baddieminspeedbaddiemaxspeed) 'surface':pygame transform scale(baddieimage(baddiesizebaddiesize)) baddies append(newbaddie move the player around if moveleft and playerrect left playerrect move_ip(- playermoverate if moveright and playerrect right windowwidth playerrect move_ip(playermoverate if moveup and playerrect top playerrect move_ip( - playermoverate if movedown and playerrect bottom windowheight playerrect move_ip( playermoverate move the mouse cursor to match the player pygame mouse set_pos(playerrect centerxplayerrect centery
7,778
move the baddies down for in baddies if not reversecheat and not slowcheat ['rect'move_ip( ['speed'] elif reversecheat ['rect'move_ip( - elif slowcheat ['rect'move_ip( delete baddies that have fallen past the bottom for in baddies[:] if ['rect'top windowheight baddies remove( draw the game world on the window windowsurface fill(backgroundcolor draw the score and top score drawtext('score% (score)fontwindowsurface drawtext('top score% (topscore)fontwindowsurface draw the player' rectangle windowsurface blit(playerimageplayerrect draw each baddie for in baddies windowsurface blit( ['surface'] ['rect'] pygame display update( check if any of the baddies have hit the player if playerhashitbaddie(playerrectbaddies) if score topscore topscore score set new top score break mainclock tick(fps stop the game and show the "game overscreen pygame mixer music stop( gameoversound play( drawtext('game over'fontwindowsurface(windowwidth )(windowheight )post questions to
7,779
drawtext('press key to play again 'fontwindowsurface(windowwidth (windowheight pygame display update( waitforplayertopresskey( gameoversound stop(when you run this programthe game will look like figure - figure - an altered screenshot of the dodger game importing the modules import pygamerandomsys from pygame locals import the dodger game imports the same modules previous pygame programs havepygamerandomsysand pygame locals the pygame locals module contains several constant variables that pygame uses such as the event types (quitkeydownetc and keyboard keys (k_escapek_leftetc by using the from pygame locals import syntaxyou can just type quit in the source code instead of pygame locals quit setting up the constant variables windowwidth windowheight
7,780
textcolor ( backgroundcolor ( the constant variables on lines to are much more descriptive than typing out the values for examplefrom the line windowsurface fill(backgroundcoloris more understandable than windowsurface fill(( )you can easily change the game by changing the constant variables by changing windowwidth on line you automatically change the code everywhere windowwidth is used if you had used the value insteadthen you would have to change each occurrence of in the code it is easier to change the value in the constant once fps the mainclock tick(method call on line will slow the game down enough to be playable you pass an integer to mainclock tick(so that the function knows how long to pause the program this integer (which you store in fpsis the number of frames per second you want the game to run "frameis the drawing of graphics on the screen for single iteration through the game loop you can set fps to and always call mainclock tick(fpsthen you can change fps to higher value to have the game run faster or lower value to slow the game down baddieminsize baddiemaxsize baddieminspeed baddiemaxspeed addnewbaddierate lines to set some more constant variables that will describe the falling baddies the width and height of the baddies will be between baddieminsize and baddiemaxsize the rate at which the baddies fall down the screen will be between baddieminspeed and baddiemaxspeed pixels per iteration through the game loop and new baddie will be added to the top of the window every addnewbaddierate iterations through the game loop playermoverate the playermoverate will store the number of pixels the player' character moves in the window on each iteration through the game loop if the character is moving by increasing this numberyou can increase the speed the character moves post questions to
7,781
defining functions there are several functions you'll create for the game def terminate() pygame quit( sys exit(pygame requires that you call both pygame quit(and sys exit(put them both into function called terminate(now you only need to call terminate()instead of both of the pygame quit(and sys exit(functions def waitforplayertopresskey() while true for event in pygame event get()sometimes you'll want to pause the game until the player presses key create new function called waitforplayertopresskey(inside this functionthere' an infinite loop that only breaks when keydown or quit event is received at the start of the looppygame event get(to return list of event objects to check out if event type =quitterminate(if the player has closed the window while the program is waiting for the player to press keypygame will generate quit event in that casecall the terminate(function on line if event type =keydownif event key =k_escapepressing escape quits terminate(return if you receive keydown eventthen you should first check if it is the esc key that was pressed if the player presses the esc keythe program should terminate if that wasn' the casethen execution will skip the if-block on line and go straight to the return statementwhich exits the waitforplayertopresskey(function if quit or keydown event isn' generatedthen the code keeps looping since the loop does nothingthis will make it look like the game has frozen until the player presses key def playerhashitbaddie(playerrectbaddies) for in baddies
7,782
if playerrect colliderect( ['rect'])return true return false the playerhashitbaddie(function will return true if the player' character has collided with one of the baddies the baddies parameter is list of "baddiedictionary data structures each of these dictionaries has 'rectkeyand the value for that key is rect object that represents the baddie' size and location playerrect is also rect object rect objects have method named colliderect(that returns true if the rect object has collided with the rect object that is passed to it otherwisecolliderect(will return false the for loop on line iterates through each baddie dictionary in the baddies list if any of these baddies collide with the player' characterthen playerhashitbaddie(will return true if the code manages to iterate through all the baddies in the baddies list without detecting collision with any of themit will return false def drawtext(textfontsurfacexy) textobj font render(text textcolor textrect textobj get_rect( textrect topleft (xy surface blit(textobjtextrectdrawing text on the window involves few steps firstthe render(method call on line creates surface object that has the text rendered in specific font on it nextyou need to know the size and location of the surface object you can get rect object with this information from the get_rect(surface method the rect object returned on line from get_rect(has copy of the width and height information from the surface object line changes the location of the rect object by setting new tuple value for its topleft attribute finallyline blits the surface object of the rendered text onto the surface object that was passed to the drawtext(function displaying text in pygame take few more steps than simply calling the print(function but if you put this code into single function named drawtext()then you only need to call this function to display text on the screen initializing pygame and setting up the window now that the constant variables and functions are finishedstart calling the pygame functions that set up the window and clock post questions to
7,783
set up pygamethe windowand the mouse cursor pygame init( mainclock pygame time clock(line sets up the pygame by calling the pygame init(function line creates pygame time clock(object and stores it in the mainclock variable this object will help us keep the program from running too fast windowsurface pygame display set_mode((windowwidthwindowheight)line creates new surface object which is used for the window displayed on the screen you can specify the width and height of this surface object (and the windowby passing tuple with the windowwidth and windowheight constant variables notice that there' only one argument passed to pygame display set_mode() tuple the arguments for pygame display set_mode(are not two integers but one tuple of two integers pygame display set_caption('dodger'line sets the caption of the window to the string 'dodgerthis caption will appear in the title bar at the top of the window pygame mouse set_visible(falsein dodgerthe mouse cursor shouldn' be visible this is because you want the mouse to be able to move the player' character around the screenbut the mouse cursor would get in the way of the character' image on the screen calling pygame mouse set_visible(falsewill tell pygame to make the cursor not visible fullscreen mode the pygame display set_mode(function has secondoptional parameter you can pass the pygame fullscreen constant to make the window take up the entire screen instead of being in window look at this modification to line windowsurface pygame display set_mode((windowwidthwindowheight)pygame fullscreenit will still be windowwidth and windowheight in size for the windows width and heightbut the image will be stretched larger to fit the screen try running the program wiuth and without fullscreen mode
7,784
set up fonts font pygame font sysfont(none line creates font object to use by calling pygame font sysfont(passing none uses the default font passing makes the font have size of points set up sounds gameoversound pygame mixer sound('gameover wav' pygame mixer music load('background mid'nextcreate the sound objects and set up the background music the background music will constantly be playing during the gamebut sound objects will only be played when the player loses the game you can use any wav or mid file for this game some sound files are available at this book' website at long as they have the filenames of gameover wav and background mid (you can change the strings used on lines and to match the filenames the pygame mixer sound(constructor function creates new sound object and stores reference to this object in the gameoversound variable in your own gamesyou can create as many sound objects as you likeeach with different sound file the pygame mixer music load(function loads sound file to play for the background music this function doesn' return any objectsand only one background sound file can be loaded at time set up images playerimage pygame image load('player png' playerrect playerimage get_rect( baddieimage pygame image load('baddie png'next you'll load the image files to be used for the player' character and the baddies on the screen the image for the character is stored in player png and the image for the baddies is stored in baddie png all the baddies look the sameso you only need one image file for them you can download these images from this book' website at display the start screen when the game first startsdisplay the "dodgername on the screen you also want to instruct the player that they can start the game by pushing any key this screen appears so that the player has time to get ready to start playing after running the program post questions to
7,785
show the "startscreen drawtext('dodger'fontwindowsurface(windowwidth )(windowheight ) drawtext('press key to start 'fontwindowsurface(windowwidth (windowheight pygame display update( waitforplayertopresskey(on lines and call the drawtext(function and pass it five arguments the string of the text you want to appear the font that you want the string to appear in the surface object onto which to render the text the coordinate on the surface object to draw the text at the coordinate on the surface object to draw the text at this may seem like many arguments to pass for function callbut keep in mind that this function call replaces five lines of code each time you call it this shortens the program and makes it easier to find bugs since there' less code to check the waitforplayertopresskey(function will pause the game by looping until keydown event is generated then the execution breaks out of the loop and the program continues to run start of the main game code topscore while truethe value in the topscore variable starts at when the program first runs whenever the player loses and has score larger than the current top scorethe top score is replaced with this larger score the infinite loop started on line is technically not the "game loopthe game loop handles events and drawing the window while the game is running insteadthis while loop will iterate each time the player starts new game when the player loses and the game resetsthe program' execution will loop back to line set up the start of the game baddies [score
7,786
at the beginningyou want to set baddies to an empty list the baddies variable is list of dictionary objects with the following keys'rectthe rect object that describes where and what size the baddie is 'speedhow fast the baddie falls down the screen this integer represents pixels per iteration through the game loop 'surfacethe surface object that has the scaled baddie image drawn on it this is the surface object that is blitted to the surface object returned by pygame display set_mode(line resets the player' score to playerrect topleft (windowwidth windowheight the starting location of the player is in the center of the screen and pixels up from the bottom the first item in line ' tuple is the -coordinate of the left edge the second item in the tuple is the -coordinate of the top edge moveleft moveright moveup movedown false reversecheat slowcheat false baddieaddcounter the movement variables moveleftmoverightmoveupand movedown are set to false the reversecheat and slowcheat variables are also set to false they will be set to true only when the player enables these cheats by holding down the "zand "xkeysrespectively the baddieaddcounter variable is counter to tell the program when to add new baddie at the top of the screen the value in baddieaddcounter increments by one each time the game loop iterates when baddieaddcounter is equal to addnewbaddieratethen the baddieaddcounter counter resets to and new baddie is added to the top of the screen (this check is done later on line pygame mixer music play(- the background music starts playing on line with call to pygame mixer music play(the first argument is the number of times the music should repeat itself - is special value that tells pygame you want the music to repeat endlessly the second argument is float that says how many seconds into the music you want it to start playing passing means the music starts playing from the beginning post questions to
7,787
the game loop the game loop' code constantly updates the state of the game world by changing the position of the player and baddieshandling events generated by pygameand drawing the game world on the screen all of this happens several dozen times secondwhich makes it run in "real time while truethe game loop runs while the game part is playing score + increase score line is the start of the main game loop line increases the player' score on each iteration of the game loop the longer the player can go without losingthe higher their score the loop will only exit when the player either loses the game or quits the program event handling there are four different types of events the program will handlequitkeydownkeyupand mousemotion for event in pygame event get()if event type =quitterminate(line is the start of the event-handling code it calls pygame event get()which returns list of event objects each event object represents an event that has happened since the last call to pygame event get(the code will check the type attribute of the event object to see what type of event it isand handle the event accordingly if the type attribute of the event object is equal to quitthen the user has closed the program the quit constant variable was imported from the pygame locals module if event type =keydownif event key =ord(' ')reversecheat true if event key =ord(' ')slowcheat true if the event' type is keydownthe player has pressed down key the event object for keyboard events will also have key attribute that is set to the integer ordinal value of the key pressed the ord(function will return the ordinal value of the letter passed to it for exampleline checks if the event describes the "zkey being pressed down with event key =ord(' 'if this condition is trueset the reversecheat variable to true to
7,788
indicate that the reverse cheat has been activated line checks if the "xkey has been pressed to activate the slow cheat pygame' keyboard events always use the ordinal values of lowercase lettersnot uppercase always use event key =ord(' 'instead of event key =ord(' 'otherwiseyour program may act as though the key wasn' pressed if event key =k_left or event key =ord(' ')moveright false moveleft true if event key =k_right or event key =ord(' ')moveleft false moveright true if event key =k_up or event key =ord(' ')movedown false moveup true if event key =k_down or event key =ord(' ')moveup false movedown true lines to check if the event was generated by the player pressing one of the arrow or wasd keys there isn' an ordinal value for every key on the keyboardsuch as the arrow keys or the esc key insteadthe pygame locals module provides constant variables to use instead line checks if the player has pressed the left arrow key with event key =k_left notice that pressing down on one of the arrow keys not only sets movement variable to truebut it also sets the movement variable in the opposite direction to false for exampleif the left arrow key is pushed downthen the code on line sets moveleft to truebut it also sets moveright to false this prevents the player from confusing the program into thinking that the player' character should move in two opposite directions at the same time table - lists commonly-used constant variables for the key attribute of keyboard-related event objects table - constant variables for keyboard keys pygame constant variable keyboard key pygame constant variable keyboard key k_left k_home left arrow home k_right right arrow k_end end k_up up arrow k_pageup pgup post questions to
7,789
k_down down arrow k_pagedown pgdn k_escape esc k_f k_backspace backspace k_f k_tab tab k_f k_return return or enter k_f k_space space bar k_f k_delete del k_f k_lshift left shift k_f k_rshift right shift k_f k_lctrl left ctrl k_f k_rctrl right ctrl k_f k_lalt left alt k_f k_ralt right alt k_f if event type =keyupif event key =ord(' ')reversecheat false score if event key =ord(' ')slowcheat false score the keyup event is created whenever the player stops pressing down on keyboard key and releases it event objects with type of keyup also have key attribute just like keydown events line checks if the player has released the "zkeywhich will deactivate the reverse cheat in that caseline sets reversecheat to false and line resets the score to the score reset is to discourage the player for using the cheats lines to do the same thing for the "xkey and the slow cheat when the "xkey is releasedslowcheat is set to false and the player' score is reset to
7,790
if event key =k_escapeterminate(at any time during the gamethe player can press the esc key on the keyboard to quit line checks if the key that was released was the esc key by checking event key =k_escape if soline calls the terminate(function to exit the program if event key =k_left or event key =ord(' ')moveleft false if event key =k_right or event key =ord(' ')moveright false if event key =k_up or event key =ord(' ')moveup false if event key =k_down or event key =ord(' ')movedown false lines to check if the player has stopped holding down one of the arrow or wasd keys in that casethe code sets the corresponding movement variable to false for exampleif the player was holding down the left arrow keythen the moveleft would have been set to true on line when they release itthe condition on line will evaluate to trueand the moveleft variable will be set to false the move_ip(method if event type =mousemotion if the mouse movesmove the player where the cursor is playerrect move_ip(event pos[ playerrect centerxevent pos[ playerrect centerynow that you've handled the keyboard eventslet' handle any mouse events that may have been generated the dodger game doesn' do anything if the player has clicked mouse buttonbut it does respond when the player moves the mouse this gives the player two ways of controlling the player character in the gamethe keyboard or the mouse the mousemotion event is generated whenever the mouse is moved event objects with type set to mousemotion also have an attribute named pos for the position of the mouse event the pos attribute stores tuple of the xand -coordinates of where the mouse cursor moved in the window if the event' type is mousemotionthe player' character moves to the position of the mouse cursor post questions to
7,791
the move_ip(method for rect objects will move the location of the rect object horizontally or vertically by number of pixels for exampleplayerrect move_ip( would move the rect object pixels to the right and pixels down to move the rect object left or uppass negative values for exampleplayerrect move_ip(- - will move the rect object left by pixels and up pixels the "ipat the end of move_ip(stands for "in placethis is because the method changes the rect object itselfrather than return new rect object with the changes there is also move(method which doesn' change the rect objectbut instead creates and returns new rect object in the new location adding new baddies add new baddies at the top of the screenif needed if not reversecheat and not slowcheatbaddieaddcounter + on each iteration of the game loopincrement the baddieaddcounter variable by one this only happens if the cheats are not enabled remember that reversecheat and slowcheat are set to true as long as the "zand "xkeys are being held downrespectively and while those keys are being held downbaddieaddcounter isn' incremented thereforeno new baddies will appear at the top of the screen if baddieaddcounter =addnewbaddierate baddieaddcounter baddiesize random randint(baddieminsizebaddiemaxsize newbaddie {'rect'pygame rect(random randint( windowwidth-baddiesize) baddiesizebaddiesizebaddiesize) 'speed'random randint(baddieminspeedbaddiemaxspeed) 'surface':pygame transform scale(baddieimage(baddiesizebaddiesize)) when the baddieaddcounter reaches the value in addnewbaddierateit is time to add new baddie to the top of the screen firstthe baddieaddcounter counter is reset back to line generates size for the baddie in pixels the size will be random integer between baddieminsize and baddiemaxsizewhich are constants set to and on lines and line is where new baddie data structure is created rememberthe data structure for baddies is simply dictionary with keys 'rect''speed'and 'surfacethe 'rectkey
7,792
holds reference to rect object which stores the location and size of the baddie the call to the pygame rect(constructor function has four parametersthe -coordinate of the top edge of the areathe -coordinate of the left edge of the areathe width in pixelsand the height in pixels the baddie needs to appear randomly across the top of the windowso pass random randint( windowwidth-baddiesizefor the -coordinate of the left edge the reason you pass windowwidth-baddiesize instead of windowwidth is because this value is for the left edge of the baddie if the left edge of the baddie is too far on the right side of the screenthen part of the baddie will be off the edge of the window and not visible the bottom edge of the baddie should be just above the top edge of the window the ycoordinate of the top edge of the window is to put the baddie' bottom edge thereset the top edge to baddiesize the baddie' width and height should be the same (the image is square)so pass baddiesize for the third and fourth argument the rate of speed that the baddie moves down the screen is set in the 'speedkey set it to random integer between baddieminspeed and baddiemaxspeed baddies append(newbaddieline will add the newly created baddie data structure to the list of baddie data structures the program will use this list to check if the player has collided with any of the baddiesand to know where to draw baddies on the window moving the player' character move the player around if moveleft and playerrect left playerrect move_ip(- playermoverate the four movement variables moveleftmoverightmoveup and movedown are set to true and false when pygame generates the keydown and keyup eventsrespectively if the player' character is moving left and the left edge of the player' character is greater than (which is the left edge of the window)then playerrect should be moved to the left you'll always move the playerrect object by the number of pixels in playermoverate to get the negative form of an integermultiple it by - on line since is stored in playermoveratethe expression - playermoverate evaluates to - post questions to
7,793
thereforecalling playerrect move_ip(- playermoverate will change the location of playerrect by pixels to the left of its current location if moveright and playerrect right windowwidthplayerrect move_ip(playermoverate if moveup and playerrect top playerrect move_ip( - playermoverateif movedown and playerrect bottom windowheightplayerrect move_ip( playermoveratelines to do the same thing for the other three directionsrightupand down each of the three if statements in lines to checks that their movement variable is set to true and that the edge of the rect object of the player is inside the window then it calls move_ip(to move the rect object the pygame mouse set_pos(function move the mouse cursor to match the player pygame mouse set_pos(playerrect centerxplayerrect centeryline moves the mouse cursor to the same position as the player' character the pygame mouse set_pos(function moves the mouse cursor to the xand -coordinates you pass it this is so that the mouse cursor and player' character are always in the same place specificallythe cursor will be right in the middle of the character' rect object because you passed the centerx and centery attributes of playerrect for the coordinates the mouse cursor still exists and can be movedeven though it is invisible because of the pygame mouse set_visible(falsecall on line move the baddies down for in baddiesnow loop through each baddie data structure in the baddies list to move them down little if not reversecheat and not slowcheatb['rect'move_ip( ['speed']if neither of the cheats have been activatedthen move the baddie' location down number of pixels equal to its speedwhich is stored in the 'speedkey implementing the cheat codes
7,794
elif reversecheatb['rect'move_ip( - if the reverse cheat is activatedthen the baddie should move up by five pixels passing - for the second argument to move_ip(will move the rect object upwards by five pixels elif slowcheatb['rect'move_ip( if the slow cheat has been activatedthen the baddie should move downwardsbut only by the slow speed of one pixel per iteration through the game loop the baddie' normal speed (which is stored in the 'speedkey of the baddie' data structureis ignored while the slow cheat is activated removing the baddies delete baddies that have fallen past the bottom for in baddies[:]any baddies that fell below the bottom edge of the window should be removed from the baddies list remember that while iterating through listdo not modify the contents of the list by adding or removing items so instead of iterating through the baddies list with the for loopiterate through copy of the baddies list this copy is made with the blank slicing operator [:the for loop on line uses variable for the current item in the iteration through baddies[: if ['rect'top windowheightbaddies remove(blet' evaluate the expression ['rect'top is the current baddie data structure from the baddies[:list each baddie data structure in the list is dictionary with 'rectkeywhich stores rect object so ['rect'is the rect object for the baddie finallythe top attribute is the -coordinate of the top edge of the rectangular area remember that the -coordinates increase going down so ['rect'top windowheight will check if the top edge of the baddie is below the bottom of the window if this condition is truethen line removes the baddie data structure from the baddies list drawing the window post questions to
7,795
in python david mertz
7,796
by david mertz copyright ( 'reilly mediainc all rights reserved attribution-sharealike international (cc by-sa seeprinted in the united states of america published by 'reilly mediainc gravenstein highway northsebastopolca 'reilly books may be purchased for educationalbusinessor sales promotional use online editions are also available for most titles (more informationcontact our corporate/institutional sales departmentor corporate@oreilly com editormeghan blanchette production editorshiny kalapurakkel proofreadercharles roumeliotis may interior designerdavid futato cover designerkaren montgomery first edition revision history for the first edition first release the 'reilly logo is registered trademark of 'reilly mediainc functional programming in pythonthe cover imageand related trade dress are trademarks of 'reilly mediainc while the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accuratethe publisher and the author disclaim all responsibility for errors or omissionsincluding without limitation responsibility for damages resulting from the use of or reliance on this work use of the information and instructions contained in this work is at your own risk if any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of othersit is your responsibility to ensure that your use thereof complies with such licenses and/or rights - - [lsi
7,797
preface (avoidingflow control encapsulation comprehensions recursion eliminating loops callables named functions and lambdas closures and callable instances methods of classes multiple dispatch lazy evaluation the iterator protocol moduleitertools higher-order functions utility higher-order functions the operator module the functools module decorators iii
7,798
what is functional programmingwe' better start with the hardest question"what is functional programming (fp)anyway?one answer would be to say that functional programming is what you do when you program in languages like lispschemeclojurescalahaskellmlocamlerlangor few others that is safe answerbut not one that clarifies very much unfortunatelyit is hard to get consistent opinion on just what functional programming iseven from functional programmers themselves story about elephants and blind men seems apropos here it is also safe to contrast functional programming with "imperative programming(what you do in languages like cpascalc++javaperlawktcland most othersat least for the most partfunctional programming is also not object-oriented programming (oop)although some languages are both and it is not logic programming ( prolog)but again some languages are multiparadigm personallyi would roughly characterize functional programming as having at least several of the following characteristics languages that get called functional make these things easyand make other things either hard or impossiblefunctions are first class (objectsthat iseverything you can do with "datacan be done with functions themselves (such as passing function to another functionrecursion is used as primary control structure in some languagesno other "loopconstruct exists
7,799
of the name lisplists are often used with recursion on sublists as substitute for loops "purefunctional languages eschew side effects this excludes the almost ubiquitous pattern in imperative languages of assigning first onethen another value to the same variable to track the program state functional programming either discourages or outright disallows statementsand instead works with the evaluation of expressions (in other wordsfunctions plus argumentsin the pure caseone program is one expression (plus supporting definitionsfunctional programming worries about what is to be computed rather than how it is to be computed much functional programming utilizes "higher orderfunctions (in other wordsfunctions that operate on functions that operate on functionsadvocates of functional programming argue that all these characteristics make for more rapidly developedshorterand less bug-prone code moreoverhigh theorists of computer sciencelogicand math find it lot easier to prove formal properties of functional languages and programs than of imperative languages and programs one crucial concept in functional programming is that of "pure function"--one that always returns the same result given the same arguments--which is more closely akin to the meaning of "functionin mathematics than that in imperative programming python is most definitely not "pure functional programming language"side effects are widespread in most python programs that isvariables are frequently reboundmutable data collections often change contentsand / is freely interleaved with computation it is also not even "functional programming languagemore generally howeverpython is multiparadigm language that makes functional programming easy to do when desiredand easy to mix with other programming styles beyond the standard library while they will not be discussed withing the limited space of this reporta large number of useful third-party python libraries for vi preface