id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
10,700 | when the left arrow key is pressed down (and moving to the left is valid move for the falling pieceas determined by the call to isvalidposition())then we should change the position to one space to the left by subtracting the value of fallingpiece[' 'by the isvalidposition(function has optional parameters called adjx and adjy normally the isvalidposition(function checks the position of the data provided by the piece object that is passed for the second parameter howeversometimes we don' want to check where the piece is currently locatedbut rather few spaces over from that position if we pass - for the adjx ( short name for --adjusted ||)then it doesn' check the validity of the position in the piece' data structurebut rather if the position of where the piece would be if it was one space to the left passing for adjx would check one space to the right there is also an adjy optional parameter passing - for adjy checks one space above where the piece is currently positionedand passing value like for adjy would check three spaces down from where the piece is the movingleft variable is set to trueand just to make sure the falling piece won' move both left and rightthe movingright variable is set to false on line the lastmovesidewaystime variable will be updated to the current time on line these variables are set so that the player can just hold down the arrow key to keep moving the piece over if the movingleft variable is set to truethe program can know that the left arrow key (or keyhas been pressed and not yet let go and if seconds (the number stored in movesidewaysfreqhas passed since the time stored in lastmovesidewaystimethen it is time for the program to move the falling piece to the left again the lastmovesidewaystime works just like how the lastclicktime variable did in the simulate elif (event key =k_right or event key =k_dand isvalidposition(boardfallingpieceadjx= ) fallingpiece[' '+ movingright true movingleft false lastmovesidewaystime time time(the code on lines to is almost identical to lines to except that it handles moving the falling piece to the right when the right arrow key (or keyhas been pressed rotating the block (if there is room to rotateelif (event key =k_up or event key =k_w)email questions to the authoral@inventwithpython com |
10,701 | fallingpiece['rotation'(fallingpiece['rotation' len(shapes[fallingpiece['shape']]the up arrow key (or keywill rotate the falling piece to its next rotation all the code has to do is increment the 'rotationkey' value in the fallingpiece dictionary by howeverif incrementing the 'rotationkey' value makes it larger than the total number of rotationsthen --modding|by the total number of possible rotations for that shape (which is what len(shapes[fallingpiece['shape']]isthen it will --roll over|to here' an example of this modding with the shapewhich has possible rotations if not isvalidposition(boardfallingpiece) fallingpiece['rotation'(fallingpiece['rotation' len(shapes[fallingpiece['shape']]if the new rotated position is not valid because it overlaps some boxes already on the boardthen we want to switch it back to the original rotation by subtracting from fallingpiece['rotation'we can also mod it by len(shapes[fallingpiece['shape']]so that if the new value is - the modding will change it back to the last rotation in the list here' an example of modding negative number- |
10,702 | elif (event key =k_q)rotate the other direction fallingpiece['rotation'(fallingpiece['rotation' len(shapes[fallingpiece['shape']] if not isvalidposition(boardfallingpiece) fallingpiece['rotation'(fallingpiece['rotation' len(shapes[fallingpiece['shape']]lines to do the same thing to except they handle the case where the player has pressed the key which rotates the piece in the opposite direction in this casewe subtract from fallingpiece['rotation'(which is done on line instead of adding making the block fall faster with the down key elif (event key =k_down or event key =k_s)movingdown true if isvalidposition(boardfallingpieceadjy= )fallingpiece[' '+ lastmovedowntime time time(if the down arrow or key is pressed downthen the player wants the piece to fall faster than normal line moves the piece down one space on the board (but only if it is valid spacethe movingdown variable is set to true and lastmovedowntime is reset to the current time these variables will be checked later so that the piece keeps falling at the faster rate as long as the down arrow or key is held down finding the bottom adjy= ) move the current block all the way down elif event key =k_spacemovingdown false movingleft false movingright false for in range( boardheight)if not isvalidposition(boardfallingpiecebreak fallingpiece[' '+ when the player presses the space key the falling piece will immediately drop down as far as it can go on the board and land the program first needs to find out how many spaces the piece can move until it lands lines to will set all the moving variables to false (which makes the code in later parts of the programming think that the user has let up on any arrow keys that were held downthis is email questions to the authoral@inventwithpython com |
10,703 | done because this code will move the piece to the absolute bottom and begin falling the next pieceand we don' want to surprise the player by having those pieces immediately start moving just because they were holding down an arrow key when they hit the space key to find the farthest that the piece can fallwe should first call isvalidposition(and pass the integer for the adjy parameter if isvalidposition(returns falsewe know that the piece cannot fall any further and is already at the bottom if isvalidposition(returns truethen we know that it can fall space down in that casewe should call isvalidposition(with adjy set to if it returns true againwe will call isvalidposition(with adjy set to and so on this is what the for loop on line handlescalling isvalidposition(with increasing integer values to pass for adjy until the function call returns false at that pointwe know that the value in is one space more past the bottom this is why line increases fallingpiece[' 'by instead of (also note that the second parameter to range(on line ' for statement is set to boardheight because this is the maximum amount that the piece could fall before it must hit the bottom of the board moving by holding down the key handle moving the block because of user input if (movingleft or movingrightand time time(lastmovesidewaystime movesidewaysfreq if movingleft and isvalidposition(boardfallingpieceadjx= ) fallingpiece[' '- elif movingright and isvalidposition(boardfallingpieceadjx= ) fallingpiece[' '+ lastmovesidewaystime time time(remember that on line the movingleft variable was set to true if the player pressed down on the left arrow key(the same for line where movingright was set to true if the player pressed down on the right arrow key the moving variables were set back to false if the user let up on these keys also (see line and what also happened when the player pressed down on the left or right arrow key was that the lastmovesidewaystime variable was set to the current time (which was the return value of time time()if the player continued to hold down the arrow key without letting up on itthen the movingleft or movingright variable would still be set to true |
10,704 | if the user held down on the key for longer than seconds (the value stored in movesidewaysfreq is the float then the expression time time(lastmovesidewaystime movesidewaysfreq would evaluate to true line ' condition is true if the user has both held down the arrow key and seconds has passedand in that case we should move the falling piece to the left or right even though the user hasn' pressed the arrow key again this is very useful because it would become tiresome for the player to repeatedly hit the arrow keys to get the falling piece to move over multiple spaces on the board insteadthey can just hold down an arrow key and the piece will keep moving over until they let up on the key when that happensthe code on lines to will set the moving variable to false and the condition on line will be false that is what stops the falling piece from sliding over more to demonstrate why the time time(lastmovesidewaystime movesidewaysfreq returns true after the number of seconds in movesidewaysfreq has passedrun this short programimport time waittime begin time time(while truenow time time(message '% % % (beginnow(now begin)if now begin waittimeprint(message passed wait time!'elseprint(message not yet 'time sleep( this program has an infinite loopso in order to terminate itpress ctrl- the output of this program will look something like this not yet not yet not yet not yet not yet not yet not yet not yet not yet email questions to the authoral@inventwithpython com |
10,705 | not yet not yet not yet not yet not yet not yet not yet not yet not yet passed wait time passed wait time passed wait time passed wait time passed wait timetraceback (most recent call last)file " :\timetest py"line in time sleep( keyboardinterrupt the first number on each line of output is the return value of time time(when the program first started (and this value never changesthe second number is the latest return value from time time((this value keeps getting updated on each iteration of the loopand the third number is the current time minus the start time this third number is the number of seconds that have elapsed since the begin time time(line of code was executed if this number is greater than the code will start printing --passed wait time!|instead of --not yet |this is how our game program can know if certain amount of time has passed since line of code was run in our tetromino programthe time time(lastmovesidewaystime expression will evaluate to the number of seconds that has elapsed since the last time lastmovesidewaystime was set to the current time if this value is greater than the value in movesidewaysfreqwe know it is time for the code to move the falling piece over one more space don' forget to update lastmovesidewaystime to the current time againthis is what we do on line if movingdown and time time(lastmovedowntime movedownfreq and isvalidposition(boardfallingpieceadjy= ) fallingpiece[' '+ lastmovedowntime time time( |
10,706 | lines to do almost the same thing as lines to do except for moving the falling piece down this has separate move variable (movingdownand --last time|variable (lastmovedowntimeas well as different --move frequency|variable (movedownfreqletting the piece "naturallyfall let the piece fall if it is time to fall if time time(lastfalltime fallfreqsee if the piece has landed if not isvalidposition(boardfallingpieceadjy= )falling piece has landedset it on the board addtoboard(boardfallingpiecescore +removecompletelines(boardlevelfallfreq calculatelevelandfallfreq(scorefallingpiece none elsepiece did not landjust move the block down fallingpiece[' '+ lastfalltime time time(the rate that the piece is naturally moving down (that isfallingis tracked by the lastfalltime variable if enough time has elapsed since the falling piece last fell down one spacelines to will handle dropping the piece by one space if the condition on line is truethen the piece has landed the call to addtoboard(will make the piece part of the board data structure (so that future pieces can land on it)and the removecompletelines(call will handle erasing any complete lines on the board and pulling the boxes down the removecompletelines(function also returns an integer value of how many lines were removedso we add this number to the score because the score may have changedwe call the calculatelevelandfallfreq(function to update the current level and frequency that the pieces fall and finallywe set the fallingpiece variable to none to indicate that the next piece should become the new falling pieceand random new piece should be generated for the new next piece (that is done on lines to at the beginning of the game loop if the piece has not landedwe simply set its position down one space (on line and reset lastfalltime to the current time (on line drawing everything on the screen drawing everything on the screen displaysurf fill(bgcolordrawboard(boardemail questions to the authoral@inventwithpython com |
10,707 | drawstatus(scoreleveldrawnextpiece(nextpieceif fallingpiece !nonedrawpiece(fallingpiecepygame display update(fpsclock tick(fpsnow that the game loop has handled all events and updated the game statethe game loop just needs to draw the game state to the screen most of the drawing is handled by other functionsso the game loop code just needs to call those functions then the call to pygame display update(makes the display surface appear on the actual computer screenand the tick(method call adds slight pause so the game doesn' run too fast maketextobjs() shortcut function for making text def maketextobjs(textfontcolor) surf font render(texttruecolor return surfsurf get_rect(the maketextobjs(function just provides us with shortcut given the textfont objectand color objectit calls render(for us and returns the surface and rect object for this text this just saves us from typing out the code to create the surface and rect object each time we need them the same old terminate(function def terminate() pygame quit( sys exit(the terminate(function works the same as in the previous game programs waiting for key press event with the checkforkeypress(function def checkforkeypress() go through event queue looking for keyup event grab keydown events to remove them from the event queue checkforquit( for event in pygame event get([keydownkeyup]) if event type =keydown |
10,708 | continue return event key return none the checkforkeypress(function works almost the same as it did in the wormy game first it calls checkforquit(to handle any quit events (or keyup events specifically for the esc keyand terminates the program if there are any then it pulls out all the keyup and keydown events from the event queue it ignores any keydown events (keydown was specified to pygame event get(only to clear those events out of the event queueif there were no keyup events in the event queuethen the function returns none showtextscreen() generic text screen function def showtextscreen(text) this function displays large text in the center of the screen until key is pressed draw the text drop shadow titlesurftitlerect maketextobjs(textbigfonttextshadowcolor titlerect center (int(windowwidth )int(windowheight ) displaysurf blit(titlesurftitlerect draw the text titlesurftitlerect maketextobjs(textbigfonttextcolor titlerect center (int(windowwidth int(windowheight displaysurf blit(titlesurftitlerect draw the additional "press key to play text presskeysurfpresskeyrect maketextobjs('press key to play 'basicfonttextcolor presskeyrect center (int(windowwidth )int(windowheight displaysurf blit(presskeysurfpresskeyrectinstead of separate functions for the start screen and game over screenswe will create one generic function named showtextscreen(the showtextscreen(function will draw whatever text we pass for the text parameter alsothe text --press key to play |will be displayed in addition notice that lines to draw the text in darker shadow color firstand then lines to draw the same text againexcept offset by pixels to the left and pixels upward this creates --drop shadow|effect that makes the text look bit prettier you can compare the difference by commenting out lines to to see the text without drop shadow email questions to the authoral@inventwithpython com |
10,709 | the showtextscreen(will be used for the start screenthe game over screenand also for pause screen (the pause screen is explained later in this while checkforkeypress(=nonepygame display update(fpsclock tick(we want the text to stay on the screen until the user presses key this small loop will constantly call pygame display update(and fpsclock tick(until checkforkeypress(returns value other than none this happens when the user presses key the checkforquit(function def checkforquit() for event in pygame event get(quit)get all the quit events terminate(terminate if any quit events are present for event in pygame event get(keyup)get all the keyup events if event key =k_escape terminate(terminate if the keyup event was for the esc key pygame event post(eventput the other keyup event objects back the checkforquit(function can be called to handle any events that will cause the program to terminate this happens if there are any quit events in the event queue (this is handle by lines and )or if there is keyup event of the esc key the player should be able to press the esc key at any time to quit the program because the pygame event get(call on line pulls out all of the keyup events (including events for keys other than the esc key)if the event is not for the esc keywe want to put it back into the event queue by calling the pygame event post(function the calculatelevelandfallfreq(function def calculatelevelandfallfreq(score) based on the scorereturn the level the player is on and how many seconds pass until falling piece falls one space level int(score fallfreq (level return levelfallfreq every time the player completes linetheir score will increase by one point every ten pointsthe game goes up level and the pieces start falling down faster both the level and the falling frequency can be calculated from the score that is passed to this function |
10,710 | to calculate the levelwe use the int(function to round down the score divided by so if the score any number between and the int(call will round it down to the part of the code is there because we want the first level to be level not level when the score reaches then int( will evaluate to and the will make the level here is graph showing the values of level for the scores to level int(score level score to calculate the falling frequencywe start with base time of (meaning that the piece will naturally fall once every secondsthen we multiply the level by and subtract that from the base time so on level we subtract (that is from to get on level we subtract (that is to get you can think of the level part of the equation as --for every levelthe piece will fall seconds faster than the previous level |we can also make graph showing how fast the pieces will fall at each level of the gameemail questions to the authoral@inventwithpython com |
10,711 | fallfreq (level fall frequency (seconds - level you can see that at level the falling frequency will be less than this won' cause any bugs with our codebecause line just checks that the elapsed time since the falling piece last fell one space is greater than the calculated falling frequency so if the falling frequency is negativethen the condition on line will always be true and the piece will fall on every iteration of the game loop from level and beyondthe piece cannot fall any faster if the fps is set at this means that at reaching level the falling piece will fall spaces second considering that the board is only spaces tallthat means the player will have less than second to set each pieceif you want the pieces to start (if you can see what meanfalling faster at slower rateyou can change the equation that the calculatelevelandfallfreq(uses for examplelet' say line was this fallfreq (level in the above casethe pieces would only fall seconds faster on each level rather than seconds faster the graph would look like this (the original line is also in the graph in light grey) |
10,712 | fallfreq (level fall frequency (seconds - level as you can seewith this new equationlevel would only be as hard as the original level you can change the game to be as difficult or easy as you like by changing the equations in calculatelevelandfallfreq(generating pieces with the getnewpiece(function def getnewpiece() return random new piece in random rotation and color shape random choice(list(shapes keys()) newpiece {'shape'shape 'rotation'random randint( len(shapes[shape] ) ' 'int(boardwidth int(templatewidth ) ' '- start it above the board ( less than 'color'random randint( len(colors)- ) return newpiece the getnewpiece(function generates random piece that is positioned at the top of the board firstto randomly choose the shape of the piecewe create list of all the possible shapes by calling list(shapes keys()on line the keys(dictionary method returns value of the data type --dict_keys||which must be converted to list value with the list(function before being passed to random choice(this is because the random choice(function only accepts list values for its parameter the random choice(function then randomly returns the value of an item from the list the piece data structures are simply dictionary value with the keys 'shape''rotation'' '' 'and 'coloremail questions to the authoral@inventwithpython com |
10,713 | the value for the 'rotationkey is random integer between to one less than however many possible rotations there are for that shape the number of rotations for shape can be found from the expression len(shapes[shape]notice that we don' store the list of string values (like the ones store in the constants like s_shape_templatein each piece data structure to represent the boxes of each piece insteadwe just store an index for the shape and rotation which refer to the pieces constant the 'xkey' value is always set to the middle of the board (also accounting for the width of the pieces themselveswhich is found from our templatewidth constantthe 'ykey' value is always set to - to place it slightly above the board (the top row of the board is row since the colors constant is tuple of the different colorsselecting random number from to the length of colors (subtracting onewill give us random index value for the piece' color once all of the values in the newpiece dictionary are setthe getnewpiece(function returns newpiece adding pieces to the board data structure def addtoboard(boardpiece) fill in the board based on piece' locationshapeand rotation for in range(templatewidth) for in range(templateheight) if shapes[piece['shape']][piece['rotation']][ ][ !blank board[ piece[' ']][ piece[' ']piece['color'the board data structure is data representation for the rectangular space where pieces that have previously landed are tracked the currently falling piece is not marked on the board data structure what the addtoboard(function does is takes piece data structure and adds its boxes to the board data structure this happens after piece has landed the nested for loops on lines and go through every space in the piece data structureand if it finds box in the space (line )it adds it to the board (line creating new board data structure def getblankboard() create and return new blank board data structure board [ for in range(boardwidth) board append([blankboardheight |
10,714 | return board the data structure used for the board is fairly simpleit' list of lists of values if the value is the same as the value in blankthen it is an empty space if the value is an integerthen it represents box that is the color that the integer indexes in the colors constant list that is is blue is green is redand is yellow in order to create blank boardlist replication is used to create the lists of blank values which represents column this is done on line one of these lists is created for each of the columns in the board (this is what the for loop on line doesthe isonboard(and isvalidposition(functions def isonboard(xy) return > and boardwidth and boardheight the isonboard(is simple function which checks that the xy coordinates that are passed represent valid values that exist on the board as long as both the xy coordinates are not less or greater than or equal to the boardwidth and boardheight constantsthen the function returns true def isvalidposition(boardpieceadjx= adjy= ) return true if the piece is within the board and not colliding for in range(templatewidth) for in range(templateheight) isaboveboard piece[' 'adjy if isaboveboard or shapes[piece['shape']][piece['rotation']][ ][ =blank continue the isvalidposition(function is given board data structure and piece data structureand returns true if all the boxes in the piece are both on the board and not overlapping any boxes on the board this is done by taking the piece' xy coordinates (which is really the coordinate of the upper right box on the boxes for the pieceand adding the coordinate inside the piece data structure here' couple pictures to help illustrate thisemail questions to the authoral@inventwithpython com |
10,715 | the board with falling piece in valid position the board with the falling piece in an invalid position on the left boardthe falling piece' (that isthe top left corner of the falling piece'sxy coordinates are ( on the board but the boxes inside the falling piece' coordinate system have their own coordinates to find the --board|coordinates of these pieceswe just have to add the --board|coordinates of the falling piece' top left box and the --piece|coordinates of the boxes on the left boardthe falling piece' boxes are at the following --piece|coordinates( ( ( ( when we add the ( coordinate (the piece' coordinates on the boardto these coordinatesit looks like this( ( ( ( after adding the ( coordinate the boxes are at the following --board|coordinates( ( ( ( |
10,716 | and now that we can figure out where the falling piece' boxes are as board coordinateswe can see if they overlap with the landed boxes that are already on the board the nested for loops on lines and go through each of the possible coordinates on the falling piece we want to check if box of the falling piece is either off of the board or overlapping box on the board (although one exception is if the box is above the boardwhich is where it could be when the falling piece just begins falling line creates variable named isaboveboard that is set to true if the box on the falling piece at the coordinates pointed to be and is above the board otherwise it is set to false the if statement on line checks if the space on the piece is above the board or is blank if either of those is truethen the code executes continue statement and goes to the next iteration (note that the end of line has [ ][xinstead of [ ][ythis is because the coordinates in the pieces data structure are reversed see the previous section--setting up the piece templates|| adjy) blank if not isonboard( piece[' 'adjxy piece[' 'return false if board[ piece[' 'adjx][ piece[' 'adjy!return false return true the if statement on line checks that the piece' box is not located on the board the if statement on line checks that the board space the piece' box is located is not blank if either of these conditions are truethen the isvalidposition(function will return false notice that these if statements also adjust the coordinates for the adjx and adjy parameters that were passed in to the function if the code goes through the nested for loop and hasn' found reason to return falsethen the position of the piece must be valid and so the function returns true on line checking forand removingcomplete lines def iscompleteline(boardy) return true if the line filled with boxes with no gaps for in range(boardwidth) if board[ ][ =blank return false return true email questions to the authoral@inventwithpython com |
10,717 | the iscompleteline does simple check at the row specified by the parameter row on the board is considered to be --complete|when every space is filled by box the for loop on line goes through each space in the row if space is blank (which is caused by it having the same value as the blank constant)then the function return false def removecompletelines(board) remove any completed lines on the boardmove everything above them downand return the number of complete lines numlinesremoved boardheight start at the bottom of the board while > the removecompletelines(function will find any complete lines in the passed board data structureremove the linesand then shift all the boxes on the board above that line down one row the function will return the number of lines that were removed (which is tracked by the numlinesremoved variableso that this can be added to the score the way this function works is by running in loop starting on line with the variable starting at the lowest row (which is boardheight whenever the row specified by is not completey will be decremented to the next highest row the loop finally stops once reaches - if iscompleteline(boardy)remove the line and pull boxes down by one line for pulldowny in range( - )for in range(boardwidth)board[ ][pulldownyboard[ ][pulldowny- set very top line to blank for in range(boardwidth)board[ ][ blank numlinesremoved + note on the next iteration of the loopy is the same this is so that if the line that was pulled down is also completeit will be removed elsey - move on to check next row up return numlinesremoved the iscompleteline(function will return true if the line that is referring to is complete in that casethe program needs to copy the values of each row above the removed line to the next lowest line this is what the for loop on line does (which is why its call to the range(function begins at yrather than also note that it uses the three argument form of |
10,718 | range()so that the list it returns starts at yends at and after each iteration --increases|by let' look at the following example to save spaceonly the top five rows of the board are shown row is complete linewhich means that all the rows above it (row and must be --pulled down|firstrow is copied down to row the board on the right shows what the board will look like after this is donethis --pulling down|is really just copying the higher row' values to the row below it on line after row is copied to row then row is copied to row followed by row copied to row row (the row at the very topdoesn' have row above it to copy values down but row doesn' need row copied to itit just needs all the spaces set to blank this is what lines and do after thatthe board will have changed from the board shown below on the left to the board shown below on the rightafter the complete line is removedthe execution reaches the end of the while loop that started on line so the execution jumps back to the beginning of the loop note that at no point when email questions to the authoral@inventwithpython com |
10,719 | the line was being removed and the rows being pulled down that the variable changed at all so on the next iterationthe variable is pointing to the same row as before this is needed because if there were two complete linesthen the second complete line would have been pulled down and would also have to be removed the code will then remove this complete lineand then go to the next iteration it is only when there is not completed line that the variable is decremented on line once the variable has been decremented all the way to the execution will exit the while loop convert from board coordinates to pixel coordinates def converttopixelcoords(boxxboxy) convert the given xy coordinates of the board to xy coordinates of the location on the screen return (xmargin (boxx boxsize))(topmargin (boxy boxsize)this helper function converts the board' box coordinates to pixel coordinates this function works the same way to the other --convert coordinates|functions used in the previous game programs drawing box on the board or elsewhere on the screen def drawbox(boxxboxycolorpixelx=nonepixely=none) draw single box (each tetromino piece has four boxes at xy coordinates on the board orif pixelx pixely are specifieddraw to the pixel coordinates stored in pixelx pixely (this is used for the "nextpiece if color =blank return if pixelx =none and pixely =none pixelxpixely converttopixelcoords(boxxboxy pygame draw rect(displaysurfcolors[color](pixelx pixely boxsize boxsize ) pygame draw rect(displaysurflightcolors[color](pixelx pixely boxsize boxsize )the drawbox(function draws single box on the screen the function can receive boxx and boxy parameters for board coordinates where the box should be drawn howeverif the pixelx and pixely parameters are specifiedthen these pixel coordinates will override the boxx and boxy parameters the pixelx and pixely parameters are used to draw the boxes of the --next|piecewhich is not on the board if the pixelx and pixely parameters are not setthen they will be set to none by default when the function first begins then the if statement on line will overwrite the none values |
10,720 | with the return values from converttopixelcoords(this call gets the pixel coordinates of the board coordinates specified by boxx and boxy the code won' fill the entire box' space with color to have black outline in between the boxes of piecethe left and top parameters in the pygame draw rect(call have added to them and is added to the width and height parameters in order to draw the highlighted boxfirst the box is drawn with the darker color on line thena slightly smaller box is drawn on top of the darker box on line drawing everything to the screen def drawboard(board) draw the border around the board pygame draw rect(displaysurfbordercolor(xmargin topmargin (boardwidth boxsize (boardheight boxsize ) fill the background of the board pygame draw rect(displaysurfbgcolor(xmargintopmarginboxsize boardwidthboxsize boardheight) draw the individual boxes on the board for in range(boardwidth) for in range(boardheight) drawbox(xyboard[ ][ ]the drawboard(function is responsible for calling the drawing functions for the board' border and all the boxes on the board first the board' border is drawn on displaysurffollowed by the background color of the board then call to drawbox(is made for each space on the board the drawbox(function is smart enough to leave out the box if board[ ][yis set to blank drawing the score and level text def drawstatus(scorelevel) draw the score text scoresurf basicfont render('score%sscoretruetextcolor scorerect scoresurf get_rect( scorerect topleft (windowwidth displaysurf blit(scoresurfscorerect draw the level text levelsurf basicfont render('level%sleveltruetextcolor levelrect levelsurf get_rect( levelrect topleft (windowwidth displaysurf blit(levelsurflevelrectemail questions to the authoral@inventwithpython com |
10,721 | the drawstatus(function is responsible for rendering the text for the --score:|and --level:|information that appears in the upper right of the corner of the screen drawing piece on the board or elsewhere on the screen def drawpiece(piecepixelx=nonepixely=none) shapetodraw shapes[piece['shape']][piece['rotation'] if pixelx =none and pixely =none if pixelx pixely hasn' been specifieduse the location stored in the piece data structure pixelxpixely converttopixelcoords(piece[' ']piece[' '] draw each of the blocks that make up the piece for in range(templatewidth) for in range(templateheight) if shapetodraw[ ][ !blank drawbox(nonenonepiece['color']pixelx ( boxsize)pixely ( boxsize)the drawpiece(function will draw the boxes of piece according to the piece data structure that is passed to it this function will be used to draw the falling piece and the --next|piece since the piece data structure will contain all of the shapepositionrotationand color informationnothing else besides the piece data structure needs to be passed to the function howeverthe --next|piece is not drawn on the board in this casewe ignore the position information stored inside the piece data structure and instead let the caller of the drawpiece(function pass in arguments for the optional pixelx and pixely parameters to specify where exactly on the window the piece should be drawn if no pixelx and pixely arguments are passed inthen lines and will overwrite those variables with the return values of converttopixelcoords(call the nested for loops on line and will then call drawbox(for each box of the piece that needs to be drawn drawing the "nextpiece def drawnextpiece(piece) draw the "nexttext nextsurf basicfont render('next:'truetextcolor nextrect nextsurf get_rect( nextrect topleft (windowwidth displaysurf blit(nextsurfnextrect draw the "nextpiece drawpiece(piecepixelx=windowwidth- pixely= |
10,722 | if __name__ ='__main__' main(the drawnextpiece(draws the --next|piece in the upper right corner of the screen it does this by calling the drawpiece(function and passing in arguments for drawpiece()' pixelx and pixely parameters that' the last function line and are run after all the function definitions have been executedand then the main(function is called to begin the main part of the program summary the tetromino game (which is clone of the more popular game--tetris||is pretty easy to explain to someone in english--blocks fall from the top of boardand the player moves and rotates them so that they form complete lines the complete lines disappear (giving the player pointsand the lines above them move down the game keeps going until the blocks fill up the entire board and the player loses |explaining it in plain english is one thingbut when we have to tell computer exactly what to do there are many details we have to fill in the original tetris game was designed and programmed one personalex pajitnovin the soviet union in the game is simplefunand addictive it is one of the most popular video games ever madeand has sold million copies with many people creating their own clones and variations of it and it was all created by one person who knew how to program with the right idea and some programming knowledge you can create incredibly fun games and with some practiceyou will be able to turn your game ideas into real programs that might become as popular as tetrisfor additional programming practiceyou can download buggy versions of tetromino from there are also variations of the tetromino game on the book' website --pentomino|is version of this game with pieces made up of five boxes there is also --tetromino for idiots||where all of the pieces are made up of just one box email questions to the authoral@inventwithpython com |
10,723 | these variations can be downloaded from |
10,724 | squirrel eat squirrel how to play squirrel eat squirrel squirrel eat squirrel is loosely based on the game --katamari damacy|the player controls small squirrel that must hop around the screen eating smaller squirrels and avoiding larger squirrels each time the player' squirrel eats squirrel that is smaller than itit grows larger if the player' squirrel gets hit by larger squirrel larger than itit loses life point the player wins when the squirrel becomes monstrously large squirrel called the omega squirrel the player loses if their squirrel gets hit three times ' not really sure where got the idea for video game where squirrels eat each other ' little strange sometimes the design of squirrel eat squirrel there are three types of data structures in this gamewhich are represented as dictionary values the types are player squirrelsenemy squirrelsand grass objects there is only one player squirrel object at time in the game notetechnically--object|means something specific in object-oriented programming python does have oop featuresbut they aren' covered in this book technically the pygame objects such as --rect object|or --surface object|are objects but ' going to use the term --object|in this book to refer to --things that exist in the game world|but reallythe player squirrelenemy squirrelsand grass --objects|are just dictionary values email questions to the authoral@inventwithpython com |
10,725 | all the objects have the following keys in their dictionary value' '' 'and 'rectthe 'xand 'ykey' value give the coordinates of the top left of the object in game world coordinates these are different from pixel coordinates (which is what the 'rectkey' value tracksthe difference between game world and pixel coordinates will be explained when you learn about the concept of cameras in additionthe player squirrelenemy squirreland grass objects have other keys which are explained in large comment at the start of the source code source code to squirrel eat squirrel this source code can be downloaded from messageslook at the line number that is mentioned in the error message and check your code for any typos you can also copy and paste your code into the web form at book you will also need to download the following image files squirrel eat squirrel ( katamari damacy clone by al sweigart al@inventwithpython com creative commons by-nc-sa us import randomsystimemathpygame from pygame locals import fps frames per second to update the screen winwidth width of the program' windowin pixels winheight height in pixels half_winwidth int(winwidth half_winheight int(winheight grasscolor ( white ( red ( |
10,726 | cameraslack how far from the center the squirrel moves before moving the camera moverate how fast the player moves bouncerate how fast the player bounces (large is slower bounceheight how high the player bounces startsize how big the player starts off winsize how big the player needs to be to win invulntime how long the player is invulnerable after being hit in seconds gameovertime how long the "game overtext stays on the screen in seconds maxhealth how much health the player starts with numgrass number of grass objects in the active area numsquirrels number of squirrels in the active area squirrelminspeed slowest squirrel speed squirrelmaxspeed fastest squirrel speed dirchangefreq chance of direction change per frame left 'left right 'right "" this program has three data structures to represent the playerenemy squirrelsand grass background objects the data structures are dictionaries with the following keys keys used by all three data structures 'xthe left edge coordinate of the object in the game world (not pixel coordinate on the screen 'ythe top edge coordinate of the object in the game world (not pixel coordinate on the screen 'rectthe pygame rect object representing where on the screen the object is located player data structure keys 'surfacethe pygame surface object that stores the image of the squirrel which will be drawn to the screen 'facingeither set to left or rightstores which direction the player is facing 'sizethe width and height of the player in pixels (the width height are always the same 'bouncerepresents at what point in bounce the player is in means standing (no bounce)up to bouncerate (the completion of the bounce 'healthan integer showing how many more times the player can be hit by larger squirrel before dying enemy squirrel data structure keysemail questions to the authoral@inventwithpython com |
10,727 | 'surfacethe pygame surface object that stores the image of the squirrel which will be drawn to the screen 'movexhow many pixels per frame the squirrel moves horizontally negative integer is moving to the lefta positive to the right 'moveyhow many pixels per frame the squirrel moves vertically negative integer is moving upa positive moving down 'widththe width of the squirrel' imagein pixels 'heightthe height of the squirrel' imagein pixels 'bouncerepresents at what point in bounce the player is in means standing (no bounce)up to bouncerate (the completion of the bounce 'bounceratehow quickly the squirrel bounces lower number means quicker bounce 'bounceheighthow high (in pixelsthe squirrel bounces grass data structure keys 'grassimagean integer that refers to the index of the pygame surface object in grassimages used for this grass object "" def main() global fpsclockdisplaysurfbasicfontl_squir_imgr_squir_imggrassimages pygame init( fpsclock pygame time clock( pygame display set_icon(pygame image load('gameicon png') displaysurf pygame display set_mode((winwidthwinheight) pygame display set_caption('squirrel eat squirrel' basicfont pygame font font('freesansbold ttf' load the image files l_squir_img pygame image load('squirrel png' r_squir_img pygame transform flip(l_squir_imgtruefalse grassimages [ for in range( ) grassimages append(pygame image load('grass% pngi) while true rungame( def rungame() set up variables for the start of new game invulnerablemode false if the player is invulnerable invulnerablestarttime time the player became invulnerable gameovermode false if the player has lost gameoverstarttime time the player lost |
10,728 | winmode false if the player has won create the surfaces to hold game text gameoversurf basicfont render('game over'truewhite gameoverrect gameoversurf get_rect( gameoverrect center (half_winwidthhalf_winheight winsurf basicfont render('you have achieved omega squirrel!'truewhite winrect winsurf get_rect( winrect center (half_winwidthhalf_winheight winsurf basicfont render('(press "rto restart )'truewhite winrect winsurf get_rect( winrect center (half_winwidthhalf_winheight camerax and cameray are where the middle of the camera view is camerax cameray grassobjs [stores all the grass objects in the game squirrelobjs [stores all the non-player squirrel objects stores the player object playerobj {'surface'pygame transform scale(l_squir_img(startsizestartsize)) 'facing'left 'size'startsize ' 'half_winwidth ' 'half_winheight 'bounce': 'health'maxhealth moveleft false moveright false moveup false movedown false start off with some random grass images on the screen for in range( ) grassobjs append(makenewgrass(cameraxcameray) grassobjs[ ][' 'random randint( winwidth grassobjs[ ][' 'random randint( winheight while truemain game loop check if we should turn off invulnerability email questions to the authoral@inventwithpython com |
10,729 | if invulnerablemode and time time(invulnerablestarttime invulntime invulnerablemode false move all the squirrels for sobj in squirrelobjs move the squirreland adjust for their bounce sobj[' '+sobj['movex' sobj[' '+sobj['movey' sobj['bounce'+ if sobj['bounce'sobj['bouncerate'] sobj['bounce' reset bounce amount random chance they change direction if random randint( dirchangefreq sobj['movex'getrandomvelocity( sobj['movey'getrandomvelocity( if sobj['movex' faces right sobj['surface'pygame transform scale(r_squir_img(sobj['width']sobj['height']) elsefaces left sobj['surface'pygame transform scale(l_squir_img(sobj['width']sobj['height']) go through all the objects and see if any need to be deleted for in range(len(grassobjs - - ) if isoutsideactivearea(cameraxcameraygrassobjs[ ]) del grassobjs[ for in range(len(squirrelobjs - - ) if isoutsideactivearea(cameraxcameraysquirrelobjs[ ]) del squirrelobjs[ add more grass squirrels if we don' have enough while len(grassobjsnumgrass grassobjs append(makenewgrass(cameraxcameray) while len(squirrelobjsnumsquirrels squirrelobjs append(makenewsquirrel(cameraxcameray) adjust camerax and cameray if beyond the "camera slack playercenterx playerobj[' 'int(playerobj['size' playercentery playerobj[' 'int(playerobj['size' if (camerax half_winwidthplayercenterx cameraslack camerax playercenterx cameraslack half_winwidth elif playercenterx (camerax half_winwidthcameraslack camerax playercenterx cameraslack half_winwidth |
10,730 | if (cameray half_winheightplayercentery cameraslack cameray playercentery cameraslack half_winheight elif playercentery (cameray half_winheightcameraslack cameray playercentery cameraslack half_winheight draw the green background displaysurf fill(grasscolor draw all the grass objects on the screen for gobj in grassobjs grect pygame rect(gobj[' 'camerax gobj[' 'cameray gobj['width'] gobj['height'] displaysurf blit(grassimages[gobj['grassimage']]grect draw the other squirrels for sobj in squirrelobjs sobj['rect'pygame rect(sobj[' 'camerax sobj[' 'cameray getbounceamount(sobj['bounce']sobj['bouncerate']sobj['bounceheight']) sobj['width'] sobj['height'] displaysurf blit(sobj['surface']sobj['rect'] draw the player squirrel flashison round(time time() = if not gameovermode and not (invulnerablemode and flashison) playerobj['rect'pygame rect(playerobj[' 'camerax playerobj[' 'cameray getbounceamount(playerobj['bounce']bounceratebounceheight) playerobj['size'] playerobj['size'] displaysurf blit(playerobj['surface']playerobj['rect'] draw the health meter drawhealthmeter(playerobj['health'] for event in pygame event get()event handling loop if event type =quit terminate( elif event type =keydownemail questions to the authoral@inventwithpython com |
10,731 | if event key in (k_upk_w) movedown false moveup true elif event key in (k_downk_s) moveup false movedown true elif event key in (k_leftk_a) moveright false moveleft true if playerobj['facing'=rightchange player image playerobj['surface'pygame transform scale(l_squir_img(playerobj['size']playerobj['size']) playerobj['facing'left elif event key in (k_rightk_d) moveleft false moveright true if playerobj['facing'=leftchange player image playerobj['surface'pygame transform scale(r_squir_img(playerobj['size']playerobj['size']) playerobj['facing'right elif winmode and event key =k_r return elif event type =keyup stop moving the player' squirrel if event key in (k_leftk_a) moveleft false elif event key in (k_rightk_d) moveright false elif event key in (k_upk_w) moveup false elif event key in (k_downk_s) movedown false elif event key =k_escape terminate( if not gameovermode actually move the player if moveleft playerobj[' '-moverate if moveright playerobj[' '+moverate if moveup playerobj[' '-moverate if movedown |
10,732 | playerobj[' '+moverate if (moveleft or moveright or moveup or movedownor playerobj['bounce'! playerobj['bounce'+ if playerobj['bounce'bouncerate playerobj['bounce' reset bounce amount check if the player has collided with any squirrels for in range(len(squirrelobjs)- - - ) sqobj squirrelobjs[ if 'rectin sqobj and playerobj['rect'colliderect(sqobj['rect']) player/squirrel collision has occurred if sqobj['width'sqobj['height'<playerobj['size']** player is larger and eats the squirrel playerobj['size'+int(sqobj['width'sqobj['height'])** del squirrelobjs[ if playerobj['facing'=left playerobj['surface'pygame transform scale(l_squir_img(playerobj['size']playerobj['size']) if playerobj['facing'=right playerobj['surface'pygame transform scale(r_squir_img(playerobj['size']playerobj['size']) if playerobj['size'winsize winmode true turn on "win mode elif not invulnerablemode player is smaller and takes damage invulnerablemode true invulnerablestarttime time time( playerobj['health'- if playerobj['health'= gameovermode true turn on "game over mode gameoverstarttime time time( else game is overshow "game overtext displaysurf blit(gameoversurfgameoverrect if time time(gameoverstarttime gameovertime return end the current game email questions to the authoral@inventwithpython com |
10,733 | check if the player has won if winmode displaysurf blit(winsurfwinrect displaysurf blit(winsurf winrect pygame display update( fpsclock tick(fps def drawhealthmeter(currenthealth) for in range(currenthealth)draw red health bars pygame draw rect(displaysurfred( ( maxhealthi ) for in range(maxhealth)draw the white outlines pygame draw rect(displaysurfwhite( ( maxhealthi ) def terminate() pygame quit( sys exit( def getbounceamount(currentbouncebounceratebounceheight) returns the number of pixels to offset based on the bounce larger bouncerate means slower bounce larger bounceheight means higher bounce currentbounce will always be less than bouncerate return int(math sin(math pi float(bouncerate)currentbounce bounceheight def getrandomvelocity() speed random randint(squirrelminspeedsquirrelmaxspeed if random randint( = return speed else return -speed def getrandomoffcamerapos(cameraxcamerayobjwidthobjheight) create rect of the camera view camerarect pygame rect(cameraxcameraywinwidthwinheight while true |
10,734 | random randint(camerax winwidthcamerax ( winwidth) random randint(cameray winheightcameray ( winheight) create rect object with the random coordinates and use colliderect( to make sure the right edge isn' in the camera view objrect pygame rect(xyobjwidthobjheight if not objrect colliderect(camerarect) return xy def makenewsquirrel(cameraxcameray) sq { generalsize random randint( multiplier random randint( sq['width'(generalsize random randint( )multiplier sq['height'(generalsize random randint( )multiplier sq[' ']sq[' 'getrandomoffcamerapos(cameraxcameraysq['width']sq['height'] sq['movex'getrandomvelocity( sq['movey'getrandomvelocity( if sq['movex' squirrel is facing left sq['surface'pygame transform scale(l_squir_img(sq['width']sq['height']) elsesquirrel is facing right sq['surface'pygame transform scale(r_squir_img(sq['width']sq['height']) sq['bounce' sq['bouncerate'random randint( sq['bounceheight'random randint( return sq def makenewgrass(cameraxcameray) gr { gr['grassimage'random randint( len(grassimages gr['width'grassimages[ get_width( gr['height'grassimages[ get_height( gr[' ']gr[' 'getrandomoffcamerapos(cameraxcameraygr['width']gr['height'] gr['rect'pygame rect(gr[' ']gr[' ']gr['width']gr['height'] return gr def isoutsideactivearea(cameraxcamerayobj) return false if camerax and cameray are more than email questions to the authoral@inventwithpython com |
10,735 | half-window length beyond the edge of the window boundsleftedge camerax winwidth boundstopedge cameray winheight boundsrect pygame rect(boundsleftedgeboundstopedgewinwidth winheight objrect pygame rect(obj[' ']obj[' ']obj['width']obj['height'] return not boundsrect colliderect(objrect if __name__ ='__main__' main(the usual setup code squirrel eat squirrel ( katamari damacy clone by al sweigart al@inventwithpython com creative commons by-nc-sa us import randomsystimemathpygame from pygame locals import fps frames per second to update the screen winwidth width of the program' windowin pixels winheight height in pixels half_winwidth int(winwidth half_winheight int(winheight grasscolor ( white ( red ( the start of the program assigns several constant variables this program frequently makes use of the half length of the width and height of the window so much that the half_winwidth and half_winheight variables store these numbers cameraslack moving the camera how far from the center the squirrel moves before the --camera slack|is described later basicallyit means that the camera will begin following the player squirrel when it moves pixels away from the center of the window moverate bouncerate how fast the player moves how fast the player bounces (large is slower |
10,736 | bounceheight how high the player bounces startsize how big the player starts off winsize how big the player needs to be to win invulntime how long the player is invulnerable after being hit in seconds gameovertime how long the "game overtext stays on the screen in seconds maxhealth how much health the player starts with numgrass number of grass objects in the active area numsquirrels number of squirrels in the active area squirrelminspeed slowest squirrel speed squirrelmaxspeed fastest squirrel speed dirchangefreq chance of direction change per frame left 'left right 'rightthe comments next to these constants explains what the constant variable is used for describing the data structures "" this program has three data structures to represent the playerenemy squirrelsand grass background objects the data structures are dictionaries with the following keys keys used by all three data structures 'xthe left edge coordinate of the object in the game world (not pixel coordinate on the screen 'ythe top edge coordinate of the object in the game world (not pixel coordinate on the screen 'rectthe pygame rect object representing where on the screen the object is located player data structure keys 'surfacethe pygame surface object that stores the image of the squirrel which will be drawn to the screen 'facingeither set to left or rightstores which direction the player is facing 'sizethe width and height of the player in pixels (the width height are always the same 'bouncerepresents at what point in bounce the player is in means standing (no bounce)up to bouncerate (the completion of the bounce 'healthan integer showing how many more times the player can be hit by larger squirrel before dying enemy squirrel data structure keysemail questions to the authoral@inventwithpython com |
10,737 | 'surfacethe pygame surface object that stores the image of the squirrel which will be drawn to the screen 'movexhow many pixels per frame the squirrel moves horizontally negative integer is moving to the lefta positive to the right 'moveyhow many pixels per frame the squirrel moves vertically negative integer is moving upa positive moving down 'widththe width of the squirrel' imagein pixels 'heightthe height of the squirrel' imagein pixels 'bouncerepresents at what point in bounce the player is in means standing (no bounce)up to bouncerate (the completion of the bounce 'bounceratehow quickly the squirrel bounces lower number means quicker bounce 'bounceheighthow high (in pixelsthe squirrel bounces grass data structure keys 'grassimagean integer that refers to the index of the pygame surface object in grassimages used for this grass object ""the comments from lines to are in one largemulti-line string they describe the keys in the player squirrelenemy squirreland grass objects in pythona multi-line string value by itself works as multi-line comment the main(function def main() global fpsclockdisplaysurfbasicfontl_squir_imgr_squir_imggrassimages pygame init( fpsclock pygame time clock( pygame display set_icon(pygame image load('gameicon png') displaysurf pygame display set_mode((winwidthwinheight) pygame display set_caption('squirrel eat squirrel' basicfont pygame font font('freesansbold ttf' the first several lines of the main(function are the same setup code that we've seen in our previous game programs the pygame display set_icon(is pygame function that sets the icon in the window' title bar (just like pygame display set_caption(sets the caption text in the title barthe single argument to pygame display set_icon(is surface object of small image the ideal image size is pixelsalthough you can use other sized images the image will just be compressed into smaller size to be used as the window' icon |
10,738 | the pygame transform flip(function load the image files l_squir_img pygame image load('squirrel png'r_squir_img pygame transform flip(l_squir_imgtruefalsegrassimages [for in range( )grassimages append(pygame image load('grass% pngi)the image for the player and enemy squirrels is loaded from squirrel png on line make sure that this png file is in the same folder as squirrel pyotherwise you will get the error pygame errorcouldn' open squirrel png the image in squirrel png (which you can download from squirrel facing to the left we also need surface object that contains picture of the squirrel facing to the right instead of creating second png image filewe can call the pygame transform flip(function this function has three parametersthe surface object with the image to flipa boolean value to do horizontal flipand boolean value to do vertical flip by passing true for the second parameter and false for the third parameterthe surface object that returns has the image of the squirrel facing to the right the original surface object in l_squir_img that we passed in is unchanged here are examples of images being horizontally and vertically flippedoriginal horizontal flip vertical flip horizontal and vertical flip while truerungame(after the setup in main(is completethe game begins with rungame(being called more detailed game state than usual def rungame() set up variables for the start of new game email questions to the authoral@inventwithpython com |
10,739 | invulnerablemode false if the player is invulnerable invulnerablestarttime time the player became invulnerable gameovermode false if the player has lost gameoverstarttime time the player lost winmode false if the player has won the squirrel eat squirrel game has quite few variables that track the game state these variables will be explained in more detail later when they are used in the code the usual text creation code white create the surfaces to hold game text gameoversurf basicfont render('game over'truewhitegameoverrect gameoversurf get_rect(gameoverrect center (half_winwidthhalf_winheightwinsurf basicfont render('you have achieved omega squirrel!'truewinrect winsurf get_rect(winrect center (half_winwidthhalf_winheightwinsurf basicfont render('(press "rto restart )'truewhitewinrect winsurf get_rect(winrect center (half_winwidthhalf_winheight these variables contain surface objects with the --game over||--you have achieved omega squirrel!||and --(press "rto restart )|text that appears on the screen after the game ends (with either the player losing or winningcameras camerax and cameray are where the middle of the camera view is camerax cameray the camerax and cameray variables track the game coordinates of the --camera|imagine the game world as an infinite space this couldof coursenever fit on any screen we can only draw portion of the infinite space on the screen we call the area of this portion camerabecause it is as though our screen is just the area of the game world in front what camera would see here' picture of the game world (an infinite green fieldand the area that the camera can view |
10,740 | as you can seethe game world xy coordinates keep getting bigger and smaller forever the game world origin is where the ( game world coordinates are you can see that the three squirrels are located (in game world coordinatesat (- - )( )and ( - but we can only display pixel area on the screen (though this can change if we pass different numbers to the pygame display set_mode(function)so we need to track where the camera' origin is located in game world coordinates in the picture abovethe camera is placed at (- - in game world coordinates the picture below shows the same field and squirrelsexcept everything is given in camera coordinatesemail questions to the authoral@inventwithpython com |
10,741 | the area that the camera can see (called the camera viewhas it' center (that isits originat the game world coordinates (- - since what the camera sees is displayed on the player' screenthe --camera|coordinates are the same as the --pixel|coordinates to find out the pixel coordinates of the squirrels (that iswhere on the screen they appear)take the game coordinates of the squirrel and subtract the game coordinates of the camera' origin so the squirrel on the left has game world coordinates of (- - but appears at ( on the screen in pixel coordinates (for the coordinate- - and for the coordinate- - when we do the same calculation to find the pixel coordinates of the other two squirrelswe find that they exist outside of the range of the screen this is why they don' appear in the camera' view the "active areathe --active area|is just name came up with to describe the area of the game world that the camera views plus an area around it the size of the camera area |
10,742 | calculating if something is in the active area or not is explained in the isoutsideactivearea(function' explanation later in this when we create new enemy squirrel or grass objectswe don' want them to be created inside the view of the camerasince it'll appear that they just pop out of nowhere but we also don' want to create them too far away from the camerabecause then they may never wander into the camera' view inside the active area but outside the camera is where squirrel and grass objects can safely be created alsowhen squirrel and grass objects are beyond the border of the active area then they are far away enough to delete so that they don' take up memory any more objects that far away aren' needed since it is much less likely that they'll come back into view of the camera if you have ever played super mario world on the super nintendothere is good youtube video explaining how super mario world' camera system works you can find this video at keeping track of the location of things in the game world grassobjs [stores all the grass objects in the game squirrelobjs [stores all the non-player squirrel objects stores the player object playerobj {'surface'pygame transform scale(l_squir_img(startsizestartsize)) 'facing'left 'size'startsize ' 'half_winwidth ' 'half_winheight 'bounce': 'health'maxhealth moveleft false moveright false moveup false movedown false the grassobjs variable holds list of all the grass objects in the game as new grass objects are createdthey are added to this list as grass objects are deletedthey are removed from this list the same goes for the squirrelobjs variable and the enemy squirrel objects the playerobj variable is not listbut just the dictionary value itself the move variables on lines to track which of arrow keys (or wasd keysare being held downjust like in few of the previous game programs email questions to the authoral@inventwithpython com |
10,743 | starting off with some grass start off with some random grass images on the screen for in range( )grassobjs append(makenewgrass(cameraxcameray)grassobjs[ ][' 'random randint( winwidthgrassobjs[ ][' 'random randint( winheightthe active area should start off with few grass objects visible on the screen the makenewgrass(function will create and return grass object that is randomly located somewhere in the active area but outside the camera view this is what we normally want when we call makenewgrass()but since we want to make sure the first few grass objects are on the screenthe and coordinates are overwritten the game loop while truemain game loop the game looplike the game loops in the previous game programswill do event handlingupdating the game stateand drawing everything to the screen checking to disable invulnerability invulntime check if we should turn off invulnerability if invulnerablemode and time time(invulnerablestarttime invulnerablemode false when the player gets hit by an enemy squirrel and does not diewe make the player invulnerable for couple seconds (since the invulntime constant is set to during this timethe player' squirrel flashes and the won' take any damage from other squirrels if the --invulnerability mode|time is overline will set invulnerablemode to false moving the enemy squirrels move all the squirrels for sobj in squirrelobjsmove the squirreland adjust for their bounce sobj[' '+sobj['movex'sobj[' '+sobj['movey'the enemy squirrels all move according to the values in their 'movexand 'moveykeys if these values are positivethe squirrels move right or down if these values are negativethey |
10,744 | move left or up the larger the valuethe farther they move on each iteration through the game loop (which means they move fasterthe for loop on line will apply this moving code to each of the enemy squirrel objects in the squirrelobjs list firstline and will adjust their 'xand 'ykeysvalues sobj['bounce'+ if sobj['bounce'sobj['bouncerate']sobj['bounce' reset bounce amount the value in sobj['bounce'is incremented on each iteration of the game loop for each squirrel when this value is the squirrel is at the very beginning of its bounce when this value is equal to the value in sobj['bouncerate'the value is at its end (this is why smaller sobj['bouncerate'value makes for faster bounce if sobj['bouncerate'is then it only takes three iterations through the game loop for the squirrel to do full bounce if sobj['bouncerate'were then it would take ten iterations when sobj['bounce'gets larger than sobj['bouncerate']then it needs to be reset to this is what lines and do random chance they change direction if random randint( dirchangefreq sobj['movex'getrandomvelocity( sobj['movey'getrandomvelocity( if sobj['movex' faces right sobj['surface'pygame transform scale(r_squir_img(sobj['width']sobj['height']) elsefaces left sobj['surface'pygame transform scale(l_squir_img(sobj['width']sobj['height'])there is chance on each iteration through the game loop that the squirrel will randomly change speed and direction on line the random randint( call randomly selects an integer out of possible integers if this number is less than dirchangefreq (which we set to on line then new value will be set for sobj['movex'and sobj['movey'because this means the squirrel might have changed directionthe surface object in sobj['surface'should be replaced by new one that is properly facing left or right and scaled to the squirrel' size this is what lines to determine note that line gets surface object scaled from r_squir_img and line gets one scaled from l_squir_img email questions to the authoral@inventwithpython com |
10,745 | removing the far away grass and squirrel objects go through all the objects and see if any need to be deleted for in range(len(grassobjs - - )if isoutsideactivearea(cameraxcameraygrassobjs[ ])del grassobjs[ifor in range(len(squirrelobjs - - )if isoutsideactivearea(cameraxcameraysquirrelobjs[ ])del squirrelobjs[iduring each iteration of the game loopthe code will check all of the grass and enemy squirrel objects to see if they are outside the --active area|the isoutsideactivearea(function takes the current coordinates of the camera (which are stored in camerax and camerayand the grass/enemy squirrel objectand returns true if the object is not located in the active area if this is the casethis object is deleted on line (for grass objectsor line (for squirrel objectsthis is how squirrel and grass objects get deleted when the player moves far enough away from them (or when the enemy squirrels move away far enough from the playerthis ensures that there is always number of squirrels and grass objects near the player when deleting items in listiterate over the list in reverse deleting squirrel and grass objects is done with the del operator howevernotice that the for loop on line and pass arguments to the range(function so that the numbering starts at the index of the last item and then decrements by - (unlike incrementing by as it normally doesuntil it reaches the number - we are iterating backwards over the list' indexes compared to how it is normally done this is done because we are iterating over the list that we are also deleting items from to see why this reverse order is neededsay we had the following list valueanimals ['cat''mouse''dog''horse'so we wanted to write code to delete any instances of the string 'dogfrom this list we might think to write out code like thisfor in range(len(animals))if animals[ ='dog'del animals[ibut if we ran this codewe would get an indexerror error that looks like thistraceback (most recent call last) |
10,746 | file ""line in indexerrorlist index out of range to see why this error happenslet' walk through the code firstthe animals list would be set to ['cat''mouse''dog''horse'and len(animalswould return this means that the call to range( would cause the for loop to iterate with the values and when the for loop iterates with set to the if statement' condition will be true and the del animals[istatement will delete animals[ this means that afterwards the animals list will be ['cat''mouse''horse'the indexes of all the items after 'dogare all shifted down by one because the 'dogvalue was removed but on the next iteration through the for loopi is set to but animals[ is out of bounds because the valid indexes of the animals list is no longer to but to the original call to range(was for list with items in it the list changed in lengthbut the for loop is set up for the original length howeverif we iterate from the last index of the list to we don' run into this problem the following program deletes the 'dogstring from the animals list without causing an indexerror erroranimals ['cat''mouse''dog''horse'for in range(len(animals - - )if animals[ ='dog'del animals[ithe reason this code doesn' cause an error is because the for loop iterates over and on the first iterationthe code checks if animals[ is equal to 'dogit isn' (animals[ is 'horse'so the code moves on to the next iteration then animals[ is checked if it equals 'dogit doesso animals[ is deleted after animals[ is deletedthe animals list is set to ['cat''mouse''horse'on the next iterationi is set to there is value at animals[ (the 'mousevalue)so no error is caused it doesn' matter that all the items in the list after 'doghave shifted down by onebecause since we started at the end of the list and are going towards the frontall of those items have already been checked similarlywe can delete grass and squirrel objects from the grassobjs and squirrelobjs lists without error because the for loop on lines and iterate in reverse order email questions to the authoral@inventwithpython com |
10,747 | adding new grass and squirrel objects add more grass squirrels if we don' have enough while len(grassobjsnumgrassgrassobjs append(makenewgrass(cameraxcameray)while len(squirrelobjsnumsquirrelssquirrelobjs append(makenewsquirrel(cameraxcameray)remember that the numgrass constant was set to and the numsquirrels constant was set to at the beginning of the programthese variables are set so that we can be sure there are always plenty of grass and squirrel objects in the active area at all times if the length of the grassobjs or squirrelobjs drops below numgrass or numsquirrels respectivelythen new grass and squirrel objects are created the makenewgrass(and makenewsquirrel(functions that create these objects are explained later in this camera slackand moving the camera view adjust camerax and cameray if beyond the "camera slackplayercenterx playerobj[' 'int(playerobj['size' playercentery playerobj[' 'int(playerobj['size' if (camerax half_winwidthplayercenterx cameraslackcamerax playercenterx cameraslack half_winwidth elif playercenterx (camerax half_winwidthcameraslackcamerax playercenterx cameraslack half_winwidth if (cameray half_winheightplayercentery cameraslackcameray playercentery cameraslack half_winheight elif playercentery (cameray half_winheightcameraslackcameray playercentery cameraslack half_winheight the camera' position (which is stored as integers in the camerax and cameray variablesneeds to be updated when the player moves over 've called the number of pixels the player can move before the camera gets updated the --camera slack|line set the cameraslack constant to which our program will take to mean that the player squirrel can move pixels from the center before the camera position gets updated to follow the squirrel in order to understand the equations used in the if statements on lines and you should note that (camerax half_winwidthand (cameray half_winheightare the xy game world coordinates currently at the center of the screen the playercenterx and playercentery is set to the middle of the player' squirrel' positionalso in game world coordinates for line if the center coordinate minus the player' center coordinate is greater than the cameraslack valuethat means the player is more pixels to the right of the center of the |
10,748 | camera than the camera slack should allow the camerax value needs to be updated so that the player squirrel is just at the edge of the camera slack this is why line sets camerax to playercenterx cameraslack half_winwidth note that the camerax variable is changednot the playerobj[' 'value we want to move the cameranot the player the other three if statements follow similar logic for the leftup and down sides drawing the backgroundgrasssquirrelsand health meter draw the green background displaysurf fill(grasscolorline begins the code that starts drawing the contents of the display surface object firstline draws green color for the background this will paint over all of the previous contents of the surface so that we can start drawing the frame from scratch draw all the grass objects on the screen for gobj in grassobjsgrect pygame rect(gobj[' 'cameraxgobj[' 'cameraygobj['width']gobj['height']displaysurf blit(grassimages[gobj['grassimage']]grectthe for loop on line goes through all the grass objects in the grassobjs list and creates rect object from the xywidthand height information stored in it this rect object is stored in variable named grect on line grect is used in the blit(method call to draw the grass image on the display surface note that gobj['grassimage'only contains an integer that is an index to grassimages grassimages is list of surface objects that contain all the grass images surface objects take up much more memory than just single integerand all the grass objects with similar gobj['grassimage'values look identical so it makes sense to only have each grass image stored once in grassimages and simply store integers in the grass objects themselves draw the other squirrels for sobj in squirrelobjs sobj['rect'pygame rect(sobj[' 'camerax sobj[' 'cameray getbounceamount(sobj['bounce']sobj['bouncerate']sobj['bounceheight']) sobj['width'] sobj['height']email questions to the authoral@inventwithpython com |
10,749 | displaysurf blit(sobj['surface']sobj['rect']the for loop that draws all the enemy squirrel game objects is similar to the previous for loopexcept that the rect object it creates is saved in the 'rectkey' value of the squirrel dictionary the reason the code does this is because we will use this rect object later to check if the enemy squirrels have collided with the player squirrel note that the top parameter for the rect constructor is not just sobj[' 'cameray but sobj[' 'cameray getbounceamount(sobj['bounce']sobj['bouncerate']sobj['bounceheight']the getbounceamount(function will return the number of pixels that the top value should be raised alsothere is no common list of surface objects of the squirrel imageslike there was with grass game objects and grassimages each enemy squirrel game object has its own surface object stored in the 'surfacekey this is because the squirrel images can be scaled to different sizes draw the player squirrel flashison round(time time() = after drawing the grass and enemy squirrelsthe code will draw the player' squirrel howeverthere is one case where we would skip drawing the player' squirrel when the player collides with larger enemy squirrelthe player takes damage and flashes for little bit to indicate that the player is temporarily invulnerable this flashing effect is done by drawing the player squirrel on some iterations through the game loop but not on others the player squirrel will be drawn on game loop iterations for tenth of secondand then not drawn on the game loop iterations for tenth of second this repeats over and over again as long as the player is invulnerable (whichin the codemeans that the invulnerablemode variable is set to trueour code will make the flashing last for two secondssince was stored in the invulntime constant variable on line to determine if the flash is on or notline grabs the current time from time time(let' use the example where this function call returns this value is passed to round()which rounds it to one digit past the decimal point (since is passed as round()' second parameterthis means round(will return the value this value is then multiplied by to become once we have it as an integerwe can do the --mod two|trick first discussed in the memory puzzle to see if it is even or odd evaluates to which means that flashison will be set to falsesince = is false |
10,750 | in facttime time(will keep returning values that will end up putting false into flashison until which is the next tenth second this is why the flashison variable will constantly have false for one tenth of secondand then true for the next one tenth of second (no matter how many iterations happen in that tenth of second if not gameovermode and not (invulnerablemode and flashison) playerobj['rect'pygame rect(playerobj[' 'camerax playerobj[' 'cameray getbounceamount(playerobj['bounce']bounceratebounceheight) playerobj['size'] playerobj['size'] displaysurf blit(playerobj['surface']playerobj['rect']there are three things that must be true before we draw the player' squirrel the game must currently be going on (which happens while gameovermode is falseand the player is not invulnerable and not flashing (which happens while invulnerablemode and flashison are falsethe code for drawing the player' squirrel is almost identical to the code for drawing the enemy squirrels draw the health meter drawhealthmeter(playerobj['health']the drawhealthmeter(function draws the indicator at the top left corner of the screen that tells the player how many times the player squirrel can be hit before dying this function will be explained later in this the event handling loop for event in pygame event get()event handling loop if event type =quitterminate(the first thing that is checked in the event handling loop is if the quit event has been generated if sothen the program should be terminated elif event type =keydownif event key in (k_upk_w)movedown false moveup true elif event key in (k_downk_s)email questions to the authoral@inventwithpython com |
10,751 | moveup false movedown true if the up or down arrow keys have been pressed (or their wasd equivalents)then the move variable (moverightmovedownetc for that direction should be set to true and the move variable for the opposite direction should be set to false elif event key in (k_leftk_a) moveright false moveleft true if playerobj['facing'=rightchange player image playerobj['surface'pygame transform scale(l_squir_img(playerobj['size']playerobj['size']) playerobj['facing'left elif event key in (k_rightk_d) moveleft false moveright true if playerobj['facing'=leftchange player image playerobj['surface'pygame transform scale(r_squir_img(playerobj['size']playerobj['size']) playerobj['facing'right the moveleft and moveright variables should also be set when the left or right arrow keys are pressed alsothe value in playerobj['facing'should be updated to either left or right if the player squirrel is now facing new directionthe playerobj['surface'value should be replaced with correctly scaled image of the squirrel facing the new direction line is run if the left arrow key was pressed and checks if the player squirrel was facing right if that was sothen new scaled surface object of the player squirrel image is stored in playerobj['surface'the code in line ' elif statement handles the opposite case elif winmode and event key =k_rreturn if the player has won the game by growing large enough (in which casewinmode will be set to trueand the key has been pressedthen rungame()should return this will end the current gameand new game will start the next time that rungame(gets called elif event type =keyupstop moving the player' squirrel if event key in (k_leftk_a)moveleft false |
10,752 | elif event key in (k_rightk_d)moveright false elif event key in (k_upk_w)moveup false elif event key in (k_downk_s)movedown false if the player lets up on any of the arrow or wasd keysthen the code should set the move variable for that direction to false this will stop the squirrel from moving in that direction any more elif event key =k_escapeterminate(if the key that was pressed was the esc keythen terminate the program moving the playerand accounting for bounce if not gameovermodeactually move the player if moveleftplayerobj[' '-moverate if moverightplayerobj[' '+moverate if moveupplayerobj[' '-moverate if movedownplayerobj[' '+moverate the code inside the if statement on line will move the player' squirrel around only if the game is not over (this is why pressing on the arrow keys after the player' squirrel dies will have no effect depending on which of the move variables is set to truethe playerobj dictionary should have its playerobj[' 'and playerobj[' 'values changed by moverate (this is why larger value in moverate makes the squirrel move faster if (moveleft or moveright or moveup or movedownor playerobj['bounce'! playerobj['bounce'+ if playerobj['bounce'bouncerate playerobj['bounce' reset bounce amount email questions to the authoral@inventwithpython com |
10,753 | the value in playerobj['bounce'keeps track of at what point in bouncing the player is at this variable stores an integer value from to bouncerate just like the bounce value for the enemy squirrelsa playerobj['bounce'value of means the player squirrel is at the start of bounce and value of bouncerate means the player squirrel is at the end of the bounce the player squirrel will bounce whenever the player is movingor if the player has stopped moving but the squirrel hasn' finished its current bounce this condition is captured in the if statement on line if any of the move variables is set to true or the current playerobj['bounce'is not (which means the player is currently in bounce)then the variable should be incremented on line because the playerobj['bounce'variable should only be in the range of to bouncerateif incrementing it makes it larger than bouncerateit should be reset back to collision detectioneat or be eaten check if the player has collided with any squirrels for in range(len(squirrelobjs)- - - )sqobj squirrelobjs[ithe for loop on will go run code on each of the enemy squirrel game objects in squirrelobjs notice that the parameters to range(on line start at the last index of squirrelobjs and decrement this is because the code inside this for loop may end up deleting some of these enemy squirrel game objects (if the player' squirrel ends up eating them)so it is important to iterate from the end down to the front the reason why was explained previously in the --when deleting items in listiterate over the list in reverse|section if 'rectin sqobj and playerobj['rect'colliderect(sqobj['rect']) player/squirrel collision has occurred if sqobj['width'sqobj['height'<playerobj['size']** player is larger and eats the squirrel playerobj['size'+int(sqobj['width'sqobj['height'])** del squirrelobjs[iif the player' squirrel is equal or larger than the size of the enemy squirrel it has collided withthen the player' squirrel will eat that squirrel and grow the number that is added to the 'size |
10,754 | key in the player object (that isthe growthis calculated based on the enemy squirrel' size on line here' graph showing the growth from different sized squirrels notice that larger squirrels cause more growthint(sqobj['width'sqobj['height'])** growth size of eaten squirrel (width heightsoaccording to the charteating squirrel that has width and height of (that isan area of pixelswould cause the player to grow pixels wider and taller line deletes the eaten squirrel object from the squirrelobjs list so that it will no longer appear on the screen or have its position updated if playerobj['facing'=left playerobj['surface'pygame transform scale(l_squir_img(playerobj['size']playerobj['size']) if playerobj['facing'=right playerobj['surface'pygame transform scale(r_squir_img(playerobj['size']playerobj['size'])the player' squirrel image needs to be updated now that the squirrel is larger this can be done by passing the original squirrel image in l_squir_img or r_squir_img to the pygame transform scale(functionwhich will return an enlarged version of the image depending on whether playerobj['facing'is equal to left or right determines which original squirrel image we pass to the function if playerobj['size'winsizewinmode true turn on "win modeemail questions to the authoral@inventwithpython com |
10,755 | the way the player wins the game is by getting the squirrel to have size larger than the integer stored in the winsize constant variable if this is truethen the winmode variable is set to true code in the other parts of this function will handle displaying the congratulations text and checking for the player to press the key to restart the game elif not invulnerablemodeplayer is smaller and takes damage invulnerablemode true invulnerablestarttime time time(playerobj['health'- if playerobj['health'= gameovermode true turn on "game over modegameoverstarttime time time(if the player' area was not equal to or larger than the area of the enemy squirreland invulnerablemode was not set to truethen the player will take damage from colliding with this larger squirrel to prevent the player from being damaged several times by the same squirrel immediatelywe will briefly make the player invulnerable to further squirrel attacks by setting invulnerablemode to true on line line will set invulnerablestarttime to the current time (which is returned by time time()so that lines and can know when to set invulnerablemode to false line decrements the player' health by because there is chance that the player' health is now at line checks for this andif sosets gameovermode to true and gameoverstarttime to the current time the game over screen elsegame is overshow "game overtext displaysurf blit(gameoversurfgameoverrectif time time(gameoverstarttime gameovertimereturn end the current game when the player has diedthe --game over|text (which is on the surface object in the gameoversurf variablewill be shown on the screen for the number of seconds that is in the gameovertime constant once this amount of time has elapsedthen the rungame(function will return |
10,756 | this lets the enemy squirrels continue to be animated and moving around for few seconds after the player dies and before the next game starts the --game over screen|in squirrel eat squirrel does not wait until the player presses key before new game starts winning check if the player has won if winmodedisplaysurf blit(winsurfwinrectdisplaysurf blit(winsurf winrect pygame display update(fpsclock tick(fpsthe winmode variable is set to true on line if the player has reached certain size (which is dictated by the winsize constantall that happens when the player has won is that the --you have achieved omega squirrel!|text (which is on the surface object stored in the winsurf variableand the --(press -- |to restart )|text (which is on the surface object stored in the winsurf variableappears on the screen the game continues until the user presses the keyat which point the program execution will return from rungame(the event handling code for the key is done on lines and drawing graphical health meter def drawhealthmeter(currenthealth) for in range(currenthealth)draw red health bars pygame draw rect(displaysurfred( ( maxhealthi ) for in range(maxhealth)draw the white outlines pygame draw rect(displaysurfwhite( ( maxhealthi ) to draw the health meterfirst the for loop on line draws the filled-in red rectangle for the amount of health the player has then the for loop on line draws an unfilled white rectangle for all of the possible health the player could have (which is the integer value stored in the maxhealth constantnote that the pygame display update(function is not called in drawhealthmeter(the same old terminate(function def terminate() pygame quit( sys exit(email questions to the authoral@inventwithpython com |
10,757 | the terminate(function works the same as in the previous game programs the mathematics of the sine function def getbounceamount(currentbouncebounceratebounceheight) returns the number of pixels to offset based on the bounce larger bouncerate means slower bounce larger bounceheight means higher bounce currentbounce will always be less than bouncerate return int(math sin(math pi float(bouncerate)currentbounce bounceheight there is mathematical function (which is similar to functions in programming in that they both --return|or --evaluate|to number based on their parameterscalled sine (pronounced like --sign|and often abbreviated as --sin||you may have learned about it in math classbut if you haven' it will be explained here python has this mathematic function as python function in the math module you can pass an int or float value to math sin()and it will return float value that is called the --sine value|in the interactive shelllet' see what math sin(returns for some valuesimport math math sin( math sin( math sin( math sin( - math sin( - it seems really hard to predict what value math sin(is going to return based on what value we pass it (which might make you wonder what math sin(is useful forbut if we graph the sine values of the integers through on graphwe would get this |
10,758 | values returned by math sin( math sin(arg - - - arg you can kind of see wavy pattern in the values returned by math sin(if you figure out the sine values for more numbers besides integers (for example and and so onand then connect the dots with linesyou can see this wavy pattern more easilyvalues returned by math sin( math sin(arg - - - arg in factif you kept adding more and more data points to this graphyou would see that the sine wave looks like thisemail questions to the authoral@inventwithpython com |
10,759 | notice that math sin( returns then gradually increases until math sin( returns then it begins to decrease until math sin( returns the number is special number in mathematics called pi (pronounced the same as delicious --pie||this value is also stored in the constant variable pi in the math module (which is why line uses the variablemath pi)which is technically the float value since we want wavy-looking bounce for our squirrelwe'll only pay attention to the return values of math sin(for the arguments to values returned by math sin( math sin(arg arg let' take look at the return value of getbounceamount(and figure out what it does exactly return int(math sin(math pi float(bouncerate)currentbounce bounceheightremember that on line we set the bouncerate constant to this means that our code will only increment playerobj['bounce'from to and that we want to split up the range of floating-point values from to into partswhich we can do with simple division each of the equal parts of the length on the graph for the --sine wave bounce|is you can see that when playerobj['bounce'is at (halfway between and )the value passed to the math sin(call is math pi which is (halfway between and then math sin( will return which is the highest part of the sine wave (and the highest part of the sine wave happens half way through the wave |
10,760 | as playerobj['bounce'gets its value incrementedthe getbounceamount(function will return values that have the same bounce shape that the sine wave has from to if you want to make the bounce higherthan increase the bounceheight constant if you want to make the bounce slowerthan increase the bouncerate constant the sine function is concept from trigonometry mathematics if you' like to learn more about the sine wavethe wikipedia page has detailed informationbackwards compatibility with python version the reason we call float(to convert bouncerate to floating point number is simply so that this program will work in python version in python version the division operator will evaluate to floating point value even if both of the operands are integerslike thispython version howeverin python version the division operator will only evaluate to floating point value if one of the operands is also floating point value if both operands are integersthen python ' division operator will evaluate to an integer value (rounding down if needed)like thispython version but if we always convert one of the values to floating point value with the float(functionthen the division operator will evaluate to float value no matter which version of python runs this source code making these changes so that our code works with older versions of software is called backwards compatibility it is important to maintain backwards compatibilitybecause email questions to the authoral@inventwithpython com |
10,761 | not everyone will always be running the latest version of software and you want to ensure that the code you write works with as many computers as possible you can' always make your python code backwards compatible with python but if it' possible then you should do it otherwisewhen people with python try to run your games will get error messages and think that your program is buggy list of some differences between python and python can be found at the getrandomvelocity(function def getrandomvelocity() speed random randint(squirrelminspeedsquirrelmaxspeed if random randint( = return speed else return -speed the getrandomvelocity(function is used to randomly determine how fast an enemy squirrel will move the range of this velocity is set in the squirrelminspeed and squirrelmaxspeed constantsbut on top of thatthe speed is either negative (indicating the squirrel goes to the left or upor positive (indicating the squirrel goes to the right or downthere is fifty-fifty chance for the random speed to be positive or negative finding place to add new squirrels and grass def getrandomoffcamerapos(cameraxcamerayobjwidthobjheight) create rect of the camera view camerarect pygame rect(cameraxcameraywinwidthwinheight while true random randint(camerax winwidthcamerax ( winwidth) random randint(cameray winheightcameray ( winheight) create rect object with the random coordinates and use colliderect( to make sure the right edge isn' in the camera view objrect pygame rect(xyobjwidthobjheight if not objrect colliderect(camerarect) return xy when new squirrel or grass object is created in the game worldwe want it to be within the active area (so that it is near the player' squirrelbut not within the view of the camera (so that it doesn' just suddenly pop into existence on the screento do thiswe create rect object that |
10,762 | represents the area of the camera (using cameraxcameraywinwidthand winheight constantsnextwe randomly generate numbers for the xy coordinates that would be within the active area the active area' left and top edge are winwidth and winheight pixels to the left and up of camerax and cameray so the active area' left and top edge are at camerax winwidth and cameray winheight the active area' width and height are also three times the size of the winwidth and winheightas you can see in this image (where winwidth is set to pixels and winheight set to pixels)this means the right and bottom edges will be at camerax ( winwidthand cameray ( winheightline will check if the random xy coordinates would collide with the camera view' rect object if notthen those coordinates are returned if sothen the while loop on line will keep generating new coordinates until it finds acceptable ones creating enemy squirrel data structures def makenewsquirrel(cameraxcameray) sq { generalsize random randint( multiplier random randint( sq['width'(generalsize random randint( )multiplier sq['height'(generalsize random randint( )multiplier sq[' ']sq[' 'getrandomoffcamerapos(cameraxcameraysq['width']sq['height'] sq['movex'getrandomvelocity( sq['movey'getrandomvelocity(creating enemy squirrel game objects is similar to making the grass game objects the data for each enemy squirrel is also stored in dictionary the width and height are set to random sizes on line and the generalsize variable is used so that the width and height of each email questions to the authoral@inventwithpython com |
10,763 | squirrel aren' too different from each other otherwiseusing completely random numbers for width and height could give us very tall and skinny squirrels or very short and wide squirrels the width and height of the squirrel are this general size with random number from to added to it (for slight variation)and then multiplied by the multiplier variable the original xy coordinate position of the squirrel will be random location that the camera cannot seeto prevent the squirrels from just --popping|into existence on the screen the speed and direction are also randomly selected by the getrandomvelocity(function flipping the squirrel image if sq['movex' squirrel is facing left sq['surface'pygame transform scale(l_squir_img(sq['width']sq['height']) elsesquirrel is facing right sq['surface'pygame transform scale(r_squir_img(sq['width']sq['height']) sq['bounce' sq['bouncerate'random randint( sq['bounceheight'random randint( return sq the l_squir_img and r_squir_img constants contain surface objects with left-facing and right-facing squirrel images on them new surface objects will be made using the pygame transform scale(function to match the squirrel' width and height (stored in sq['width'and sq['height'respectivelyafter thatthe three bounce-related values are randomly generated (except for sq['bounce'which is because the squirrel always starts at the beginning of the bounceand the dictionary is returned on line creating grass data structures def makenewgrass(cameraxcameray) gr { gr['grassimage'random randint( len(grassimages gr['width'grassimages[ get_width( gr['height'grassimages[ get_height( gr[' ']gr[' 'getrandomoffcamerapos(cameraxcameraygr['width']gr['height'] gr['rect'pygame rect(gr[' ']gr[' ']gr['width']gr['height'] return gr |
10,764 | the grass game objects are dictionaries with the usual ' '' ''width''height'and 'rectkeys but also 'grassimagekey which is number from to one less than the length of the grassimages list this number will determine what image the grass game object has for exampleif the value of the grass object' 'grassimagekey is then it will use the surface object stored at grassimages[ for its image checking if outside the active area def isoutsideactivearea(cameraxcamerayobj) return false if camerax and cameray are more than half-window length beyond the edge of the window boundsleftedge camerax winwidth boundstopedge cameray winheight boundsrect pygame rect(boundsleftedgeboundstopedgewinwidth winheight objrect pygame rect(obj[' ']obj[' ']obj['width']obj['height'] return not boundsrect colliderect(objrectthe isoutsideactivearea(will return true if the object you pass it is outside of the --active area|that is dictated by the camerax and cameray parameters remember that the active area is an area around the camera view the size of the camera view (which has width and height set by winwidth and winheight)like thiswe can create rect object that represents the active area by passing camerax winwidth for the left edge value and cameray winheight for the top edge valueand then winwidth and winheight for the width and height once we have the active area represented as rect objectwe can use the colliderect(method to determine if the object in the obj parameter is collides with (that isis inside ofthe active area rect object email questions to the authoral@inventwithpython com |
10,765 | since the player squirrelenemy squirrel and grass objects all have ' '' ''widthand 'heightkeysthe isoutsideactivearea(code can work with any type of those game objects if __name__ ='__main__' main(finallyafter all the functions have been definedthe program will run the main(function and start the game summary squirrel eat squirrel was our first game to have multiple enemies moving around the board at once the key to having several enemies was using dictionary value with identical keys for each enemy squirrelso that the same code could be run on each of them during an iteration through the game loop the concept of the camera was also introduced cameras weren' needed for our previous games because the entire game world fit onto one screen howeverwhen you make your own games that involve player moving around large game worldyou will need code to handle converting between the game world' coordinate system and the screen' pixel coordinate system finallythe mathematical sine function was introduced to give realistic squirrel hops (no matter how tall or long each hop wasyou don' need to know lot of math to do programming in most casesjust knowing additionmultiplicationand negative numbers is fine howeverif you study mathematicsyou'll often find several uses for math to make your games cooler for additional programming practiceyou can download buggy versions of squirrel eat squirrel from |
10,766 | star pusher how to play star pusher star pusher is sokoban or --box pusher|clone the player is in room with several stars there are star marks on the grounds of some of the tile sprites in the room the player must figure out how to push the stars on top of the tiles with star marks the player cannot push star if there is wall or another star behind it the player cannot pull starsso if star gets pushed into cornerthe player will have to restart the level when all of the stars have been pushed onto star-marked floor tilesthe level is complete and the next level starts each level is made up of grid of tile images tile sprites are images of the same size that can be placed next to each other to form more complex images with few floor and wall tileswe can create levels of many interesting shapes and sizes the level files are not included in the source code insteadyou can either create the level files yourself or download them level file with levels can be downloaded from level file is in the same folder as the starpusher py file otherwise you will get this error messageassertionerrorcannot find the level filestarpusherlevels txt the level designs were originally made david skinner you can download more puzzles from his website at source code to star pusher this source code can be downloaded from messageslook at the line number that is mentioned in the error message and check your code for any typos you can also copy and paste your code into the web form at email questions to the authoral@inventwithpython com |
10,767 | book the level file can be downloaded from downloaded from alsojust like the squirrelgrassand enemy --objects|in the squirrel eat squirrel gamewhen say --map objects||--game state objects||or --level objects|in this do not mean objects in the object-oriented programming sense these --objects|are really just dictionary valuesbut it is easier to refer to them as objects since they represent things in the game world star pusher ( sokoban clone by al sweigart al@inventwithpython com creative commons by-nc-sa us import randomsyscopyospygame from pygame locals import fps frames per second to update the screen winwidth width of the program' windowin pixels winheight height in pixels half_winwidth int(winwidth half_winheight int(winheight the total width and height of each tile in pixels tilewidth tileheight tilefloorheight cam_move_speed how many pixels per frame the camera moves the percentage of outdoor tiles that have additional decoration on themsuch as tree or rock outside_decoration_pct brightblue white ( bgcolor brightblue textcolor white up 'up down 'down left 'left right 'right |
10,768 | def main() global fpsclockdisplaysurfimagesdicttilemappingoutsidedecomappingbasicfontplayerimagescurrentimage pygame initialization and basic set up of the global variables pygame init( fpsclock pygame time clock( because the surface object stored in displaysurf was returned from the pygame display set_mode(functionthis is the surface object that is drawn to the actual computer screen when pygame display update(is called displaysurf pygame display set_mode((winwidthwinheight) pygame display set_caption('star pusher' basicfont pygame font font('freesansbold ttf' global dict value that will contain all the pygame surface objects returned by pygame image load( imagesdict {'uncovered goal'pygame image load('redselector png') 'covered goal'pygame image load('selector png') 'star'pygame image load('star png') 'corner'pygame image load('wall block tall png') 'wall'pygame image load('wood block tall png') 'inside floor'pygame image load('plain block png') 'outside floor'pygame image load('grass block png') 'title'pygame image load('star_title png') 'solved'pygame image load('star_solved png') 'princess'pygame image load('princess png') 'boy'pygame image load('boy png') 'catgirl'pygame image load('catgirl png') 'horngirl'pygame image load('horngirl png') 'pinkgirl'pygame image load('pinkgirl png') 'rock'pygame image load('rock png') 'short tree'pygame image load('tree_short png') 'tall tree'pygame image load('tree_tall png') 'ugly tree'pygame image load('tree_ugly png') these dict values are globaland map the character that appears in the level file to the surface object it represents tilemapping {' 'imagesdict['corner'] '#'imagesdict['wall'] ' 'imagesdict['inside floor'] 'imagesdict['outside floor']email questions to the authoral@inventwithpython com |
10,769 | outsidedecomapping {' 'imagesdict['rock'] ' 'imagesdict['short tree'] ' 'imagesdict['tall tree'] ' 'imagesdict['ugly tree'] playerimages is list of all possible characters the player can be currentimage is the index of the player' current player image currentimage playerimages [imagesdict['princess'] imagesdict['boy'] imagesdict['catgirl'] imagesdict['horngirl'] imagesdict['pinkgirl'] startscreen(show the title screen until the user presses key read in the levels from the text file see the readlevelsfile(for details on the format of this file and how to make your own levels levels readlevelsfile('starpusherlevels txt' currentlevelindex the main game loop this loop runs single levelwhen the user finishes that levelthe next/previous level is loaded while truemain game loop run the level to actually start playing the game result runlevel(levelscurrentlevelindex if result in ('solved''next') go to the next level currentlevelindex + if currentlevelindex >len(levels) if there are no more levelsgo back to the first one currentlevelindex elif result ='back' go to the previous level currentlevelindex - if currentlevelindex if there are no previous levelsgo to the last one currentlevelindex len(levels)- elif result ='reset' pass do nothing loop re-calls runlevel(to reset the level def runlevel(levelslevelnum) global currentimage levelobj levels[levelnum |
10,770 | mapobj decoratemap(levelobj['mapobj']levelobj['startstate']['player'] gamestateobj copy deepcopy(levelobj['startstate'] mapneedsredraw true set to true to call drawmap( levelsurf basicfont render('level % of % (levelobj['levelnum' totalnumoflevels) textcolor levelrect levelsurf get_rect( levelrect bottomleft ( winheight mapwidth len(mapobjtilewidth mapheight (len(mapobj[ ] (tileheight tilefloorheighttileheight max_cam_x_pan abs(half_winheight int(mapheight )tilewidth max_cam_y_pan abs(half_winwidth int(mapwidth )tileheight leveliscomplete false track how much the camera has moved cameraoffsetx cameraoffsety track if the keys to move the camera are being held down cameraup false cameradown false cameraleft false cameraright false while truemain game loop reset these variables playermoveto none keypressed false for event in pygame event get()event handling loop if event type =quit player clicked the "xat the corner of the window terminate( elif event type =keydown handle key presses keypressed true if event key =k_left playermoveto left elif event key =k_right playermoveto right elif event key =k_up playermoveto up elif event key =k_down playermoveto down email questions to the authoral@inventwithpython com |
10,771 | set the camera move mode elif event key =k_acameraleft true elif event key =k_dcameraright true elif event key =k_wcameraup true elif event key =k_scameradown true elif event key =k_nreturn 'nextelif event key =k_breturn 'backelif event key =k_escapeterminate(esc key quits elif event key =k_backspacereturn 'resetreset the level elif event key =k_pchange the player image to the next one currentimage + if currentimage >len(playerimages)after the last player imageuse the first one currentimage mapneedsredraw true elif event type =keyupunset the camera move mode if event key =k_acameraleft false elif event key =k_dcameraright false elif event key =k_wcameraup false elif event key =k_scameradown false if playermoveto !none and not leveliscompleteif the player pushed key to movemake the move (if possibleand push any stars that are pushable moved makemove(mapobjgamestateobjplayermovetoif movedincrement the step counter gamestateobj['stepcounter'+ |
10,772 | mapneedsredraw true if islevelfinished(levelobjgamestateobj) level is solvedwe should show the "solved!image leveliscomplete true keypressed false displaysurf fill(bgcolor if mapneedsredraw mapsurf drawmap(mapobjgamestateobjlevelobj['goals'] mapneedsredraw false if cameraup and cameraoffsety max_cam_x_pan cameraoffsety +cam_move_speed elif cameradown and cameraoffsety -max_cam_x_pan cameraoffsety -cam_move_speed if cameraleft and cameraoffsetx max_cam_y_pan cameraoffsetx +cam_move_speed elif cameraright and cameraoffsetx -max_cam_y_pan cameraoffsetx -cam_move_speed adjust mapsurf' rect object based on the camera offset mapsurfrect mapsurf get_rect( mapsurfrect center (half_winwidth cameraoffsetxhalf_winheight cameraoffsety draw mapsurf to the displaysurf surface object displaysurf blit(mapsurfmapsurfrect displaysurf blit(levelsurflevelrect stepsurf basicfont render('steps% (gamestateobj['stepcounter']) textcolor steprect stepsurf get_rect( steprect bottomleft ( winheight displaysurf blit(stepsurfsteprect if leveliscomplete is solvedshow the "solved!image until the player has pressed key solvedrect imagesdict['solved'get_rect( solvedrect center (half_winwidthhalf_winheight displaysurf blit(imagesdict['solved']solvedrect if keypressed return 'solvedemail questions to the authoral@inventwithpython com |
10,773 | pygame display update(draw displaysurf to the screen fpsclock tick( def decoratemap(mapobjstartxy) """makes copy of the given map object and modifies it here is what is done to it walls that are corners are turned into corner pieces the outside/inside floor tile distinction is made tree/rock decorations are randomly added to the outside tiles returns the decorated map object "" startxstarty startxy syntactic sugar copy the map object so we don' modify the original passed mapobjcopy copy deepcopy(mapobj remove the non-wall characters from the map data for in range(len(mapobjcopy)) for in range(len(mapobjcopy[ ])) if mapobjcopy[ ][yin ('$'''@''+''*') mapobjcopy[ ][ flood fill to determine inside/outside floor tiles floodfill(mapobjcopystartxstarty'' ' convert the adjoined walls into corner tiles for in range(len(mapobjcopy)) for in range(len(mapobjcopy[ ])) if mapobjcopy[ ][ ='#' if (iswall(mapobjcopyxy- and iswall(mapobjcopyx+ )or (iswall(mapobjcopyx+ yand iswall(mapobjcopyxy+ )or (iswall(mapobjcopyxy+ and iswall(mapobjcopyx- )or (iswall(mapobjcopyx- yand iswall(mapobjcopyxy- )) mapobjcopy[ ][ ' elif mapobjcopy[ ][ =and random randint( outside_decoration_pct |
10,774 | mapobjcopy[ ][yrandom choice(list(outsidedecomapping keys()) return mapobjcopy def isblocked(mapobjgamestateobjxy) """returns true if the (xyposition on the map is blocked by wall or starotherwise return false "" if iswall(mapobjxy) return true elif len(mapobjor len(mapobj[ ]) return true and aren' actually on the map elif (xyin gamestateobj['stars'] return true star is blocking return false def makemove(mapobjgamestateobjplayermoveto) """given map and game state objectsee if it is possible for the player to make the given move if it isthen change the player' position (and the position of any pushed starif notdo nothing returns true if the player movedotherwise false "" make sure the player can move in the direction they want playerxplayery gamestateobj['player' this variable is "syntactic sugartyping "starsis more readable than typing "gamestateobj['stars']in our code stars gamestateobj['stars' the code for handling each of the directions is so similar aside from adding or subtracting to the / coordinates we can simplify it by using the xoffset and yoffset variables if playermoveto =up xoffset yoffset - elif playermoveto =right xoffset yoffset elif playermoveto =downemail questions to the authoral@inventwithpython com |
10,775 | xoffset yoffset elif playermoveto =left xoffset - yoffset see if the player can move in that direction if iswall(mapobjplayerx xoffsetplayery yoffset) return false else if (playerx xoffsetplayery yoffsetin stars there is star in the waysee if the player can push it if not isblocked(mapobjgamestateobjplayerx (xoffset* )playery (yoffset* )) move the star ind stars index((playerx xoffsetplayery yoffset) stars[ind(stars[ind][ xoffsetstars[ind][ yoffset else return false move the player upwards gamestateobj['player'(playerx xoffsetplayery yoffset return true def startscreen() """display the start screen (which has the title and instructions until the player presses key returns none "" position the title image titlerect imagesdict['title'get_rect( topcoord topcoord tracks where to position the top of the text titlerect top topcoord titlerect centerx half_winwidth topcoord +titlerect height unfortunatelypygame' font text system only shows one line at timeso we can' use strings with \ newline characters in them so we will use list with each line in it instructiontext ['push the stars over the marks ' 'arrow keys to movewasd for camera controlp to change character ' 'backspace to reset levelesc to quit ' ' for next levelb to go back level ' start with drawing blank color to the entire window |
10,776 | displaysurf fill(bgcolor draw the title image to the window displaysurf blit(imagesdict['title']titlerect position and draw the text for in range(len(instructiontext)) instsurf basicfont render(instructiontext[ ] textcolor instrect instsurf get_rect( topcoord + pixels will go in between each line of text instrect top topcoord instrect centerx half_winwidth topcoord +instrect height adjust for the height of the line displaysurf blit(instsurfinstrect while truemain loop for the start screen for event in pygame event get() if event type =quit terminate( elif event type =keydown if event key =k_escape terminate( return user has pressed keyso return display the displaysurf contents to the actual screen pygame display update( fpsclock tick( def readlevelsfile(filename) assert os path exists(filename)'cannot find the level file% (filename mapfile open(filename' ' each level must end with blank line content mapfile readlines(['\ \ ' mapfile close( levels [will contain list of level objects levelnum maptextlines [contains the lines for single level' map mapobj [the map object made from the data in maptextlines for linenum in range(len(content)) process each line that was in the level file line content[linenumrstrip('\ \ ' if ';in lineemail questions to the authoral@inventwithpython com |
10,777 | ignore the linesthey're comments in the level file line line[:line find(';')if line !''this line is part of the map maptextlines append(lineelif line ='and len(maptextlines blank line indicates the end of level' map in the file convert the text in maptextlines into level object find the longest row in the map maxwidth - for in range(len(maptextlines))if len(maptextlines[ ]maxwidthmaxwidth len(maptextlines[ ]add spaces to the ends of the shorter rows this ensures the map will be rectangular for in range(len(maptextlines))maptextlines[ +(maxwidth len(maptextlines[ ])convert maptextlines to map object for in range(len(maptextlines[ ]))mapobj append([]for in range(len(maptextlines))for in range(maxwidth)mapobj[xappend(maptextlines[ ][ ]loop through the spaces in the map and find the @and characters for the starting game state startx none the and for the player' starting position starty none goals [list of (xytuples for each goal stars [list of (xyfor each star' starting position for in range(maxwidth)for in range(len(mapobj[ ]))if mapobj[ ][yin ('@''+')'@is player'+is player goal startx starty if mapobj[ ][yin (''+''*')is goal'*is star goal goals append((xy)if mapobj[ ][yin ('$''*')'$is star stars append((xy) |
10,778 | basic level design sanity checks assert startx !none and starty !none'level % (around line %sin % is missing "@or "+to mark the start point (levelnum+ linenumfilename assert len(goals 'level % (around line %sin % must have at least one goal (levelnum+ linenumfilename assert len(stars>len(goals)'level % (around line %sin % is impossible to solve it has % goals but only % stars (levelnum+ linenumfilenamelen(goals)len(stars) create level object and starting game state object gamestateobj {'player'(startxstarty) 'stepcounter' 'stars'stars levelobj {'width'maxwidth 'height'len(mapobj) 'mapobj'mapobj 'goals'goals 'startstate'gamestateobj levels append(levelobj reset the variables for reading the next map maptextlines [ mapobj [ gamestateobj { levelnum + return levels def floodfill(mapobjxyoldcharacternewcharacter) """changes any values matching oldcharacter on the map object to newcharacter at the (xypositionand does the same for the positions to the leftrightdownand up of (xy)recursively "" in this gamethe flood fill algorithm creates the inside/outside floor distinction this is "recursivefunction for more info on the flood fill algorithmsee if mapobj[ ][ =oldcharacter mapobj[ ][ynewcharacter if len(mapobj and mapobj[ + ][ =oldcharacter floodfill(mapobjx+ yoldcharacternewcharactercall right if and mapobj[ - ][ =oldcharacteremail questions to the authoral@inventwithpython com |
10,779 | floodfill(mapobjx- yoldcharacternewcharactercall left if len(mapobj[ ] and mapobj[ ][ + =oldcharacter floodfill(mapobjxy+ oldcharacternewcharactercall down if and mapobj[ ][ - =oldcharacter floodfill(mapobjxy- oldcharacternewcharactercall up def drawmap(mapobjgamestateobjgoals) """draws the map to surface objectincluding the player and stars this function does not call pygame display update()nor does it draw the "leveland "stepstext in the corner "" mapsurf will be the single surface object that the tiles are drawn onso that it is easy to position the entire map on the displaysurf surface object firstthe width and height must be calculated mapsurfwidth len(mapobjtilewidth mapsurfheight (len(mapobj[ ] (tileheight tilefloorheighttileheight mapsurf pygame surface((mapsurfwidthmapsurfheight) mapsurf fill(bgcolorstart with blank color on the surface draw the tile sprites onto this surface for in range(len(mapobj)) for in range(len(mapobj[ ])) spacerect pygame rect(( tilewidthy (tileheight tilefloorheight)tilewidthtileheight) if mapobj[ ][yin tilemapping basetile tilemapping[mapobj[ ][ ] elif mapobj[ ][yin outsidedecomapping basetile tilemapping[' first draw the base ground/wall tile mapsurf blit(basetilespacerect if mapobj[ ][yin outsidedecomapping draw any tree/rock decorations that are on this tile mapsurf blit(outsidedecomapping[mapobj[ ][ ]]spacerect elif (xyin gamestateobj['stars'] if (xyin goals goal and star are on this spacedraw goal first mapsurf blit(imagesdict['covered goal']spacerect then draw the star sprite mapsurf blit(imagesdict['star']spacerect elif (xyin goals draw goal without star on it mapsurf blit(imagesdict['uncovered goal']spacerect |
10,780 | last draw the player on the board if (xy=gamestateobj['player'] notethe value "currentimagerefers to key in "playerimageswhich has the specific player image we want to show mapsurf blit(playerimages[currentimage]spacerect return mapsurf def islevelfinished(levelobjgamestateobj) """returns true if all the goals have stars in them "" for goal in levelobj['goals'] if goal not in gamestateobj['stars'] found space with goal but no star on it return false return true def terminate() pygame quit( sys exit( if __name__ ='__main__' main(the initial setup star pusher ( sokoban clone by al sweigart al@inventwithpython com creative commons by-nc-sa us import randomsyscopyospygame from pygame locals import fps frames per second to update the screen winwidth width of the program' windowin pixels winheight height in pixels half_winwidth int(winwidth half_winheight int(winheight the total width and height of each tile in pixels tilewidth email questions to the authoral@inventwithpython com |
10,781 | tileheight tilefloorheight cam_move_speed how many pixels per frame the camera moves the percentage of outdoor tiles that have additional decoration on themsuch as tree or rock outside_decoration_pct brightblue white ( bgcolor brightblue textcolor white up 'up down 'down left 'left right 'rightthese constants are used in various parts of the program the tilewidth and tileheight variables show that each of the tile images are pixels wide and pixels tall howeverthese tiles overlap with each other when drawn on the screen (this is explained later the tilefloorheight refers to the fact that the part of the tile that represents the floor is pixels tall here is diagram of the plain floor imagethe grassy tiles outside of the level' room will sometimes have extra decorations added to them (such as trees or rocksthe outside_decoration_pct constant shows what percentage of these tiles will randomly have these decorations def main() global fpsclockdisplaysurfimagesdicttilemappingoutsidedecomappingbasicfontplayerimagescurrentimage pygame initialization and basic set up of the global variables pygame init( fpsclock pygame time clock( because the surface object stored in displaysurf was returned |
10,782 | from the pygame display set_mode(functionthis is the surface object that is drawn to the actual computer screen when pygame display update(is called displaysurf pygame display set_mode((winwidthwinheight)pygame display set_caption('star pusher'basicfont pygame font font('freesansbold ttf' this is the usual pygame setup that happens at the beginning of the program global dict value that will contain all the pygame surface objects returned by pygame image load(imagesdict {'uncovered goal'pygame image load('redselector png')'covered goal'pygame image load('selector png')'star'pygame image load('star png')'corner'pygame image load('wall block tall png')'wall'pygame image load('wood block tall png')'inside floor'pygame image load('plain block png')'outside floor'pygame image load('grass block png')'title'pygame image load('star_title png')'solved'pygame image load('star_solved png')'princess'pygame image load('princess png')'boy'pygame image load('boy png')'catgirl'pygame image load('catgirl png')'horngirl'pygame image load('horngirl png')'pinkgirl'pygame image load('pinkgirl png')'rock'pygame image load('rock png')'short tree'pygame image load('tree_short png')'tall tree'pygame image load('tree_tall png')'ugly tree'pygame image load('tree_ugly png')the imagesdict is dictionary where all of the loaded images are stored this makes it easier to use in other functionssince only the imagesdict variable needs to be made global if we stored each of these images in separate variablesthen all variables (for the images used in this gamewould need to be made global dictionary containing all of the surface objects with the images is easier to handle these dict values are globaland map the character that appears in the level file to the surface object it represents tilemapping {' 'imagesdict['corner']'#'imagesdict['wall']' 'imagesdict['inside floor']'imagesdict['outside floor']email questions to the authoral@inventwithpython com |
10,783 | the data structure for the map is just list of single character strings the tilemapping dictionary links the characters used in this map data structure to the images that they represent (this will become more clear in the drawmap(function' explanation outsidedecomapping {' 'imagesdict['rock']' 'imagesdict['short tree']' 'imagesdict['tall tree']' 'imagesdict['ugly tree']the outsidedecomapping is also dictionary that links the characters used in the map data structure to images that were loaded the --outside decoration|images are drawn on top of the outdoor grassy tile playerimages is list of all possible characters the player can be currentimage is the index of the player' current player image currentimage playerimages [imagesdict['princess']imagesdict['boy']imagesdict['catgirl']imagesdict['horngirl']imagesdict['pinkgirl']the playerimages list stores the images used for the player the currentimage variable tracks the index of the currently selected player image for examplewhen currentimage is set to then playerimages[ ]which is the --princess|player imageis drawn to the screen startscreen(show the title screen until the user presses key read in the levels from the text file see the readlevelsfile(for details on the format of this file and how to make your own levels levels readlevelsfile('starpusherlevels txt'currentlevelindex the startscreen(function will keep displaying the initial start screen (which also has the instructions for the gameuntil the player presses key when the player presses keythe startscreen(function returns and then reads in the levels from the level file the player starts off on the first levelwhich is the level object in the levels list at index the main game loop this loop runs single levelwhen the user finishes that levelthe next/previous level is loaded while truemain game loop run the level to actually start playing the game |
10,784 | result runlevel(levelscurrentlevelindexthe runlevel(function handles all the action for the game it is passed list of level objectsand the integer index of the level in that list to be played when the player has finished playing the levelrunlevel(will return one of the following strings'solved(because the player has finished putting all the stars on the goals)'next(because the player wants to skip to the next level)'back(because the player wants to go back to the previous level)and 'reset(because the player wants to start playing the current level over againmaybe because they pushed star into corner if result in ('solved''next')go to the next level currentlevelindex + if currentlevelindex >len(levels)if there are no more levelsgo back to the first one currentlevelindex elif result ='back'go to the previous level currentlevelindex - if currentlevelindex if there are no previous levelsgo to the last one currentlevelindex len(levels)- if runlevel(has returned the strings 'solvedor 'next'then we need to increment levelnum by if this increments levelnum beyond the number of levels there arethen levelnum is set back at the opposite is done if 'backis returnedthen levelnum is decremented by if this makes it go below then it is set to the last level (which is len(levels)- elif result ='reset'pass do nothing loop re-calls runlevel(to reset the level if the return value was 'reset'then the code does nothing the pass statement does nothing (like comment)but is needed because the python interpreter expects an indented line of code after an elif statement we could remove lines and from the source code entirelyand the program will still work just the same the reason we include it here is for program readabilityso that if we make changes to the code laterwe won' forget that runlevel(can also return the string 'resetemail questions to the authoral@inventwithpython com |
10,785 | def runlevel(levelslevelnum) global currentimage levelobj levels[levelnum mapobj decoratemap(levelobj['mapobj']levelobj['startstate']['player'] gamestateobj copy deepcopy(levelobj['startstate']the levels list contains all the level objects that were loaded from the level file the level object for the current level (which is what levelnum is set tois stored in the levelobj variable map object (which makes distinction between indoor and outdoor tilesand decorates the outdoor tiles with trees and rocksis returned from the decoratemap(function and to track the state of the game while the player plays this levela copy of the game state object that is stored in levelobj is made using the copy deepcopy(function the game state object copy is made because the game state object stored in levelobj['startstate'represents the game state at the very beginning of the leveland we do not want to modify this otherwiseif the player restarts the levelthe original game state for that level will be lost the copy deepcopy(function is used because the game state object is dictionary of that has tuples but technicallythe dictionary contains references to tuples (references are explained in detail at dictionary will make copy of the references but not the values they refer toso that both the copy and the original dictionary still refer to the same tuples the copy deepcopy(function solves this problem by making copies of the actual tuples in the dictionary this way we can guarantee that changing one dictionary will not affect the other dictionary mapneedsredraw true set to true to call drawmap( levelsurf basicfont render('level % of % (levelobj['levelnum' totalnumoflevels) textcolor levelrect levelsurf get_rect( levelrect bottomleft ( winheight mapwidth len(mapobjtilewidth mapheight (len(mapobj[ ] (tileheight tilefloorheighttileheight max_cam_x_pan abs(half_winheight int(mapheight )tilewidth max_cam_y_pan abs(half_winwidth int(mapwidth )tileheight leveliscomplete false track how much the camera has moved cameraoffsetx |
10,786 | cameraoffsety track if the keys to move the camera are being held downcameraup false cameradown false cameraleft false cameraright false more variables are set at the start of playing level the mapwidth and mapheight variables are the size of the maps in pixels the expression for calculating mapheight is bit complicated since the tiles overlap each other only the bottom row of tiles is the full height (which accounts for the tileheight part of the expression)all of the other rows of tiles (which number as (len(mapobj[ ] )are slightly overlapped this means that they are effectively each only (tileheight tilefloorheightpixels tall the camera in star pusher can be moved independently of the player moving around the map this is why the camera needs its own set of --moving|variablescameraupcameradowncameraleftand cameraright the cameraoffsetx and cameraoffsety variables track the position of the camera while truemain game loop reset these variablesplayermoveto none keypressed false for event in pygame event get()event handling loop if event type =quitplayer clicked the "xat the corner of the window terminate(the playermoveto variable will be set to the direction constant that the player intends to move the player character on the map the keypressed variable tracks if any key has been pressed during this iteration of the game loop this variable is checked later when the player has solved the level elif event type =keydownhandle key presses keypressed true if event key =k_leftplayermoveto left elif event key =k_rightplayermoveto right elif event key =k_upemail questions to the authoral@inventwithpython com |
10,787 | playermoveto up elif event key =k_downplayermoveto down set the camera move mode elif event key =k_acameraleft true elif event key =k_dcameraright true elif event key =k_wcameraup true elif event key =k_scameradown true elif event key =k_nreturn 'nextelif event key =k_breturn 'backelif event key =k_escapeterminate(esc key quits elif event key =k_backspacereturn 'resetreset the level elif event key =k_pchange the player image to the next one currentimage + if currentimage >len(playerimages)after the last player imageuse the first one currentimage mapneedsredraw true elif event type =keyupunset the camera move mode if event key =k_acameraleft false elif event key =k_dcameraright false elif event key =k_wcameraup false elif event key =k_scameradown false this code handles what to do when the various keys are pressed if playermoveto !none and not leveliscompleteif the player pushed key to movemake the move |
10,788 | (if possibleand push any stars that are pushable moved makemove(mapobjgamestateobjplayermovetoif movedincrement the step counter gamestateobj['stepcounter'+ mapneedsredraw true if islevelfinished(levelobjgamestateobj)level is solvedwe should show the "solved!image leveliscomplete true keypressed false if the playermoveto variable is no longer set to nonethen we know the player intended to move the call to makemove(handles changing the xy coordinates of the player' position in the gamestateobjas well as pushing any stars the return value of makemove(is stored in moved if this value is truethen the player character was moved in that direction if the value was falsethen the player must have tried to move into tile that was wallor push star that had something behind it in this casethe player can' move and nothing on the map changes displaysurf fill(bgcolorif mapneedsredrawmapsurf drawmap(mapobjgamestateobjlevelobj['goals']mapneedsredraw false the map does not need to be redrawn on each iteration through the game loop in factthis game program is complicated enough that doing so would cause slight (but noticeableslowdown in the game and the map really only needs to be redrawn when something has changed (such as the player moving or star being pushedso the surface object in the mapsurf variable is only updated with call to the drawmap(function when the mapneedsredraw variable is set to true after the map has been drawn on line the mapneedsredraw variable is set to false if you want to see how the program slows down by drawing on each iteration through the game loopcomment out line and rerun the program you will notice that moving the camera is significantly slower if cameraup and cameraoffsety max_cam_x_pancameraoffsety +cam_move_speed elif cameradown and cameraoffsety -max_cam_x_panemail questions to the authoral@inventwithpython com |
10,789 | cameraoffsety -cam_move_speed if cameraleft and cameraoffsetx max_cam_y_pancameraoffsetx +cam_move_speed elif cameraright and cameraoffsetx -max_cam_y_pancameraoffsetx -cam_move_speed if the camera movement variables are set to true and the camera has not gone past ( panned passedthe boundaries set by the max_cam_x_pan and max_cam_y_panthen the camera location (stored in cameraoffsetx and cameraoffsetyshould move over by cam_move_speed pixels note that there is an if and elif statement on lines and for moving the camera up and downand then separate if and elif statement on lines and this waythe user can move the camera both vertically and horizontally at the same time this wouldn' be possible if line were an elif statement adjust mapsurf' rect object based on the camera offset mapsurfrect mapsurf get_rect( mapsurfrect center (half_winwidth cameraoffsetxhalf_winheight cameraoffsety draw mapsurf to the displaysurf surface object displaysurf blit(mapsurfmapsurfrect displaysurf blit(levelsurflevelrect stepsurf basicfont render('steps% (gamestateobj['stepcounter']) textcolor steprect stepsurf get_rect( steprect bottomleft ( winheight displaysurf blit(stepsurfsteprect if leveliscomplete is solvedshow the "solved!image until the player has pressed key solvedrect imagesdict['solved'get_rect( solvedrect center (half_winwidthhalf_winheight displaysurf blit(imagesdict['solved']solvedrect if keypressed return 'solved pygame display update(draw displaysurf to the screen fpsclock tick( |
10,790 | lines to position the camera and draw the map and other graphics to the display surface object in displaysurf if the level is solvedthen the victory graphic is also drawn on top of everything else the keypressed variable will be set to true if the user pressed key during this iterationat which point the runlevel(function returns def iswall(mapobjxy) """returns true if the (xyposition on the map is wallotherwise return false "" if len(mapobjor len(mapobj[ ]) return false and aren' actually on the map elif mapobj[ ][yin ('#'' ') return true wall is blocking return false the iswall(function returns true if there is wall on the map object at the xy coordinates passed to the function wall objects are represented as either 'xor '#string in the map object def decoratemap(mapobjstartxy) """makes copy of the given map object and modifies it here is what is done to it walls that are corners are turned into corner pieces the outside/inside floor tile distinction is made tree/rock decorations are randomly added to the outside tiles returns the decorated map object "" startxstarty startxy syntactic sugar copy the map object so we don' modify the original passed mapobjcopy copy deepcopy(mapobjthe decoratemap(function alters the data structure mapobj so that it isn' as plain as it appears in the map file the three things that decoratemap(changes are explained in the comment at the top of the function remove the non-wall characters from the map data for in range(len(mapobjcopy))for in range(len(mapobjcopy[ ]))if mapobjcopy[ ][yin ('$'''@''+''*')email questions to the authoral@inventwithpython com |
10,791 | mapobjcopy[ ][ythe map object has characters that represent the position of the playergoalsand stars these are necessary for the map object (they're stored in other data structures after the map file is readso they are converted to blank spaces flood fill to determine inside/outside floor tiles floodfill(mapobjcopystartxstarty'' 'the floodfill(function will change all of the tiles inside the walls from characters to 'ocharacters it does this using programming concept called recursionwhich is explained in --recursive functions|section later in this convert the adjoined walls into corner tiles for in range(len(mapobjcopy)) for in range(len(mapobjcopy[ ])) if mapobjcopy[ ][ ='#' if (iswall(mapobjcopyxy- and iswall(mapobjcopyx+ )or (iswall(mapobjcopyx+ yand iswall(mapobjcopyxy+ )or (iswall(mapobjcopyxy+ and iswall(mapobjcopyx- )or (iswall(mapobjcopyx- yand iswall(mapobjcopyxy- )) mapobjcopy[ ][ ' elif mapobjcopy[ ][ =and random randint( outside_decoration_pct mapobjcopy[ ][yrandom choice(list(outsidedecomapping keys()) return mapobjcopy the largemulti-line if statement on line checks if the wall tile at the current xy coordinates are corner wall tile by checking if there are wall tiles adjacent to it that form corner shape if sothe '#string in the map object that represents normal wall is changed to 'xstring which represents corner wall tile def isblocked(mapobjgamestateobjxy) """returns true if the (xyposition on the map is blocked by wall or starotherwise return false "" |
10,792 | if iswall(mapobjxy)return true elif len(mapobjor len(mapobj[ ])return true and aren' actually on the map elif (xyin gamestateobj['stars']return true star is blocking return false there are three cases where space on the map would be blockedif there is stara wallor the coordinates of the space are past the edges of the map the isblocked(function checks for these three cases and returns true if the xy coordinates are blocked and false if not def makemove(mapobjgamestateobjplayermoveto) """given map and game state objectsee if it is possible for the player to make the given move if it isthen change the player' position (and the position of any pushed starif notdo nothing returns true if the player movedotherwise false "" make sure the player can move in the direction they want playerxplayery gamestateobj['player' this variable is "syntactic sugartyping "starsis more readable than typing "gamestateobj['stars']in our code stars gamestateobj['stars' the code for handling each of the directions is so similar aside from adding or subtracting to the / coordinates we can simplify it by using the xoffset and yoffset variables if playermoveto =up xoffset yoffset - elif playermoveto =right xoffset yoffset elif playermoveto =down xoffset yoffset elif playermoveto =left xoffset - yoffset email questions to the authoral@inventwithpython com |
10,793 | see if the player can move in that direction if iswall(mapobjplayerx xoffsetplayery yoffset) return false else if (playerx xoffsetplayery yoffsetin stars there is star in the waysee if the player can push it if not isblocked(mapobjgamestateobjplayerx (xoffset* )playery (yoffset* )) move the star ind stars index((playerx xoffsetplayery yoffset) stars[ind(stars[ind][ xoffsetstars[ind][ yoffset else return false move the player upwards gamestateobj['player'(playerx xoffsetplayery yoffset return true the makemove(function checks to make sure if moving the player in particular direction is valid move as long as there isn' wall blocking the pathor star that has wall or star behind itthe player will be able to move in that direction the gamestateobj variable will be updated to reflect thisand the true value will be returned to tell the function' caller that the player was moved if there was star in the space that the player wanted to movethat star' position is also changed and this information is updated in the gamestateobj variable as well this is how the --star pushing|is implemented if the player is blocked from moving in the desired directionthen the gamestateobj is not modified and the function returns false def startscreen() """display the start screen (which has the title and instructions until the player presses key returns none "" position the title image titlerect imagesdict['title'get_rect( topcoord topcoord tracks where to position the top of the text titlerect top topcoord titlerect centerx half_winwidth topcoord +titlerect height unfortunatelypygame' font text system only shows one line at |
10,794 | timeso we can' use strings with \ newline characters in them so we will use list with each line in it instructiontext ['push the stars over the marks ' 'arrow keys to movewasd for camera controlp to change character ' 'backspace to reset levelesc to quit ' ' for next levelb to go back level 'the startscreen(function needs to display few different pieces of text down the center of the window we will store each line as string in the instructiontext list the title image (stored in imagesdict['title'as surface object (that was originally loaded from the star_title png file)will be positioned pixels from the top of the window this is because the integer was stored in the topcoord variable on line the topcoord variable will track the axis positioning of the title image and the instructional text the axis is always going to be set so that the images and text are centeredas it is on line for the title image on line the topcoord variable is increased by whatever the height of that image is this way we can modify the image and the start screen code won' have to be changed start with drawing blank color to the entire windowdisplaysurf fill(bgcolordraw the title image to the windowdisplaysurf blit(imagesdict['title']titlerectposition and draw the text for in range(len(instructiontext))instsurf basicfont render(instructiontext[ ] textcolorinstrect instsurf get_rect(topcoord + pixels will go in between each line of text instrect top topcoord instrect centerx half_winwidth topcoord +instrect height adjust for the height of the line displaysurf blit(instsurfinstrectline is where the title image is blitted to the display surface object the for loop starting on line will renderpositionand blit each instructional string in the instructiontext loop the topcoord variable will always be incremented by the size of the previously rendered text (line and additional pixels (on line so that there will be pixel gap between the lines of text while truemain loop for the start screen for event in pygame event get()email questions to the authoral@inventwithpython com |
10,795 | if event type =quitterminate(elif event type =keydownif event key =k_escapeterminate(return user has pressed keyso return display the displaysurf contents to the actual screen pygame display update(fpsclock tick(there is game loop in startscreen(that begins on line and handles events that indicate if the program should terminate or return from the startscreen(function until the player does eitherthe loop will keep calling pygame display update(and fpsclock tick(to keep the start screen displayed on the screen data structures in star pusher star pusher has specific format for the levelsmapsand game state data structures the "game statedata structure the game state object will be dictionary with three keys'player''stepcounter'and 'starsthe value at the 'playerkey will be tuple of two integers for the current xy position of the player the value at the 'stepcounterkey will be an integer that tracks how many moves the player has made in this level (so the player can try to solve the puzzle in the future with fewer stepsthe value at the 'starskey is list of two-integer tuples of xy values for each of the stars on the current level the "mapdata structure the map data structure is simply list of lists where the two indexes used represent the and coordinates of the map the value at each index in the list of lists is single-character string that represents the title that is on that map at each space'# wooden wall 'xa corner wall '@the starting space for the player on this level goal space '$ space where star is at the start of the level |
10,796 | '+ space with goal and the starting player' space '* space with goal and star at the start of the level grassy outdoor space 'oan inside floor space (this is lowercase letter onot zero ' rock on grass ' short tree on grass ' tall tree on grass ' an ugly tree on grass the "levelsdata structure the level object contains game state object (which will be the state used when the level first starts) map objectand few other values the level object itself is dictionary with the following keysthe value at the key 'widthis an integer of how many tiles wide the entire map is the value at the key 'heightis an integer of how many tiles tall the entire map is the value at the key 'mapobjis the map object for this level the value at the key 'goalsis list of two-integer tuples with the xy coordinates of each goal space on the map the value at the key 'startstateis game state object used to show the starting position of the stars and player at the start of the level reading and writing text files python has functions for reading files off of the player' hard drive this will be useful for having separate file keep all of the data for each level this is also good idea because in order to get new levelsthe player doesn' have to change the source code of the game but instead can just download new level files text files and binary files text files are files that contain simple text data text files are created in windows by the notepad applicationgedit on ubuntuand textedit on mac os there are many other programs called text editors that can create and modify text files idle' own file editor is text editor the difference between text editors and word processors (like microsoft wordor openoffice writeror iwork pagesis that text editors have text only you can' set the fontsizeor color of the text (idle automatically sets the color of the text based on what kind of python code it isbut you can' change this yourselfso it is still text editor the difference between text and binary files isn' important for this game programbut you can read about it at email questions to the authoral@inventwithpython com |
10,797 | only deal with text files writing to files to create filecall the open(function pass it two argumentsa string for the name of the fileand the string 'wto tell the open(function you want to open the file in --write|mode the open(function returns file objecttextfile open('hello txt'' 'if you run this code from the interactive shellthe hello txt file that this function creates will be created in the same folder that the python exe program is in (on windowsthis will probably be :\python if the open(function is called from py programthe file is created in the same folder that the py file is in the --write|mode tells open(to create the file if it does not exist if it does existthen open(will delete that file and create newblank file this is just like how an assignment statement can create new variableor overwrite the current value in an already existing variable this can be somewhat dangerous if you accidentally send filename of an important file to the open(function with 'was the second parameterit will be deleted this could result in having to reinstall the operating system on your computer and/or the launching of nuclear missiles the file object has method called write(which can be used to write text to the file just pass it string like you would pass string to the print(function the difference is that write(does not automatically add newline character ('\ 'to the end of the string if you want to add newlineyou will have to include it in the stringtextfile open('hello txt'' 'textfile write('this will be the content of the file \nhello world!\ 'to tell python that you are done writing content to this fileyou should call the close(method of the file object (although python will automatically close any opened file objects when the program ends textfile close( |
10,798 | reading from files to read the content of filepass the string 'rinstead of 'wto the open(function then call the readlines(method on the file object to read in the contents of the file lastclose the file by calling the close(method textfile open('hello txt'' 'content textfile readlines(textfile close(the readlines(method returns list of stringsone string for each line of text in the filecontent ['this will be the content of the file \ ''hello world!\ 'if you want to re-read the contents of that fileyou will have to call close(on the file object and re-open it as an alternative to readlines()you can also call the read(methodwhich will return the entire contents of the file as single string valuetextfile open('hello txt'' 'content textfile read(content 'this will be the content of the file \nhello world!\non side noteif you leave out the second parameter to the open(functionpython will assume you mean to open the file in read mode so open('foobar txt'' 'and open('foobar txt'do the exact same thing about the star pusher map file format we need the level text file to be in specific format which characters represent wallsor starsor the player' starting positionif we have the maps for multiple levelshow can we tell when one level' map ends and the next one beginsfortunatelythe map file format we will use is already defined for us there are many sokoban games out there (you can find more at map file format if you download the levels file from open it in text editoryou'll see something like thisstar pusher (sokoban cloneemail questions to the authoral@inventwithpython com |
10,799 | by al sweigart al@inventwithpython com everything after the is comment and will be ignored by the game that reads in this file the format is described atthe starting position of the player the starting position for pushable star goal where star needs to be pushed player goal star goal (spacean empty open space wall level maps are separated by blank line ( like to use at the start of the line since it is more visible tried to use the same format as other people use for their sokoban gamesso that loading new levels is easy just place the levels in text file and name it "starpusherlevels txt(after renaming this fileof coursestarting demo level########$@#########the comments at the top of the file explain the file' format when you load the first levelit looks like this |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.