id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
10,600 | email questions to the authoral@inventwithpython com |
10,601 | slide puzzle how to play slide puzzle the board is grid with fifteen tiles (numbered through going left to rightand one blank space the tiles start out in random positionsand the player must slide tiles around until the tiles are back in their original order source code to slide puzzle 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 slide puzzle by al sweigart al@inventwithpython com creative commons by-nc-sa us import pygamesysrandom from pygame locals import create the constants (go ahead and experiment with different values boardwidth number of columns in the board boardheight number of rows in the board tilesize |
10,602 | windowwidth windowheight fps blank none black white ( brightblue darkturquoise green bgcolor darkturquoise tilecolor green textcolor white bordercolor brightblue basicfontsize buttoncolor white buttontextcolor black messagecolor white xmargin int((windowwidth (tilesize boardwidth (boardwidth )) ymargin int((windowheight (tilesize boardheight (boardheight )) up 'up down 'down left 'left right 'right def main() global fpsclockdisplaysurfbasicfontreset_surfreset_rectnew_surfnew_rectsolve_surfsolve_rect pygame init( fpsclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) pygame display set_caption('slide puzzle' basicfont pygame font font('freesansbold ttf'basicfontsize store the option buttons and their rectangles in options reset_surfreset_rect maketext('reset'textcolortilecolorwindowwidth windowheight email questions to the authoral@inventwithpython com |
10,603 | new_surfnew_rect maketext('new game'textcolortilecolorwindowwidth windowheight solve_surfsolve_rect maketext('solve'textcolortilecolorwindowwidth windowheight mainboardsolutionseq generatenewpuzzle( solvedboard getstartingboard( solved board is the same as the board in start state allmoves [list of moves made from the solved configuration while truemain game loop slideto none the directionif anya tile should slide msg 'contains the message to show in the upper left corner if mainboard =solvedboard msg 'solved! drawboard(mainboardmsg checkforquit( for event in pygame event get()event handling loop if event type =mousebuttonup spotxspoty getspotclicked(mainboardevent pos[ ]event pos[ ] if (spotxspoty=(nonenone) check if the user clicked on an option button if reset_rect collidepoint(event pos) resetanimation(mainboardallmovesclicked on reset button allmoves [ elif new_rect collidepoint(event pos) mainboardsolutionseq generatenewpuzzle( clicked on new game button allmoves [ elif solve_rect collidepoint(event pos) resetanimation(mainboardsolutionseq allmovesclicked on solve button allmoves [ else check if the clicked tile was next to the blank spot blankxblanky getblankposition(mainboard if spotx =blankx and spoty =blanky slideto left elif spotx =blankx and spoty =blanky |
10,604 | slideto right elif spotx =blankx and spoty =blanky slideto up elif spotx =blankx and spoty =blanky slideto down elif event type =keyup check if the user pressed key to slide tile if event key in (k_leftk_aand isvalidmove(mainboardleft) slideto left elif event key in (k_rightk_dand isvalidmove(mainboardright) slideto right elif event key in (k_upk_wand isvalidmove(mainboardup) slideto up elif event key in (k_downk_sand isvalidmove(mainboarddown) slideto down if slideto slideanimation(mainboardslideto'click tile or press arrow keys to slide ' show slide on screen makemove(mainboardslideto allmoves append(slidetorecord the slide pygame display update( fpsclock tick(fps def terminate() pygame quit( sys exit( 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 def getstartingboard() return board data structure with tiles in the solved state email questions to the authoral@inventwithpython com |
10,605 | for exampleif boardwidth and boardheight are both this function returns [[ ][ ][ none] counter board [ for in range(boardwidth) column [ for in range(boardheight) column append(counter counter +boardwidth board append(column counter -boardwidth (boardheight boardwidth board[boardwidth- ][boardheight- none return board def getblankposition(board) return the and of board coordinates of the blank space for in range(boardwidth)) for in range(boardheight) if board[ ][ =none return (xy def makemove(boardmove) this function does not check if the move is valid blankxblanky getblankposition(board if move =up board[blankx][blanky]board[blankx][blanky board[blankx][blanky ]board[blankx][blanky elif move =down board[blankx][blanky]board[blankx][blanky board[blankx][blanky ]board[blankx][blanky elif move =left board[blankx][blanky]board[blankx ][blankyboard[blankx ][blanky]board[blankx][blanky elif move =right board[blankx][blanky]board[blankx ][blankyboard[blankx ][blanky]board[blankx][blanky def isvalidmove(boardmove) blankxblanky getblankposition(board return (move =up and blanky !len(board[ ] or (move =down and blanky ! or |
10,606 | (move =left and blankx !len(board or (move =right and blankx ! def getrandommove(boardlastmove=none) start with full list of all four moves validmoves [updownleftright remove moves from the list as they are disqualified if lastmove =up or not isvalidmove(boarddown) validmoves remove(down if lastmove =down or not isvalidmove(boardup) validmoves remove(up if lastmove =left or not isvalidmove(boardright) validmoves remove(right if lastmove =right or not isvalidmove(boardleft) validmoves remove(left return random move from the list of remaining moves return random choice(validmoves def getlefttopoftile(tilextiley) left xmargin (tilex tilesize(tilex top ymargin (tiley tilesize(tiley return (lefttop def getspotclicked(boardxy) from the pixel coordinatesget the board coordinates for tilex in range(len(board)) for tiley in range(len(board[ ])) lefttop getlefttopoftile(tilextiley tilerect pygame rect(lefttoptilesizetilesize if tilerect collidepoint(xy) return (tilextiley return (nonenone def drawtile(tilextileynumberadjx= adjy= ) draw tile at board coordinates tilex and tileyoptionally few pixels over (determined by adjx and adjy lefttop getlefttopoftile(tilextiley pygame draw rect(displaysurftilecolor(left adjxtop adjytilesizetilesize) textsurf basicfont render(str(number)truetextcoloremail questions to the authoral@inventwithpython com |
10,607 | textrect textsurf get_rect( textrect center left int(tilesize adjxtop int(tilesize adjy displaysurf blit(textsurftextrect def maketext(textcolorbgcolortopleft) create the surface and rect objects for some text textsurf basicfont render(texttruecolorbgcolor textrect textsurf get_rect( textrect topleft (topleft return (textsurftextrect def drawboard(boardmessage) displaysurf fill(bgcolor if message textsurftextrect maketext(messagemessagecolorbgcolor displaysurf blit(textsurftextrect for tilex in range(len(board)) for tiley in range(len(board[ ])) if board[tilex][tiley] drawtile(tilextileyboard[tilex][tiley] lefttop getlefttopoftile( width boardwidth tilesize height boardheight tilesize pygame draw rect(displaysurfbordercolor(left top width height ) displaysurf blit(reset_surfreset_rect displaysurf blit(new_surfnew_rect displaysurf blit(solve_surfsolve_rect def slideanimation(boarddirectionmessageanimationspeed) notethis function does not check if the move is valid blankxblanky getblankposition(board if direction =up movex blankx movey blanky elif direction =down movex blankx |
10,608 | movey blanky elif direction =left movex blankx movey blanky elif direction =right movex blankx movey blanky prepare the base surface drawboard(boardmessage basesurf displaysurf copy( draw blank space over the moving tile on the basesurf surface moveleftmovetop getlefttopoftile(movexmovey pygame draw rect(basesurfbgcolor(moveleftmovetoptilesizetilesize) for in range( tilesizeanimationspeed) animate the tile sliding over checkforquit( displaysurf blit(basesurf( ) if direction =up drawtile(movexmoveyboard[movex][movey] - if direction =down drawtile(movexmoveyboard[movex][movey] if direction =left drawtile(movexmoveyboard[movex][movey]- if direction =right drawtile(movexmoveyboard[movex][movey] pygame display update( fpsclock tick(fps def generatenewpuzzle(numslides) from starting configurationmake numslides number of moves (and animate these moves sequence [ board getstartingboard( drawboard(board'' pygame display update( pygame time wait( pause milliseconds for effect lastmove none for in range(numslides) move getrandommove(boardlastmove slideanimation(boardmove'generating new puzzle 'int(tilesize )email questions to the authoral@inventwithpython com |
10,609 | makemove(boardmove sequence append(move lastmove move return (boardsequence def resetanimation(boardallmoves) make all of the moves in allmoves in reverse revallmoves allmoves[:gets copy of the list revallmoves reverse( for move in revallmoves if move =up oppositemove down elif move =down oppositemove up elif move =right oppositemove left elif move =left oppositemove right slideanimation(boardoppositemove''int(tilesize ) makemove(boardoppositemove if __name__ ='__main__' main(second versesame as the first much of the code in wormy is similar to the previous games we've looked atespecially the constants being set at the start of the code slide puzzle by al sweigart al@inventwithpython com creative commons by-nc-sa us import pygamesysrandom from pygame locals import create the constants (go ahead and experiment with different values boardwidth number of columns in the board boardheight number of rows in the board tilesize windowwidth |
10,610 | windowheight fps blank none black white ( brightblue darkturquoise green bgcolor darkturquoise tilecolor green textcolor white bordercolor brightblue basicfontsize buttoncolor white buttontextcolor black messagecolor white xmargin int((windowwidth (tilesize boardwidth (boardwidth )) ymargin int((windowheight (tilesize boardheight (boardheight )) up 'up down 'down left 'left right 'rightthis code at the top of the program just handles all the basic importing of modules and creating constants this is just like the beginning of the memory puzzle game from the last setting up the buttons def main() global fpsclockdisplaysurfbasicfontreset_surfreset_rectnew_surfnew_rectsolve_surfsolve_rect pygame init( fpsclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) pygame display set_caption('slide puzzle' basicfont pygame font font('freesansbold ttf'basicfontsize email questions to the authoral@inventwithpython com |
10,611 | store the option buttons and their rectangles in options reset_surfreset_rect maketext('reset'textcolortilecolorwindowwidth windowheight new_surfnew_rect maketext('new game'textcolortilecolorwindowwidth windowheight solve_surfsolve_rect maketext('solve'textcolortilecolorwindowwidth windowheight mainboardsolutionseq generatenewpuzzle( solvedboard getstartingboard( solved board is the same as the board in start state just like in the last the functions called from the main(function calls will be explained later in the for nowyou just need to know what they do and what values they return you don' need to know how they work the first part of the main(function will handle creating the windowclock objectand font object the maketext(function is defined later in the programbut for now you just need to know that it returns pygame surface object and pygame rect object which can be used to make clickable buttons the slide puzzle game will have three buttonsa --reset|button that will undo any moves the player has madea --new|button that will create new slide puzzleand --solve|button that will solve the puzzle for the player we will need to have two board data structures for this program one board will represent the current game state the other board will have its tiles in the --solved|statemeaning that all the tiles are lined up in order when the current game state' board is exactly the same as the solved boardthen we know the player has won (we won' ever change this second one it'll just be there to compare the current game state board to the generatenewpuzzle(will create board data structure that started off in the orderedsolved state and then had random slide moves performed on it (because we passed the integer to it if we want the board to be even more jumbledthen we can pass larger integer to itthis will make the board into randomly jumbled state that the player will have to solve (which will be stored in variable named mainboardthe generatenewboard(also returns list of all the random moves that were performed on it (which will be stored in variable named solutionseqbeing smart by using stupid code allmoves [list of moves made from the solved configuration |
10,612 | solving slide puzzle can be really tricky we could program the computer to do itbut that would require us to figure out an algorithm that can solve the slide puzzle that would be very difficult and involve lot of cleverness and effort to put into this program fortunatelythere' an easier way we could just have the computer memorize all the random slides it made when it created the board data structureand then the board can be solved just by performing the opposite slide since the board originally started in the solved stateundoing all the slides would return it to the solved state for examplebelow we perform --right|slide on the board on the left side of the pagewhich leaves the board in the state that is on the right side of the pageafter the right slideif we do the opposite slide ( left slidethen the board will be back in the original state so to get back to the original state after several slideswe just have to do the opposite slides in reverse order if we did right slidethen another right slidethen down slidewe would have to do an up slideleft slideand left slide to undo those first three slides this is much easier than writing function that can solve these puzzles simply by looking at the current state of them the main game loop while truemain game loop slideto none the directionif anya tile should slide msg 'contains the message to show in the upper left corner if mainboard =solvedboardmsg 'solved!drawboard(mainboardmsgin the main game loopthe slideto variable will track which direction the player wants to slide tile (it starts off at the beginning of the game loop as none and is set laterand the msg variable tracks what string to display at the top of the window the program does quick check on line to see if the board data structure has the same value as the solved board data structure stored in solvedboard if sothen the msg variable is changed to the string 'solved!email questions to the authoral@inventwithpython com |
10,613 | this won' appear on the screen until drawboard(has been called to draw it to the displaysurf surface object (which is done on line and pygame display update(is called to draw the display surface object on the actual computer screen (which is done on line at the end of the game loopclicking on the buttons checkforquit( for event in pygame event get()event handling loop if event type =mousebuttonup spotxspoty getspotclicked(mainboardevent pos[ ]event pos[ ] if (spotxspoty=(nonenone) check if the user clicked on an option button if reset_rect collidepoint(event pos) resetanimation(mainboardallmovesclicked on reset button allmoves [ elif new_rect collidepoint(event pos) mainboardsolutionseq generatenewpuzzle( clicked on new game button allmoves [ elif solve_rect collidepoint(event pos) resetanimation(mainboardsolutionseq allmovesclicked on solve button allmoves [before going into the event loopthe program calls checkforquit(on line to see if any quit events have been created (and terminates the program if there havewhy we have separate function (the checkforquit(functionfor handling the quit events will be explained later the for loop on line executes the event handling code for any other event created since the last time pygame event get(was called (or since the program startedif pygame event get(has never been called beforeif the type of event was mousebuttonup event (that isthe player had released mouse button somewhere over the window)then we pass the mouse coordinates to our getspotclicked(function which will return the board coordinates of the spot on the board the mouse release happened the event pos[ is the coordinate and event pos[ is the coordinate if the mouse button release did not happen over one of the spaces on the board (but obviously still happened somewhere on the windowsince mousebuttonup event was created)then getspotclicked(will return none if this is the casewe want to do an additional check to |
10,614 | see if the player might have clicked on the resetnewor solve buttons (which are not located on the boardthe coordinates of where these buttons are on the window are stored in the pygame rect objects that are stored in the reset_rectnew_rectand solve_rect variables we can pass the mouse coordinates from the event object to the collidepoint(method this method will return true if the mouse coordinates are within the rect object' area and false otherwise sliding tiles with the mouse elsecheck if the clicked tile was next to the blank spot blankxblanky getblankposition(mainboardif spotx =blankx and spoty =blankyslideto left elif spotx =blankx and spoty =blankyslideto right elif spotx =blankx and spoty =blanky slideto up elif spotx =blankx and spoty =blanky slideto down if getspotclicked(did not return (nonenone)then it will have returned tuple of two integer values that represent the and coordinate of the spot on the board that was clicked then the if and elif statements on lines to check if the spot that was clicked is tile that is next to the blank spot (otherwise the tile will have no place to slideour getblankposition(function will take the board data structure and return the and board coordinates of the blank spotwhich we store in the variables blankx and blanky if the spot the user clicked on was next to the blank spacewe set the slideto variable with the value that the tile should slide sliding tiles with the keyboard elif event type =keyup check if the user pressed key to slide tile if event key in (k_leftk_aand isvalidmove(mainboardleft) slideto left elif event key in (k_rightk_dand isvalidmove(mainboardright) slideto right email questions to the authoral@inventwithpython com |
10,615 | up) down) elif event key in (k_upk_wand isvalidmove(mainboardslideto up elif event key in (k_downk_sand isvalidmove(mainboardslideto down we can also let the user slide tiles by pressing keyboard keys the if and elif statements on lines to let the user set the slideto variable by either pressing the arrow keys or the wasd keys (explained latereach if and elif statement also has call to isvalidmove(to make sure that the tile can slide in that direction (we didn' have to make this call with the mouse clicks because the checks for the neighboring blank space did the same thing "equal to one oftrick with the in operator the expression event key in (k_leftk_ais just python trick to make the code simpler it is way of saying --evaluate to true if event key is equal to one of k_left or k_a|the following two expressions will evaluate the exact same wayevent key in (k_leftk_aevent key =k_left or event key =k_a you can really save on some space by using this trick when you have to check if value is equal to one of multiple values the following two expressions will evaluate the exact same wayspam ='dogor spam ='cator spam ='mouseor spam ='horseor spam = or spam ='dingospam in ('dog''cat''mouse''horse' 'dingo'wasd and arrow keys the wasand keys (together called the wasd keyspronounced --waz-dee||are commonly used in computer games to do the same thing as the arrow keysexcept the player can use their left hand instead (since the wasd keys are on the left side of the keyboardw is for upa is for lefts is for downand is for right you can easily remember this because the wasd keys have the same layout as the arrow keys |
10,616 | actually performing the tile slide if slideto slideanimation(mainboardslideto'click tile or press arrow keys to slide ' show slide on screen makemove(mainboardslideto allmoves append(slidetorecord the slide pygame display update( fpsclock tick(fpsnow that the events have all been handledwe should update the variables of the game state and display the new state on the screen if slideto has been set (either by the mouse event or keyboard event handling codethen we can call slideanimation(to perform the sliding animation the parameters are the board data structurethe direction of the slidea message to display while sliding the tileand the speed of the sliding after it returnswe need to update the actual board data structure (which is done by the makemove(functionand then add the slide to the allmoves list of all the slides made so far this is done so that if the player clicks on the --reset|buttonwe know how to undo all the player' slides idle and terminating pygame programs def terminate() pygame quit( sys exit(this is function that we can call that calls both the pygame quit(and sys exit(functions this is bit of syntactic sugarso that instead of remembering to make both of these callsthere is just single function we can call instead checking for specific eventand posting events to pygame' event queue def checkforquit() for event in pygame event get(quit)get all the quit events terminate(terminate if any quit events are present email questions to the authoral@inventwithpython com |
10,617 | for event in pygame event get(keyup)get all the keyup events if event key =k_escapeterminate(terminate if the keyup event was for the esc key pygame event post(eventput the other keyup event objects back the checkforquit(function will check for quit events (or if the user has pressed the esc keyand then call the terminate(function but this is bit tricky and requires some explanation pygame internally has its own list data structure that it creates and appends event objects to as they are made this data structure is called the event queue when the pygame event get(function is called with no parametersthe entire list is returned howeveryou can pass constant like quit to pygame event get(so that it will only return the quit events (if anythat are in the internal event queue the rest of the events will stay in the event queue for the next time pygame event get(is called you should note that pygame' event queue only stores up to event objects if your program does not call pygame event get(frequently enough and the queue fills upthen any new events that happen won' be added to the event queue line pulls out list of quit events from pygame' event queue and returns them if there are any quit events in the event queuethe program terminates line pulls out all the keyup events from the event queue and checks if any of them are for the esc key if one of the events isthen the program terminates howeverthere could be keyup events for keys other than the esc key in this casewe need to put the keyup event back into pygame' event queue we can do this with the pygame event post(functionwhich adds the event object passed to it to the end of the pygame event queue this waywhen line calls pygame event get(the non-esc key keyup events will still be there otherwise calls to checkforquit(would --consume|all of the keyup events and those events would never be handled the pygame event post(function is also handy if you ever want your program to add event objects to the pygame event queue creating the board data structure def getstartingboard() return board data structure with tiles in the solved state for exampleif boardwidth and boardheight are both this function returns [[ ][ ][ none] counter |
10,618 | board [for in range(boardwidth)column [for in range(boardheight)column append(countercounter +boardwidth board append(columncounter -boardwidth (boardheight boardwidth board[boardwidth- ][boardheight- none return board the getstartingboard(data structure will create and return data structure that represents --solved|boardwhere all the numbered tiles are in order and the blank tile is in the lower right corner this is done with nested for loopsjust like the board data structure in the memory puzzle game was made howevernotice that the first column isn' going to be [ but instead [ this is because the numbers on the tiles increase by going across the rownot down the column going down the columnthe numbers increase by the size of the board' width (which is stored in the boardwidth constantwe will use the counter variable to keep track of the number that should go on the next tile when the numbering of the tiles in the column is finishedthen we need to set counter to the number at the start of the next column not tracking the blank position def getblankposition(board) return the and of board coordinates of the blank space for in range(boardwidth)) for in range(boardheight) if board[ ][ =none return (xywhenever our code needs to find the xy coordinates of the blank spaceinstead of keeping track of where the blank space is after each slidewe can just create function that goes through the entire board and finds the blank space coordinates the none value is used in the board data structure to represent the blank space the code in getblankposition(simply uses nested for loops to find which space on the board is the blank space making move by updating the board data structure def makemove(boardmove) this function does not check if the move is valid email questions to the authoral@inventwithpython com |
10,619 | blankxblanky getblankposition(board if move =up board[blankx][blanky]board[blankx][blanky board[blankx][blanky ]board[blankx][blanky elif move =down board[blankx][blanky]board[blankx][blanky board[blankx][blanky ]board[blankx][blanky elif move =left board[blankx][blanky]board[blankx ][blankyboard[blankx ][blanky]board[blankx][blanky elif move =right board[blankx][blanky]board[blankx ][blankyboard[blankx ][blanky]board[blankx][blankythe data structure in the board parameter is list that represents where all the tiles are whenever the player makes movethe program needs to update this data structure what happens is that the value for the tile is swapped with the value for the blank space the makemove(function doesn' have to return any valuesbecause the board parameter has list reference passed for its argument this means that any changes we make to board in this function will be made to the list value that was passed to makemove((you can review the concept of references at when not to use an assertion def isvalidmove(boardmove) blankxblanky getblankposition(board return (move =up and blanky !len(board[ ] or (move =down and blanky ! or (move =left and blankx !len(board or (move =right and blankx ! the isvalidmove(function is passed board data structure and move the player would want to make the return value is true if this move is possible and false if it is not for exampleyou cannot slide tile to the left one hundred times in rowbecause eventually the blank space will be at the edge and there are no more tiles to slide to the left whether move is valid or not depends on where the blank space is this function makes call to getblankposition(to find the and coordinates of the blank spot lines to are return statement with single expression the slashes at the end of the first three lines tells the python interpreter that that is not the end of the line of code (even though it is at the end |
10,620 | of the linethis will let us split up --line of code|across multiple lines to look prettyrather than just have one very long unreadable line because the parts of this expression in parentheses are joined by or operatorsonly one of them needs to be true for the entire expression to be true each of these parts checks what the intended move is and then sees if the coordinate of the blank space allows that move getting not-so-random move def getrandommove(boardlastmove=none) start with full list of all four moves validmoves [updownleftright remove moves from the list as they are disqualified if lastmove =up or not isvalidmove(boarddown) validmoves remove(down if lastmove =down or not isvalidmove(boardup) validmoves remove(up if lastmove =left or not isvalidmove(boardright) validmoves remove(right if lastmove =right or not isvalidmove(boardleft) validmoves remove(left return random move from the list of remaining moves return random choice(validmovesat the beginning of the gamewe start with the board data structure in the solvedordered state and create the puzzle by randomly sliding around tiles to decide which of the four directions we should slidewe'll call our getrandommove(function normally we could just use the random choice(function and pass it tuple (updownleftrightto have python simply randomly choose direction value for us but the sliding puzzle game has small restriction that prevents us from choosing purely random number if you had slide puzzle and slid tile to leftand then slid tile to the rightyou would end up with the exact same board you had at the start it' pointless to make slide followed by the opposite slide alsoif the blank space is in the lower right corner than it is impossible to slide tile up or to the left the code in getrandommove(will take these factors into account to prevent the function from selecting the last move that was madethe caller of the function can pass directional value for the lastmove parameter line starts with list of all four directional values stored in the validmoves variable the lastmove value (if not set to noneis removed from email questions to the authoral@inventwithpython com |
10,621 | validmoves depending on if the blank space is at the edge of the boardlines to will remove other directional values from the lastmove list of the values that are left in lastmoveone of them is randomly selected with call to random choice(and returned converting tile coordinates to pixel coordinates def getlefttopoftile(tilextiley) left xmargin (tilex tilesize(tilex top ymargin (tiley tilesize(tiley return (lefttopthe getlefttopoftile(function converts board coordinates to pixel coordinates for the board xy coordinates that are passed inthe function calculates and returns the pixel xy coordinates of the pixel at the top left of that board space converting from pixel coordinates to board coordinates def getspotclicked(boardxy) from the pixel coordinatesget the board coordinates for tilex in range(len(board)) for tiley in range(len(board[ ])) lefttop getlefttopoftile(tilextiley tilerect pygame rect(lefttoptilesizetilesize if tilerect collidepoint(xy) return (tilextiley return (nonenonethe getspotclicked(function does the opposite of getlefttopoftile(and converts from pixel coordinates to board coordinates the nested loops on lines and go through every possible xy board coordinateand if the pixel coordinates that were passed in are within that space on the boardit returns those board coordinates since all of the tiles have width and height that is set in the tilesize constantwe can create rect object that represents the space on the board by getting the pixel coordinates of the top left corner of the board spaceand then use the collidepoint(rect method to see if the pixel coordinates are inside that rect object' area if the pixel coordinates that were passed in were not over any board spacethen the value (nonenoneis returned drawing tile def drawtile(tilextileynumberadjx= adjy= ) |
10,622 | draw tile at board coordinates tilex and tileyoptionally few pixels over (determined by adjx and adjy lefttop getlefttopoftile(tilextiley pygame draw rect(displaysurftilecolor(left adjxtop adjytilesizetilesize) textsurf basicfont render(str(number)truetextcolor textrect textsurf get_rect( textrect center left int(tilesize adjxtop int(tilesize adjy displaysurf blit(textsurftextrectthe drawtile(function will draw single numbered tile on the board the tilex and tiley parameters are the board coordinates of the tile the number parameter is string of the tile' number (like ' or ' 'the adjx and adjy keyword parameters are for making minor adjustments to the position of the tile for examplepassing for adjx would make the tile appear pixels to the right of the tilex and tiley space on the board passing - for adjx would make the tile appear pixels to the left of the space these adjustment values will be handy when we need to draw the tile in the middle of sliding if no values are passed for these arguments when drawtile(is calledthen by default they are set to this means they will be exactly on the board space given by tilex and tiley the pygame drawing functions only use pixel coordinatesso first line converts the board coordinates in tilex and tiley to pixel coordinateswhich we will store in variables left and top (since getlefttopoftile(returns the top left corner' coordinateswe draw the background square of the tile with call to pygame draw rect(while adding the adjx and adjy values to left and top in case the code needs to adjust the position of the tile lines to then create the surface object that has the number text drawn on it rect object for the surface object is positionedand then used to blit the surface object to the display surface the drawtile(function doesn' call pygame display update(functionsince the caller of drawtile(probably will want to draw more tiles for the rest of the board before making them appear on the screen the making text appear on the screen def maketext(textcolorbgcolortopleft) create the surface and rect objects for some text textsurf basicfont render(texttruecolorbgcolor textrect textsurf get_rect( textrect topleft (topleft return (textsurftextrectemail questions to the authoral@inventwithpython com |
10,623 | the maketext(function handles creating the surface and rect objects for positioning text on the screen instead of doing all these calls each time we want to make text on the screenwe can just call maketext(instead this saves us on the amount of typing we have to do for our program (though drawtile(makes the calls to render(and get_rect(itself because it positions the text surface object by the center point rather than the topleft point and uses transparent background color drawing the board def drawboard(boardmessage) displaysurf fill(bgcolor if message textsurftextrect maketext(messagemessagecolorbgcolor displaysurf blit(textsurftextrect for tilex in range(len(board)) for tiley in range(len(board[ ])) if board[tilex][tiley] drawtile(tilextileyboard[tilex][tiley]this function handles drawing the entire board and all of its tiles to the displaysurf display surface object the fill(method on line completely paints over anything that used to be drawn on the display surface object before so that we start from scratch line to handles drawing the message at the top of the window we use this for the --generating new puzzle |and other text we want to display at the top of the window remember that if statement conditions consider the blank string to be false valueso if message is set to 'then the condition is false and lines and are skipped nextnested for loops are used to draw each tile to the display surface object by calling the drawtile(function drawing the border of the board lefttop getlefttopoftile( width boardwidth tilesize height boardheight tilesize pygame draw rect(displaysurfbordercolor(left top width height ) lines to draw border around the tiles the top left corner of the boarder will be pixels to the left and pixels above the top left corner of the tile at board coordinates ( the width and height of the border are calculated from the number of tiles wide and high the board is (stored |
10,624 | in the boardwidth and boardheight constantsmultiplied by the size of the tiles (stored in the tilesize constantthe rectangle we draw on line will have thickness of pixelsso we will move the boarder pixels to the left and above where the top and left variables point so the thickness of the line won' overlap the tiles we will also add to the width and length ( of those pixels are to compensate for moving the rectangle to the left and updrawing the buttons displaysurf blit(reset_surfreset_rectdisplaysurf blit(new_surfnew_rectdisplaysurf blit(solve_surfsolve_rectfinallywe draw the buttons off to the slide of the screen the text and position of these buttons never changeswhich is why they were stored in constant variables at the beginning of the main(function animating the tile slides def slideanimation(boarddirectionmessageanimationspeed) notethis function does not check if the move is valid blankxblanky getblankposition(board if direction =up movex blankx movey blanky elif direction =down movex blankx movey blanky elif direction =left movex blankx movey blanky elif direction =right movex blankx movey blanky the first thing our tile sliding animation code needs to calculate is where the blank space is and where the moving tile is the comment on line reminds us that the code that calls slideanimation(should make sure that the slide it passes for the direction parameter is valid move to make email questions to the authoral@inventwithpython com |
10,625 | the blank space' coordinates come from call to getblankposition(from these coordinates and the direction of the slidewe can figure out the xy board coordinates of the tile that will slide these coordinates will be stored in the movex and movey variables the copy(surface method prepare the base surface drawboard(boardmessage basesurf displaysurf copy( draw blank space over the moving tile on the basesurf surface moveleftmovetop getlefttopoftile(movexmovey pygame draw rect(basesurfbgcolor(moveleftmovetoptilesizetilesize)the copy(method of surface objects will return new surface object that has the same image drawn to it but they are two separate surface objects after calling the copy(methodif we draw on one surface object using blit(or the pygame drawing functionsit will not change the image on the other surface object we store this copy in the basesurf variable on line nextwe paint another blank space over the tile that will slide this is because when we draw each frame of the sliding animationwe will draw the sliding tile over different parts of the basesurf surface object if we didn' blank out the moving tile on the basesurf surfacethen it would still be there as we draw the sliding tile in that casehere is what the basesurf surface would look likeand then what it would look like when we draw the -- |tile sliding upwards on top of it |
10,626 | you can see this for yourself by commenting out line and running the program for in range( tilesizeanimationspeed)animate the tile sliding over checkforquit(displaysurf blit(basesurf( )if direction =updrawtile(movexmoveyboard[movex][movey] -iif direction =downdrawtile(movexmoveyboard[movex][movey] iif direction =leftdrawtile(movexmoveyboard[movex][movey]- if direction =rightdrawtile(movexmoveyboard[movex][movey] pygame display update(fpsclock tick(fpsin order to draw the frames of the sliding animationwe must draw the basesurf surface on the display surfacethen on each frame of the animation draw the sliding tile closer and closer to its final position where the original blank space was the space between two adjacent tiles is the same size as single tilewhich we have stored in tilesize the code uses for loop to go from to tilesize normally this would mean that we would draw the tile pixels overthen on the next frame draw the tile pixel overthen pixelsthen and so on each of these frames would take / th of second if you have tilesize set to (as the program in this book does on line then sliding tile would take over two and half secondswhich is actually kind of slow email questions to the authoral@inventwithpython com |
10,627 | so instead we will have the for loop iterate from to tilesize by several pixels each frame the number of pixels it jumps over is stored in animationspeedwhich is passed in when slideanimation(is called for exampleif animationspeed was set to and the constant tilesize was set to then the for loop and range( tilesizeanimationspeedwould set the variable to the values (it does not include because the range(function goes up tobut not includingthe second argument this means the entire sliding animation would be done in frameswhich would mean it is done in / th of second ( third of secondsince the game runs at fps lines to makes sure that we draw the tile sliding in the correct direction (based on what value the direction variable hasafter the animation is donethen the function returns notice that while the animation is happeningany events being created by the user are not being handled those events will be handled the next time execution reaches line in the main(function or the code in the checkforquit(function creating new puzzle def generatenewpuzzle(numslides) from starting configurationmake numslides number of moves (and animate these moves sequence [ board getstartingboard( drawboard(board'' pygame display update( pygame time wait( pause milliseconds for effect the generatenewpuzzle(function will be called at the start of each new game it will create new board data structure by calling getstartingboard(and then randomly scramble it the first few lines of generatenewpuzzle(get the board and then draw it to the screen (freezing for half second to let the player see the fresh board for moment lastmove none for in range(numslides) move getrandommove(boardlastmove slideanimation(boardmove'generating new puzzle 'int(tilesize ) makemove(boardmove sequence append(move lastmove move return (boardsequencethe numslides parameter will show tell the function how many of these random moves to make the code for doing random move is the getrandommove(call on line to get the |
10,628 | move itselfthen call slideanimation(to perform the animation on the screen because doing the slide animation does not actually update the board data structurewe update the board by calling makemove(on line we need to keep track of each of the random moves that was made so that the player can click the --solve|button later and have the program undo all these random moves (the --being smart by using stupid code|section talks about why and how we do this so the move is appended to the list of moves in sequence on line then we store the random move in variable called lastmove which will be passed to getrandommove(on the next iteration this prevents the next random move from undoing the random move we just performed all of this needs to happen numslides number of timesso we put lines to inside for loop when the board is done being scrambledthen we return the board data structure and also the list of the random moves made on it animating the board reset def resetanimation(boardallmoves) make all of the moves in allmoves in reverse revallmoves allmoves[:gets copy of the list revallmoves reverse( for move in revallmoves if move =up oppositemove down elif move =down oppositemove up elif move =right oppositemove left elif move =left oppositemove right slideanimation(boardoppositemove''int(tilesize ) makemove(boardoppositemovewhen the player clicks on --reset|or --solve||the slide puzzle game program needs to undo all of the moves that were made to the board the list of directional values for the slides will be passed as the argument for the allmoves parameter line uses list slicing to create duplicate of the allmoves list remember that if you don' specify number before the :then python assumes the slice should start from the very beginning of the list and if you don' specify number after the :then python assumes the slice should keep going to the very end of the list so allmoves[:creates list slice of the entire email questions to the authoral@inventwithpython com |
10,629 | allmoves list this makes copy of the actual list to store in revallmovesrather than just copy of the list reference (see to undo all the moves in allmoveswe need to perform the opposite move of the moves in allmovesand in reverse order there is list method called reverse(which will reverse the order of the items in list we call this on the revallmoves list on line the for loop on line iterates over the list of directional values rememberwe want the opposite moveso the if and elif statements from line to set the correct directional value in the oppositemove variable then we call slideanimation(to perform the animationand makemove(to update the board data structure if __name__ ='__main__' main(just like in the memory puzzle gameafter all the def statements have been executed to create all the functionswe call the main(function to begin the meat of the program that' all there is to the slide puzzle programbut let' talk about some general programming concepts that came up in this game time vs memory tradeoffs of coursethere are few different ways to write the slide puzzle game so that it looks and acts the exact same way even though the code is different there are many different ways the program that does task could be written the most common differences are making tradeoffs between execution time and memory usage usuallythe faster program can runthe better it is this is especially true with programs that need to do lot of calculationswhether they are scientific weather simulators or games with large amount of detailed graphics to draw it' also good to use the least amount of memory possible the more variables and the larger the lists your program usesthe more memory it takes up (you can find out how to measure your program' memory usage and execution time at right nowthe programs in this book aren' big and complicated enough where you have to worry about conserving memory or optimizing the execution time but it can be something to consider as you become more skilled programmer for exampleconsider the getblankposition(function this function takes time to runsince it goes through all the possible board coordinates to find where the blank space is insteadwe could just have blankspacex and blankspacey variable which would have these xy |
10,630 | coordinates so we would not have to look through the entire board each time we want to know where it was (we would also need code that updates the blankspacex and blankspacey variables whenever move is done this code could go in makemove(using these variables would take up more memorybut they would save you on execution time so your program would run faster another example is that we keep board data structure in the solved state in the solvedboard variableso that we can compare the current board to solvedboard to see if the player has solved the puzzle each time we wanted to do this checkwe could just call the getstartingboard(function and compare the returned value to the current board then we would not need the solvedboard variable this would save us little bit of memorybut then our program would take longer to run because it is re-creating the solved-state board data structure each time we do this check there is one thing you must remember though writing code that is readable is very important skill code that is --readable|is code that is easy to understandespecially by programmers who did not write the code if another programmer can look at your program' source code and figure out what it does without much troublethen that program is very readable readability is important because when you want to fix bugs or add new features to your program (and bugs and ideas for new features always come up)then having readable program makes those tasks much easier nobody cares about few bytes alsothere is one thing that might seem kind of silly to say in this book because it seem obviousbut many people wonder about it you should know that using short variable names like or num instead of longermore descriptive variable names like blankx or numslides does not save you any memory when your program actually runs using these longer variable names is better because they'll make your program more readable you might also come up with some clever tricks that do save few bytes of memory here and there one trick is that when you no longer need variableyou can reuse that variable name for different purpose instead of just using two differently named variables try to avoid the temptation to do this usuallythese tricks reduce code readability and make it harder to debug your programs modern computers have billions of bytes of memoryand saving few bytes here and there really isn' worth making the code more confusing for human programmers email questions to the authoral@inventwithpython com |
10,631 | nobody cares about few million nanoseconds similarlythere are times when you can rearrange your code in some way to make it slightly faster by few nanoseconds these tricks also usually make the code harder to read when you consider that several billion nanoseconds have passed in the time it takes you to read this sentencesaving few nanoseconds of execution time in your program won' be noticed by the player summary this hasn' introduced any new pygame programming concepts that the memory puzzle game didn' useaside from using the copy(method of surface objects just knowing few different concepts will let you create completely different games for practiceyou can download buggy versions of the sliding puzzle program from |
10,632 | simulate how to play simulate simulate is clone of the game simon there are four colored buttons on the screen the buttons light up in certain random patternand then the player must repeat this pattern by pressing the buttons in the correct order each time the player successfully simulates the patternthe pattern gets longer the player tries to match the pattern for as long as possible source code to simulate 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 can download the four sound files that this program uses from simulate ( simon clone by al sweigart al@inventwithpython com email questions to the authoral@inventwithpython com |
10,633 | creative commons by-nc-sa us import randomsystimepygame from pygame locals import fps windowwidth windowheight flashspeed in milliseconds flashdelay in milliseconds buttonsize buttongapsize timeout seconds before game over if no button is pushed white ( black brightred ( red ( brightgreen green brightblue blue brightyellow ( yellow ( darkgray bgcolor black xmargin int((windowwidth ( buttonsizebuttongapsize ymargin int((windowheight ( buttonsizebuttongapsize rect objects for each of the four buttons yellowrect pygame rect(xmarginymarginbuttonsizebuttonsize bluerect pygame rect(xmargin buttonsize buttongapsizeymarginbuttonsizebuttonsize redrect pygame rect(xmarginymargin buttonsize buttongapsizebuttonsizebuttonsize greenrect pygame rect(xmargin buttonsize buttongapsizeymargin buttonsize buttongapsizebuttonsizebuttonsize def main() global fpsclockdisplaysurfbasicfontbeep beep beep beep pygame init( fpsclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) |
10,634 | pygame display set_caption('simulate' basicfont pygame font font('freesansbold ttf' infosurf basicfont render('match the pattern by clicking on the button or using the qwas keys ' darkgray inforect infosurf get_rect( inforect topleft ( windowheight load the sound files beep pygame mixer sound('beep ogg' beep pygame mixer sound('beep ogg' beep pygame mixer sound('beep ogg' beep pygame mixer sound('beep ogg' initialize some variables for new game pattern [stores the pattern of colors currentstep the color the player must push next lastclicktime timestamp of the player' last button push score when falsethe pattern is playing when truewaiting for the player to click colored button waitingforinput false while truemain game loop clickedbutton none button that was clicked (set to yellowredgreenor blue displaysurf fill(bgcolor drawbuttons( scoresurf basicfont render('scorestr(score) white scorerect scoresurf get_rect( scorerect topleft (windowwidth displaysurf blit(scoresurfscorerect displaysurf blit(infosurfinforect checkforquit( for event in pygame event get()event handling loop if event type =mousebuttonup mousexmousey event pos clickedbutton getbuttonclicked(mousexmousey elif event type =keydown if event key =k_q clickedbutton yellow elif event key =k_w clickedbutton blue email questions to the authoral@inventwithpython com |
10,635 | elif event key =k_a clickedbutton red elif event key =k_s clickedbutton green if not waitingforinput play the pattern pygame display update( pygame time wait( pattern append(random choice((yellowblueredgreen)) for button in pattern flashbuttonanimation(button pygame time wait(flashdelay waitingforinput true else wait for the player to enter buttons if clickedbutton and clickedbutton =pattern[currentstep] pushed the correct button flashbuttonanimation(clickedbutton currentstep + lastclicktime time time( if currentstep =len(pattern) pushed the last button in the pattern changebackgroundanimation( score + waitingforinput false currentstep reset back to first step elif (clickedbutton and clickedbutton !pattern[currentstep]or (currentstep ! and time time(timeout lastclicktime) pushed the incorrect buttonor has timed out gameoveranimation( reset the variables for new game pattern [ currentstep waitingforinput false score pygame time wait( changebackgroundanimation( pygame display update( fpsclock tick(fps |
10,636 | def terminate() pygame quit( sys exit( 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 def flashbuttonanimation(coloranimationspeed= ) if color =yellow sound beep flashcolor brightyellow rectangle yellowrect elif color =blue sound beep flashcolor brightblue rectangle bluerect elif color =red sound beep flashcolor brightred rectangle redrect elif color =green sound beep flashcolor brightgreen rectangle greenrect origsurf displaysurf copy( flashsurf pygame surface((buttonsizebuttonsize) flashsurf flashsurf convert_alpha( rgb flashcolor sound play( for startendstep in (( )( - ))animation loop for alpha in range(startendanimationspeed step) checkforquit( displaysurf blit(origsurf( ) flashsurf fill((rgbalpha) displaysurf blit(flashsurfrectangle topleft pygame display update( fpsclock tick(fpsemail questions to the authoral@inventwithpython com |
10,637 | displaysurf blit(origsurf( ) def drawbuttons() pygame draw rect(displaysurfyellowyellowrect pygame draw rect(displaysurfbluebluerect pygame draw rect(displaysurfredredrect pygame draw rect(displaysurfgreengreenrect def changebackgroundanimation(animationspeed= ) global bgcolor newbgcolor (random randint( )random randint( )random randint( ) newbgsurf pygame surface((windowwidthwindowheight) newbgsurf newbgsurf convert_alpha( rgb newbgcolor for alpha in range( animationspeed)animation loop checkforquit( displaysurf fill(bgcolor newbgsurf fill((rgbalpha) displaysurf blit(newbgsurf( ) drawbuttons(redraw the buttons on top of the tint pygame display update( fpsclock tick(fps bgcolor newbgcolor def gameoveranimation(color=whiteanimationspeed= ) play all beeps at oncethen flash the background origsurf displaysurf copy( flashsurf pygame surface(displaysurf get_size() flashsurf flashsurf convert_alpha( beep play(play all four beeps at the same timeroughly beep play( beep play( beep play( rgb color for in range( )do the flash times for startendstep in (( )( - )) the first iteration in this loop sets the following for loop to go from to the second from to |
10,638 | for alpha in range(startendanimationspeed step)animation loop alpha means transparency is opaque is invisible checkforquit( flashsurf fill((rgbalpha) displaysurf blit(origsurf( ) displaysurf blit(flashsurf( ) drawbuttons( pygame display update( fpsclock tick(fps def getbuttonclicked(xy) if yellowrect collidepoint(xy) return yellow elif bluerect collidepoint(xy) return blue elif redrect collidepoint(xy) return red elif greenrect collidepoint(xy) return green return none if __name__ ='__main__' main(the usual starting stuff simulate ( simon clone by al sweigart al@inventwithpython com creative commons by-nc-sa us import randomsystimepygame from pygame locals import fps windowwidth windowheight flashspeed in milliseconds flashdelay in milliseconds buttonsize buttongapsize timeout seconds before game over if no button is pushed email questions to the authoral@inventwithpython com |
10,639 | white ( black brightred ( red ( brightgreen green brightblue blue brightyellow ( yellow ( darkgray bgcolor black xmargin int((windowwidth ( buttonsizebuttongapsize ymargin int((windowheight ( buttonsizebuttongapsize here we set up the usual constants for things that we might want to modify later such as the size of the four buttonsthe shades of color used for the buttons (the bright colors are used when the buttons light upand the amount of time the player has to push the next button in the sequence before the game times out setting up the buttons rect objects for each of the four buttons yellowrect pygame rect(xmarginymarginbuttonsizebuttonsize bluerect pygame rect(xmargin buttonsize buttongapsizeymarginbuttonsizebuttonsize redrect pygame rect(xmarginymargin buttonsize buttongapsizebuttonsizebuttonsize greenrect pygame rect(xmargin buttonsize buttongapsizeymargin buttonsize buttongapsizebuttonsizebuttonsizejust like the buttons in the sliding puzzle games for --reset||--solve|and --new game||the simulate game has four rectangular areas and code to handle when the player clicks inside of those areas the program will need rect objects for the areas of the four buttons so it can call the collidepoint(method on them lines to set up these rect objects with the appropriate coordinates and sizes the main(function def main() global fpsclockdisplaysurfbasicfontbeep beep beep beep |
10,640 | pygame init( fpsclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) pygame display set_caption('simulate' basicfont pygame font font('freesansbold ttf' infosurf basicfont render('match the pattern by clicking on the button or using the qwas keys ' darkgray inforect infosurf get_rect( inforect topleft ( windowheight load the sound files beep pygame mixer sound('beep ogg' beep pygame mixer sound('beep ogg' beep pygame mixer sound('beep ogg' beep pygame mixer sound('beep ogg'the main(function will implement the bulk of the program and call the other functions as they are needed the usual pygame setup functions are called to initialize the librarycreate clock objectcreate windowset the captionand create font object that will be used to display the score and the instructions on the window the objects that are created by these function calls will be stored in global variables so that they can be used in other functions but they are basically constants since the value in them is never changed lines to will load sound files so that simulate can play sound effects as the player clicks on each button the pygame mixer sound(constructor function will return sound objectwhich we store in the variables beep to beep which were made into global variables on line some local variables used in this program initialize some variables for new game pattern [stores the pattern of colors currentstep the color the player must push next lastclicktime timestamp of the player' last button push score when falsethe pattern is playing when truewaiting for the player to click colored button waitingforinput false the pattern variable will be list of color values (either yellowredblueor greento keep track of the pattern that the player must memorize for exampleif the value of pattern was [redredyellowredblueblueredgreenthen the player would email questions to the authoral@inventwithpython com |
10,641 | have to first click the red button twicethen the yellow buttonthen the red buttonand so on until the final green button as the player finishes each rounda new random color is added to the end of the list the currentstep variable will keep track of which color in the pattern list the player has to click next if currentstep was and pattern was [greenredredyellow]then the player would have to click the green button if they clicked on any other buttonthe code will cause game over there is timeout constant that makes the player click on next button in the pattern within number of secondsotherwise the code causes game over in order to check if enough time has passed since the last button clickthe lastclicktime variable needs to keep track of the last time the player clicked on button (python has module named time and time time(function to return the current time this will be explained later it may be hard to believebut the score variable keeps track of the score inconceivablethere are also two modes that our program will be in either the program is playing the pattern of buttons for the player (in which casewaitingforinput is set to false)or the program has finished playing the pattern and is waiting for the user to click the buttons in the correct order (in which casewaitingforinput is set to truedrawing the board and handling input while truemain game loop clickedbutton none button that was clicked (set to yellowredgreenor blue displaysurf fill(bgcolor drawbuttons( scoresurf basicfont render('scorestr(score) white scorerect scoresurf get_rect( scorerect topleft (windowwidth displaysurf blit(scoresurfscorerect displaysurf blit(infosurfinforectline is the start of the main game loop the clickedbutton will be reset to none at the beginning of each iteration if button is clicked during this iterationthen clickedbutton will be set to one of the color values to match the button (yellowredgreenor blue |
10,642 | the fill(method is called on line to repaint the entire display surface so that we can start drawing from scratch the four colored buttons are drawn with call to the drawbuttons((explained laterthen the text for the score is created on lines to there will also be text that tells the player what their current score is unlike the call to the render(method on line for the instruction textthe text for the score changes it starts off as 'score and then becomes 'score and then 'score and so on this is why we create new surface objects by calling the render(method on line inside the game loop since the instruction text (--match the pattern by ||never changeswe only need one call to render(outside the game loop on line checking for mouse clicks checkforquit(for event in pygame event get()event handling loop if event type =mousebuttonupmousexmousey event pos clickedbutton getbuttonclicked(mousexmouseyline does quick check for any quit eventsand then line is the start of the event handling loop the xy coordinates of any mouse clicks will be stored in the mousex and mousey variables if the mouse click was over one of the four buttonsthen our getbuttonclicked(function will return color object of the button clicked (otherwise it returns nonechecking for keyboard presses elif event type =keydownif event key =k_qclickedbutton yellow elif event key =k_wclickedbutton blue elif event key =k_aclickedbutton red elif event key =k_sclickedbutton green lines to check for any keydown events (created when the user presses key on the keyboardthe qwaand keys correspond to the buttons because they are arranged in square shape on the keyboard the key is in the upper left of the four keyboard keysjust like the yellow button on the screen is in the upper leftso we will make pressing the key the same as clicking on the yellow button email questions to the authoral@inventwithpython com |
10,643 | we can do this by setting the clickedbutton variable to the value in the constant variable yellow we can do the same for the three other keys this waythe user can play simulate with either the mouse or keyboard the two states of the game loop if not waitingforinputplay the pattern pygame display update(pygame time wait( pattern append(random choice((yellowblueredgreen))for button in patternflashbuttonanimation(buttonpygame time wait(flashdelaywaitingforinput true there are two different --modes|or --states|that the program can be in when waitingforinput is falsethe program will be displaying the animation for the pattern when waitingforinput is truethe program will be waiting for the user to select buttons lines to will cover the case where the program displays the pattern animation since this is done at the start of the game or when the player finishes patternline will add random color to the pattern list to make the pattern one step longer then lines to loops through each of the values in the pattern list and calls flashbuttonanimation(which makes that button light up after it is done lighting up all the buttons in the pattern listthe program sets the waitingforinput variable to true figuring out if the player pressed the right buttons elsewait for the player to enter buttons if clickedbutton and clickedbutton =pattern[currentstep]pushed the correct button flashbuttonanimation(clickedbuttoncurrentstep + lastclicktime time time(if waitingforinput is truethen the code in line ' else statement will execute line checks if the player has clicked on button during this iteration of the game loop and if that button was the correct one the currentstep variable keeps track of the index in the pattern list for the button that the player should click on next |
10,644 | for exampleif pattern was set to [yellowredredand the currentstep variable was set to (like it would be when the player first starts the game)then the correct button for the player to click would be pattern[ (the yellow buttonif the player has clicked on the correct buttonwe want to flash the button the player clicked by calling flashbuttonanimation(thenincrease the currentstep to the next stepand then update the lastclicktime variable to the current time (the time time(function returns float value of the number of seconds since january st so we can use it to keep track of time if currentstep =len(pattern)pushed the last button in the pattern changebackgroundanimation(score + waitingforinput false currentstep reset back to first step lines to are inside the else statement that started on line if the execution is inside that else statementwe know the player clicked on button and also it was the correct button line checks if this was the last correct button in the pattern list by checking if the integer stored in currentstep is equal to the number of values inside the pattern list if this is truethen we want to change the background color by calling our changebackgroundanimation(this is simple way to let the player know they have entered the entire pattern correctly the score is incrementedcurrentstep is set back to and the waitingforinput variable is set to false so that on the next iteration of the game loop the code will add new color value to the pattern list and then flash the buttons elif (clickedbutton and clickedbutton !pattern[currentstep]or (currentstep ! and time time(timeout lastclicktime)if the player did not click on the correct buttonthe elif statement on line handles the case where either the player clicked on the wrong button or the player has waited too long to click on button either waywe need to show the --game over|animation and start new game the (clickedbutton and clickedbutton !pattern[currentstep]part of the elif statement' condition checks if button was clicked and was the wrong button to click you can compare this to line ' if statement' condition clickedbutton and clickedbutton =pattern[currentstepwhich evaluates to true if the player clicked button and it was the correct button to click email questions to the authoral@inventwithpython com |
10,645 | the other part of line ' elif condition is (currentstep ! and time time(timeout lastclicktimethis handles making sure the player did not --time out|notice that this part of the condition has two expressions connected by an and keyword that means both sides of the and keyword need to evaluate to true in order to --time out||it must not be the player' first button click but once they've started to click buttonsthey must keep clicking the buttons quickly enough until they've entered the entire pattern (or have clicked on the wrong pattern and gotten --game over||if currentstep ! is truethen we know the player has begun clicking the buttons epoch time also in order to --time out||the current time (returned by time time()minus four seconds (because is stored in timeoutmust be greater than the last time clicked button (stored in lastclicktimethe reason why time time(timeout lastclicktime works has to do with how epoch time works epoch time (also called unix epoch timeis the number of seconds it has been since january st this date is called the unix epoch for examplewhen run time time(from the interactive shell (don' forget to import the time module first)it looks like thisimport time time time( what this number means is that the moment the time time(function was called was little over , , , seconds since midnight of january st (this translates to november th at : : pm you can learn how to convert from unix epoch time to regular english time at if call time time(from the interactive shell few seconds laterit might look like thistime time( seconds after midnight of the unix epoch is november th at : : pm (actuallyit' : and seconds if you want to be precise dealing with time would be difficult if we had to deal with strings it' hard to tell that seconds have passed if we only had the string values ' : : pmand ' : : pmto compare but with epoch timeit' just matter of subtracting the integers which evaluates to this value is the number |
10,646 | of seconds between those two times (the extra comes from very small rounding errors that happen when you do math with floating point numbers they only happen sometimes and are usually too tiny to matter you can learn more about floating point rounding errors at going back to line if time time(timeout lastclicktime evaluates to truethen it has been longer than seconds since time time(was called and stored in lastclicktime if it evaluates to falsethen it has been less than seconds pushed the incorrect buttonor has timed out gameoveranimation(reset the variables for new gamepattern [currentstep waitingforinput false score pygame time wait( changebackgroundanimation(if either the player clicked on the wrong button or has timed outthe program should play the --game over|animation and then reset the variables for new game this involves setting the pattern list to blank listcurrentstep to waitingforinput to falseand then score to small pause and new background color will be set to indicate to the player the start of new gamewhich will begin on the next iteration of the game loop drawing the board to the screen pygame display update(fpsclock tick(fpsjust like the other game programsthe last thing done in the game loop is drawing the display surface object to the screen and calling the tick(method same old terminate(function def terminate() pygame quit( sys exit( 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 email questions to the authoral@inventwithpython com |
10,647 | if event key =k_escapeterminate(terminate if the keyup event was for the esc key pygame event post(eventput the other keyup event objects back the terminate(and checkforquit(functions were used and explained in the sliding puzzle so we will skip describing them again reusing the constant variables def flashbuttonanimation(coloranimationspeed= ) if color =yellow sound beep flashcolor brightyellow rectangle yellowrect elif color =blue sound beep flashcolor brightblue rectangle bluerect elif color =red sound beep flashcolor brightred rectangle redrect elif color =green sound beep flashcolor brightgreen rectangle greenrect depending on which color value is passed as an argument for the color parameterthe soundcolor of the bright flashand rectangular area of the flash will be different line to sets three local variables differently depending on the value in the color parametersoundflashcolorand rectangle animating the button flash origsurf displaysurf copy(flashsurf pygame surface((buttonsizebuttonsize)flashsurf flashsurf convert_alpha(rgb flashcolor sound play(the process of animating the button flash is simpleon each frame of the animationthe normal board is drawn and then on top of thatthe bright color version of the button that is flashing is drawn over the button the alpha value of the bright color starts off at for the first frame of animationbut then on each frame after the alpha value is slowly increased until it is fully opaque |
10,648 | and the bright color version completely paints over the normal button color this will make it look like the button is slowly brightening up the brightening up is the first half of the animation the second half is the button dimming this is done with the same codeexcept that instead of the alpha value increasing for each frameit will be decreasing as the alpha value gets lower and lowerthe bright color painted on top will become more and more invisibleuntil only the original board with the dull colors is visible to do this in codeline creates copy of the display surface object and stores it in origsurf line creates new surface object the size of single button and stores it in flashsurf the convert_alpha(method is called on flashsurf so that the surface object can have transparent colors drawn on it (otherwisethe alpha value in the color objects we use will be ignored and automatically assumed to be in your own game programsif you are having trouble getting color transparency to workmake sure that you have called the convert_alpha(method on any surface objects that have transparent colors painted on them line creates individual local variables named rgand to store the individual rgb values of the tuple stored in flashcolor this is just some syntactic sugar that makes the rest of the code in this function easier to read before we begin animating the button flashline will play the sound effect for that button the program execution keeps going after the sound effect has started to playso the sound will be playing during the button flash animation for startendstep in (( )( - ))animation loop for alpha in range(startendanimationspeed step)checkforquit(displaysurf blit(origsurf( )flashsurf fill((rgbalpha)displaysurf blit(flashsurfrectangle topleftpygame display update(fpsclock tick(fpsdisplaysurf blit(origsurf( )remember that to do the animationwe want to first draw the flashsurf with color that has increasing alpha values from to to do the brightening part of the animation then to do the dimmingwe want the alpha value to go from to we could do that with code like thisfor alpha in range( animationspeed)brightening checkforquit(displaysurf blit(origsurf( )flashsurf fill((rgbalpha)displaysurf blit(flashsurfrectangle topleftemail questions to the authoral@inventwithpython com |
10,649 | pygame display update(fpsclock tick(fpsfor alpha in range( -animationspeed)dimming checkforquit(displaysurf blit(origsurf( )flashsurf fill((rgbalpha)displaysurf blit(flashsurfrectangle topleftpygame display update(fpsclock tick(fpsbut notice that the code inside the for loops handles drawing the frame and are identical to each other if we wrote the code like the abovethen the first for loop would handle the brightening part of the animation (where the alpha value goes from to and the second for loop would handle the dimming part of the animation (where the alpha values goes from to note that for the second for loopthe third argument to the range(call is negative number whenever we have identical code like thiswe can probably shorten our code so we don' have to repeat it this is what we do with the for loop on line which supplies different values for the range(call on line for startendstep in (( )( - ))animation loop for alpha in range(startendanimationspeed step)on the first iteration of line ' for loopstart is set to end is set to and step is set to this waywhen the for loop on line is executedit is calling range( animationspeed(note that animationspeed is the same as animationspeed multiplying number by gives us the same number line ' for loop then executes and performs the brightening animation on the second iteration of line ' for loop (there are always two and only two iterations of this inner for loop)start is set to end is set to and step is set to - when the line ' for loop is executedit is calling range( -animationspeed(note that animationspeed - evaluates to -animationspeedsince multiplying any number by - returns the negative form of that same number this waywe don' have to have two separate for loops and repeat all the code that is inside of them here' the code again that is inside line ' for loop checkforquit(displaysurf blit(origsurf( )flashsurf fill((rgbalpha) |
10,650 | displaysurf blit(flashsurfrectangle topleftpygame display update(fpsclock tick(fpsdisplaysurf blit(origsurf( )we check for any quit events (in case the user tried to close the program during the animation)then blit the origsurf surface to the display surface then we paint the flashsurf surface by calling fill((supplying the rgb values of the color we got on line and the alpha value that the for loop sets in the alpha variablethen the flashsurf surface is blitted to the display surface thento make the display surface appear on the screenpygame display update(is called on line to make sure the animation doesn' play as fast as the computer can draw itwe add short pauses with call to the tick(method (if you want to see the flashing animation play very slowlyput low number like or as the argument to tick(instead of fps drawing the buttons def drawbuttons() pygame draw rect(displaysurfyellowyellowrect pygame draw rect(displaysurfbluebluerect pygame draw rect(displaysurfredredrect pygame draw rect(displaysurfgreengreenrectsince each of the buttons is just rectangle of certain color in certain placewe just make four calls to pygame draw rect(to draw the buttons on the display surface the color object and the rect object we use to position them never changewhich is why we stored them in constant variables like yellow and yellowrect animating the background change def changebackgroundanimation(animationspeed= ) global bgcolor newbgcolor (random randint( )random randint( )random randint( ) newbgsurf pygame surface((windowwidthwindowheight) newbgsurf newbgsurf convert_alpha( rgb newbgcolor for alpha in range( animationspeed)animation loop checkforquit( displaysurf fill(bgcolor newbgsurf fill((rgbalpha)email questions to the authoral@inventwithpython com |
10,651 | displaysurf blit(newbgsurf( )drawbuttons(redraw the buttons on top of the tint pygame display update(fpsclock tick(fpsbgcolor newbgcolor the background color change animation happens whenever the player finishes entering the entire pattern correctly on each iteration through the loop which starts on line the entire display surface has to be redrawn (blended with less and less transparent new background coloruntil the background is completely covered by the new colorthe steps done on each iteration of the loop areline fills in the entire display surface (stored in displaysurfwith the old background color (which is stored in bgcolorline fills in different surface object (stored in newbgsurfwith the new background color' rgb values (and the alpha transparency value changes on each iteration since that is what the for loop on line doesline then draws the newbgsurf surface to the display surface in displaysurf the reason we didn' just paint our semitransparent new background color on displaysurf to begin with is because the fill(method will just replace the color on the surfacewhereas the blit(method will blend the colors now that we have the background the way we want itwe'll draw the buttons over it with call to drawbuttons(on line line and then just draws the display surface to the screen and adds pause the reason there is global statement at the beginning of the changebackgroundanimation(function is for the bgcolor variable is because this function modifies the content of the variable with an assignment statement on line any function can read the value of global variable without specifying the global statement if that function assigns value to global variable without global statementthen python considers that variable to be local variable that just happens to have the same name as global variable the main(function uses the bgcolor variable but doesn' need global statement for it because it only reads the contents of the bgcolor the main(function never assigns bgcolor new value this concept is explained in more detail at the game over animation def gameoveranimation(color=whiteanimationspeed= ) |
10,652 | play all beeps at oncethen flash the background origsurf displaysurf copy(flashsurf pygame surface(displaysurf get_size()flashsurf flashsurf convert_alpha(beep play(play all four beeps at the same timeroughly beep play(beep play(beep play(rgb color for in range( )do the flash times each of the iterations of the for loop on the next line (line belowwill perform flash to have three flashes donewe put all of that code in for loop that has three iterations if you want more or fewer flashesthen change the integer that is passed to range(on line for startendstep in (( )( - ))the for loop on line is exactly the same as the one line the startendand step variables will be used on the next for loop (on line to control how the alpha variable changes reread the --animating the button flash|section if you need to refresh yourself on how these loops work animation loop the first iteration in this loop sets the following for loop to go from to the second from to for alpha in range(startendanimationspeed step)alpha means transparency is opaque is invisible checkforquit(flashsurf fill((rgbalpha)displaysurf blit(origsurf( )displaysurf blit(flashsurf( )drawbuttons(pygame display update(fpsclock tick(fpsthis animation loop works the same as the previous flashing animation code in the --animating the background change|section the copy of the original surface object stored in origsurf is drawn on the display surfacethen flashsurf (which has the new flashing color painted on itis blitted on top of the display surface after the background color is set upthe buttons are drawn on top on line finally the display surface is drawn to the screen with the call to pygame display update(email questions to the authoral@inventwithpython com |
10,653 | the for loop on line adjusts the alpha value for the color used for each frame of animation (increasing at firstand then decreasingconverting from pixel coordinates to buttons def getbuttonclicked(xy) if yellowrect collidepoint(xy) return yellow elif bluerect collidepoint(xy) return blue elif redrect collidepoint(xy) return red elif greenrect collidepoint(xy) return green return none if __name__ ='__main__' main(the getbuttonclicked(function simply takes xy pixel coordinates and returns either the values yellowblueredor green if one of the buttons was clickedor returns none if the xy pixel coordinates are not over any of the four buttons explicit is better than implicit you may have noticed that the code for getbuttonclicked(ends with return none statement on line this might seem like an odd thing to type outsince all functions return none if they don' have any return statement at all we could have left line out entirely and the program would have worked the exact same way so why bother writing it innormally when function reaches the end and returns the none value implicitly (that isthere is no return statement outright saying that it is returning nonethe code that calls it doesn' care about the return value all function calls have to return value (so that they can evaluate to something and be part of expressions)but our code doesn' always make use of the return value for examplethink about the print(function technicallythis function returns the none valuebut we never care about itspam print('hello'hello spam =none true |
10,654 | howeverwhen getbuttonclicked(returns noneit means that the coordinates that were passed to it were not over any of the four buttons to make it clear that in this case the value none is returned from getbuttonclicked()we have the return none line at the end of the function to make your code more readableit is better to have your code be explicit (that isclearly state something even if it might be obviousrather than implicit (that isleaving it up to the person reading code to know how it works without outright telling themin fact--explicit is better than implicit|is one of the python koans the koans are group of little sayings about how to write good code there' an easter egg (that isa little hidden surprisein the python interactive shell where if you try to import module named thisthen it will display --the zen of python|koans try it out in the interactive shellimport this the zen of pythonby tim peters beautiful is better than ugly explicit is better than implicit simple is better than complex complex is better than complicated flat is better than nested sparse is better than dense readability counts special cases aren' special enough to break the rules although practicality beats purity errors should never pass silently unless explicitly silenced in the face of ambiguityrefuse the temptation to guess there should be one-and preferably only one --obvious way to do it although that way may not be obvious at first unless you're dutch now is better than never although never is often better than *rightnow if the implementation is hard to explainit' bad idea if the implementation is easy to explainit may be good idea namespaces are one honking great idea -let' do more of thoseif you' like to know more about what these individual koans meanvisit email questions to the authoral@inventwithpython com |
10,655 | wormy how to play wormy wormy is nibbles clone the player starts out controlling short worm that is constantly moving around the screen the player cannot stop or slow down the wormbut they can control which direction it turns red apple appears randomly on the screenand the player must move the worm so that it eats the apple each time the worm eats an applethe worm grows longer by one segment and new apply randomly appears on the screen the game is over if the worm crashes into itself or the edges of the screen source code to wormy 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 wormy ( nibbles clone by al sweigart al@inventwithpython com creative commons by-nc-sa us import randompygamesys from pygame locals import fps windowwidth windowheight |
10,656 | cellsize assert windowwidth cellsize = "window width must be multiple of cell size assert windowheight cellsize = "window height must be multiple of cell size cellwidth int(windowwidth cellsize cellheight int(windowheight cellsize white ( black red ( green darkgreen darkgray bgcolor black up 'up down 'down left 'left right 'right head syntactic sugarindex of the worm' head def main() global fpsclockdisplaysurfbasicfont pygame init( fpsclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) basicfont pygame font font('freesansbold ttf' pygame display set_caption('wormy' showstartscreen( while true rungame( showgameoverscreen( def rungame() set random start point startx random randint( cellwidth starty random randint( cellheight wormcoords [{' 'startx' 'starty} {' 'startx ' 'starty} {' 'startx ' 'starty}email questions to the authoral@inventwithpython com |
10,657 | direction right start the apple in random place apple getrandomlocation( while truemain game loop for event in pygame event get()event handling loop if event type =quit terminate( elif event type =keydown if (event key =k_left or event key =k_aand direction !right direction left elif (event key =k_right or event key =k_dand direction !left direction right elif (event key =k_up or event key =k_wand direction !down direction up elif (event key =k_down or event key =k_sand direction !up direction down elif event key =k_escape terminate( check if the worm has hit itself or the edge if wormcoords[head][' '=- or wormcoords[head][' '=cellwidth or wormcoords[head][' '=- or wormcoords[head][' '=cellheight return game over for wormbody in wormcoords[ :] if wormbody[' '=wormcoords[head][' 'and wormbody[' '=wormcoords[head][' '] return game over check if worm has eaten an apply if wormcoords[head][' '=apple[' 'and wormcoords[head][' '=apple[' '] don' remove worm' tail segment apple getrandomlocation(set new apple somewhere else del wormcoords[- remove worm' tail segment move the worm by adding segment in the direction it is moving if direction =up |
10,658 | newhead {' 'wormcoords[head][' ']' 'wormcoords[head][' ' elif direction =down newhead {' 'wormcoords[head][' ']' 'wormcoords[head][' ' elif direction =left newhead {' 'wormcoords[head][' ' ' 'wormcoords[head][' '] elif direction =right newhead {' 'wormcoords[head][' ' ' 'wormcoords[head][' '] wormcoords insert( newhead displaysurf fill(bgcolor drawgrid( drawworm(wormcoords drawapple(apple drawscore(len(wormcoords pygame display update( fpsclock tick(fps def drawpresskeymsg() presskeysurf basicfont render('press key to play 'truedarkgray presskeyrect presskeysurf get_rect( presskeyrect topleft (windowwidth windowheight displaysurf blit(presskeysurfpresskeyrect def checkforkeypress() if len(pygame event get(quit) terminate( keyupevents pygame event get(keyup if len(keyupevents= return none if keyupevents[ key =k_escape terminate( return keyupevents[ key def showstartscreen() titlefont pygame font font('freesansbold ttf' titlesurf titlefont render('wormy!'truewhitedarkgreen titlesurf titlefont render('wormy!'truegreen degrees email questions to the authoral@inventwithpython com |
10,659 | degrees while true displaysurf fill(bgcolor rotatedsurf pygame transform rotate(titlesurf degrees rotatedrect rotatedsurf get_rect( rotatedrect center (windowwidth windowheight displaysurf blit(rotatedsurf rotatedrect rotatedsurf pygame transform rotate(titlesurf degrees rotatedrect rotatedsurf get_rect( rotatedrect center (windowwidth windowheight displaysurf blit(rotatedsurf rotatedrect drawpresskeymsg( if checkforkeypress() pygame event get(clear event queue return pygame display update( fpsclock tick(fps degrees + rotate by degrees each frame degrees + rotate by degrees each frame def terminate() pygame quit( sys exit( def getrandomlocation() return {' 'random randint( cellwidth )' 'random randint( cellheight ) def showgameoverscreen() gameoverfont pygame font font('freesansbold ttf' gamesurf gameoverfont render('game'truewhite oversurf gameoverfont render('over'truewhite gamerect gamesurf get_rect( overrect oversurf get_rect( gamerect midtop (windowwidth overrect midtop (windowwidth gamerect height displaysurf blit(gamesurfgamerect displaysurf blit(oversurfoverrect drawpresskeymsg( |
10,660 | pygame display update( pygame time wait( checkforkeypress(clear out any key presses in the event queue while true if checkforkeypress() pygame event get(clear event queue return def drawscore(score) scoresurf basicfont render('score% (score)truewhite scorerect scoresurf get_rect( scorerect topleft (windowwidth displaysurf blit(scoresurfscorerect def drawworm(wormcoords) for coord in wormcoords coord[' 'cellsize coord[' 'cellsize wormsegmentrect pygame rect(xycellsizecellsize pygame draw rect(displaysurfdarkgreenwormsegmentrect worminnersegmentrect pygame rect( cellsize cellsize pygame draw rect(displaysurfgreenworminnersegmentrect def drawapple(coord) coord[' 'cellsize coord[' 'cellsize applerect pygame rect(xycellsizecellsize pygame draw rect(displaysurfredapplerect def drawgrid() for in range( windowwidthcellsize)draw vertical lines pygame draw line(displaysurfdarkgray( )(xwindowheight) for in range( windowheightcellsize)draw horizontal lines pygame draw line(displaysurfdarkgray( )(windowwidthy) if __name__ ='__main__' main(email questions to the authoral@inventwithpython com |
10,661 | the grid if you play the game littleyou'll notice that the apple and the segments of the worm' body always fit along grid of lines we will call each of the squares in this grid cell (it' not always what space in grid is calledit' just name came up withthe cells have their own cartesian coordinate systemwith ( being the top left cell and ( being the bottom right cell the setup code wormy ( nibbles clone by al sweigart al@inventwithpython com creative commons by-nc-sa us import randompygamesys from pygame locals import fps windowwidth windowheight cellsize assert windowwidth cellsize = "window width must be multiple of cell size assert windowheight cellsize = "window height must be multiple of cell size cellwidth int(windowwidth cellsize cellheight int(windowheight cellsize |
10,662 | the code at the start of the program just sets up some constant variables used in the game the width and height of the cells are stored in cellsize the assert statements on lines and ensure that the cells fit perfectly in the window for exampleif the cellsize was and the windowwidth or windowheight constants were set to then only cells could fit the assert statements make sure that only whole integer number of cells fits in the window white ( black red ( green darkgreen darkgray bgcolor black up 'up down 'down left 'left right 'right head syntactic sugarindex of the worm' head some more constants are set on lines to the head constant will be explained later in this the main(function def main() global fpsclockdisplaysurfbasicfont pygame init( fpsclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) basicfont pygame font font('freesansbold ttf' pygame display set_caption('wormy' showstartscreen( while true rungame( showgameoverscreen(in the wormy game programwe've put the main part of the code in function called rungame(this is because we only want to show the --start screen|(the animation with the rotating --wormy|textonce when the program starts (by calling the showstartscreen(email questions to the authoral@inventwithpython com |
10,663 | functionthen we want to call rungame()which will start game of wormy this function will return when the player' worm collides into wall or into itself and causes game over at that point we will show the game over screen by calling showgameoverscreen(when that function call returnsthe loop goes back to the start and calls rungame(again the while loop on line will loop forever until the program terminates separate rungame(function def rungame() set random start point startx random randint( cellwidth starty random randint( cellheight wormcoords [{' 'startx' 'starty} {' 'startx ' 'starty} {' 'startx ' 'starty} direction right start the apple in random place apple getrandomlocation(at the beginning of gamewe want the worm to start in random position (but not too close to the edges of the boardso we store random coordinate in startx and starty (remember that cellwidth and cellheight is the number of cells wide and high the window isnot the number of pixels wide and highthe body of the worm will be stored in list of dictionary values there will be one dictionary value per body segment of the worm the dictionary will have keys 'xand 'yfor the xy coordinates of that body segment the head of the body to be at startx and starty the other two body segments will be one and two cells to the left of the head the head of the worm will always be the body part at wormcoords[ to make this code more readablewe've set the head constant to on line so that we can use wormcoords[headinstead of wormcoords[ the event handling loop while truemain game loop for event in pygame event get()event handling loop if event type =quit terminate( elif event type =keydown if (event key =k_left or event key =k_aand direction !right |
10,664 | direction !left !down direction !up direction left elif (event key =k_right or event key =k_dand direction right elif (event key =k_up or event key =k_wand direction direction up elif (event key =k_down or event key =k_sand direction down elif event key =k_escapeterminate(line is the start of the main game loop and line is the start of the event handling loop if the event is quit eventthen we call terminate((which we've defined the same as the terminate(function in the previous game programsotherwiseif the event is keydown eventthen we check if the key that was pressed down is an arrow key or wasd key we want an additional check so that the worm does not turn in on itself for exampleif the worm is moving leftthen if the player accidentally presses the right arrow keythe worm would immediate start going right and crash into itself that is why we have this check for the current value of the direction variable that wayif the player accidentally presses an arrow key that would cause them to immediately crash the wormwe just ignore that key press collision detection check if the worm has hit itself or the edge if wormcoords[head][' '=- or wormcoords[head][' '=cellwidth or wormcoords[head][' '=- or wormcoords[head][' '=cellheight return game over for wormbody in wormcoords[ :] if wormbody[' '=wormcoords[head][' 'and wormbody[' '=wormcoords[head][' '] return game over the worm has crashed when the head has moved off the edge of the grid or when the head moves onto cell that is already occupied by another body segment we can check if the head has moved off the edge of the grid by seeing if either the coordinate of the head (which is stored in wormcoords[head][' ']is - (which is past the left edge email questions to the authoral@inventwithpython com |
10,665 | of the gridor equal to cellwidth (which is past the right edgesince the rightmost cell coordinate is one less than cellwidththe head has also moved off the grid if the coordinate of the head (which is stored in wormcoords[head][' ']is either - (which is past the top edgeor cellheight (which is past the bottom edgeall we have to do to end the current game is to return out of rungame(when rungame(returns to the function call in main()the next line after the rungame(call (line is the call to showgameoverscreen(which makes the large --game over|text appear this is why we have the return statement on line line loops through every body segment in wormcoords after the head (which is at index this is why the for loop iterates over wormcoords[ :instead of just wormcoordsif both the 'xand 'yvalues of the body segment are the same as the 'xand 'yof the headthen we also end the game by returning out of the rungame(function detecting collisions with the apple check if worm has eaten an apply if wormcoords[head][' '=apple[' 'and wormcoords[head][' '=apple[' '] don' remove worm' tail segment apple getrandomlocation(set new apple somewhere else del wormcoords[- remove worm' tail segment we do similar collision detection check between the head of the worm and the apple' xy coordinates if they matchwe set the coordinates of the apple to random new location (which we get from the return value of getrandomlocation()if the head has not collided with an applethen we delete the last body segment in the wormcoords list remember that negative integers for indexes count from the end of the list so while is the index of the first item in the list and is for the second item- is for the last item in the list and - is for the second to last item the code on lines to (described next in the --moving the worm|sectionwill add new body segment (for the headin the direction that the worm is going this will make the worm one segment longer by not deleting the last body segment when the worm eats an applethe overall length of the worm increases by one but when line deletes the last body segmentthe size remains the same because new head segment is added right afterwards |
10,666 | moving the worm move the worm by adding segment in the direction it is moving if direction =up newhead {' 'wormcoords[head][' ']' 'wormcoords[head][' ' elif direction =down newhead {' 'wormcoords[head][' ']' 'wormcoords[head][' ' elif direction =left newhead {' 'wormcoords[head][' ' ' 'wormcoords[head][' '] elif direction =right newhead {' 'wormcoords[head][' ' ' 'wormcoords[head][' '] wormcoords insert( newheadto move the wormwe add new body segment to the beginning of the wormcoords list because the body segment is being added to the beginning of the listit will become the new head the coordinates of the new head will be right next to the old head' coordinates whether is added or subtracted from either the or coordinate depends on the direction the worm was going this new head segment is added to wormcoords with the insert(list method on line the insert(list method unlike the append(list method that can only add items to the end of listthe insert(list method can add items anywhere inside the list the first parameter for insert(is the index where the item should go (all the items originally at this index and after have their indexes increase by oneif the argument passed for the first parameter is larger than the length of the listthe item is simply added to the end of the list (just like what append(doesthe second parameter for insert(is the item value to be added type the following into the interactive shell to see how insert(worksspam ['cat''dog''bat'spam insert( 'frog'spam ['frog''cat''dog''bat'spam insert( spam ['frog''cat''dog''bat' spam insert( 'horse'spam ['frog''cat''horse''dog''bat' email questions to the authoral@inventwithpython com |
10,667 | drawing the screen displaysurf fill(bgcolordrawgrid(drawworm(wormcoordsdrawapple(appledrawscore(len(wormcoords pygame display update(fpsclock tick(fpsthe code for drawing the screen in the rungame(function is fairly simple line fills in the entire display surface with the background color lines to draw the gridwormappleand score to the display surface then the call to pygame display update(draws the display surface to the actual computer screen drawing "press keytext to the screen def drawpresskeymsg() presskeysurf basicfont render('press key to play 'truedarkgray presskeyrect presskeysurf get_rect( presskeyrect topleft (windowwidth windowheight displaysurf blit(presskeysurfpresskeyrectwhile the start screen animation is playing or the game over screen is being shownthere will be some small text in the bottom right corner that says --press key to play |rather than have the code typed out in both the showstartscreen(and the showgameoverscreen()we put it in this separate function and simply call the function from showstartscreen(and showgameoverscreen(the checkforkeypress(function def checkforkeypress() if len(pygame event get(quit) terminate( keyupevents pygame event get(keyup if len(keyupevents= return none if keyupevents[ key =k_escape terminate( return keyupevents[ key |
10,668 | this function first checks if there are any quit events in the event queue the call to pygame event get(on line returns list of all the quit events in the event queue (because we pass quit as an argumentif there are not quit events in the event queuethen the list that pygame event get(returns will be the empty list[the len(call on line will return if pygame event get(returned an empty list if there are more than zero items in the list returned by pygame event get((and rememberany items in this list will only be quit events because we passed quit as the argument to pygame event get())then the terminate(function gets called on line and the program terminates after thatthe call to pygame event get(gets list of any keyup events in the event queue if the key event is for the esc keythen the program terminates in that case as well otherwisethe first key event object in the list that was returned by pygame event get(is returned from this checkforkeypress(function the start screen def showstartscreen() titlefont pygame font font('freesansbold ttf' titlesurf titlefont render('wormy!'truewhitedarkgreen titlesurf titlefont render('wormy!'truegreen degrees degrees while true displaysurf fill(bgcolorwhen the wormy game program first begins runningthe player doesn' automatically begin playing the game insteada start screen appears which tells the player what program they are running start screen also gives the player chance to prepare for the game to begin (otherwise the player might not be ready and crash on their first gamethe wormy start screen requires two surface objects with the --wormy!|text drawn on them these are what the render(method calls create on lines and the text will be largethe font(constructor function call on line creates font object that is points in size the first --wormy!|text will have white text with dark green backgroundand the other will have green text with transparent background line begins the animation loop for the start screen during this animationthe two pieces of text will be rotated and drawn to the display surface object email questions to the authoral@inventwithpython com |
10,669 | rotating the start screen text rotatedsurf pygame transform rotate(titlesurf degrees rotatedrect rotatedsurf get_rect(rotatedrect center (windowwidth windowheight displaysurf blit(rotatedsurf rotatedrect rotatedsurf pygame transform rotate(titlesurf degrees rotatedrect rotatedsurf get_rect(rotatedrect center (windowwidth windowheight displaysurf blit(rotatedsurf rotatedrect drawpresskeymsg(if checkforkeypress()pygame event get(clear event queue return pygame display update(fpsclock tick(fpsthe showstartscreen(function will rotate the images on the surface objects that the --wormy!|text is written on the first parameter is the surface object to make rotated copy of the second parameter is the number of degrees to rotate the surface the pygame transform rotate(function doesn' change the surface object you pass itbut rather returns new surface object with the rotated image drawn on it note that this new surface object will probably be larger than the original onesince all surface objects represent rectangular areas and the corners of the rotated surface will stick out past the width and height of original surface the picture below has black rectangle along with slightly rotated version of itself in order to make surface object that can fit the rotated rectangle (which is colored gray in the picture below)it must be larger than the original black rectangle' surface objectthe amount you rotate it is given in degreeswhich is measure of rotation there are degrees in circle not rotated at all is degrees rotating to one quarter counter-clockwise is degrees to rotate clockwisepass negative integer rotating degrees is rotating the image all the way aroundwhich means you end up with the same image as if you rotated it degrees in factif the rotation argument you pass to pygame transform rotate(is or larger |
10,670 | then pygame automatically keeps subtracting from it until it gets number less than this image shows several examples of different rotation amountsthe two rotated --wormy!|surface objects are blitted to the display surface on each frame of the animation loop on lines and on line the drawpresskeymsg(function call draws the --press key to play |text in the lower corner of the display surface object this animation loop will keep looping until checkforkeypress(returns value that is not nonewhich happens if the player presses key before returningpygame event get(is called simply to clear out any other events that have accumulated in the event queue which the start screen was displayed rotations are not perfect you may wonder why we store the rotated surface in separate variablerather than just overwrite the titlesurf and titlesurf variables there are two reasons firstrotating image is never completely perfect the rotated image is always approximate if you rotate an image by degrees counterclockwiseand then rotate it back degrees clockwisethe image you have will not be the exact same image you started with think of it as making photocopyand then photocopy of the first photocopyand the another photocopy of that photocopy if you keep doing thisthe image gets worse and worse as the slight distortions add up (the only exception to this is if you rotate an image by multiple of degreessuch as or degrees in that casethe pixels can be rotated without any distortion secondif you rotate image then the rotated image will be slightly larger than the original image if you rotate that rotated imagethen the next rotated image will be slightly larger again if you keep doing thiseventually the image will become too large for pygame to handleand your email questions to the authoral@inventwithpython com |
10,671 | program will crash with the error messagepygame errorwidth or height is too large degrees + rotate by degrees each frame degrees + rotate by degrees each frame the amount that we rotate the two --wormy!|text surface objects is stored in degrees and degrees on each iteration through the animation loopwe increase the number stored in degrees by and degrees by this means on the next iteration of the animation loop the white text --wormy!|surface object will be rotated by another degrees and the green text --wormy!|surface object will be rotated by another degrees this is why the one of the surface objects rotates slower than the other def terminate() pygame quit( sys exit(the terminate(function calls pygame quit(and sys exit(so that the game correctly shuts down it is identical to the terminate(functions in the previous game programs deciding where the apple appears def getrandomlocation() return {' 'random randint( cellwidth )' 'random randint( cellheight )the getrandomlocation(function is called whenever new coordinates for the apple are needed this function returns dictionary with keys 'xand ' 'with the values set to random xy coordinates game over screens def showgameoverscreen() gameoverfont pygame font font('freesansbold ttf' gamesurf gameoverfont render('game'truewhite oversurf gameoverfont render('over'truewhite gamerect gamesurf get_rect( overrect oversurf get_rect( gamerect midtop (windowwidth overrect midtop (windowwidth gamerect height displaysurf blit(gamesurfgamerect |
10,672 | displaysurf blit(oversurfoverrectdrawpresskeymsg(pygame display update(the game over screen is similar to the start screenexcept it isn' animated the words --game|and --over|are rendered to two surface objects which are then drawn on the screen pygame time wait( checkforkeypress(clear out any key presses in the event queue while trueif checkforkeypress()pygame event get(clear event queue return the game over text will stay on the screen until the player pushes key just to make sure the player doesn' accidentally press key too soonwe will put half second pause with the call to pygame time wait(on line (the argument stands for millisecond pausewhich is half of one second thencheckforkeypress(is called so that any key events that were made since the showgameoverscreen(function started are ignored this pause and dropping of the key events is to prevent the following situationsay the player was trying to turn away from the edge of the screen at the last minutebut pressed the key too late and crashed into the edge of the board if this happensthen the key press would have happened after the showgameoverscreen(was calledand that key press would cause the game over screen to disappear almost instantly the next game would start immediately after thatand might take the player by surprise adding this pause helps the make the game more --user friendly|drawing functions the code to draw the scorewormappleand grid are all put into separate functions def drawscore(score) scoresurf basicfont render('score% (score)truewhite scorerect scoresurf get_rect( scorerect topleft (windowwidth displaysurf blit(scoresurfscorerectthe drawscore(function simply renders and draws the text of the score that was passed in its score parameter on the display surface object email questions to the authoral@inventwithpython com |
10,673 | def drawworm(wormcoords) for coord in wormcoords coord[' 'cellsize coord[' 'cellsize wormsegmentrect pygame rect(xycellsizecellsize pygame draw rect(displaysurfdarkgreenwormsegmentrect worminnersegmentrect pygame rect( cellsize cellsize pygame draw rect(displaysurfgreenworminnersegmentrectthe drawworm(function will draw green box for each of the segments of the worm' body the segments are passed in the wormcoords parameterwhich is list of dictionaries each with an 'xkey and 'ykey the for loop on line loops through each of the dictionary values in wormcoords because the grid coordinates take up the entire window and also begin pixelit is fairly easy to convert from grid coordinates to pixel coordinates line and simply multiply the coord[' 'and coord[' 'coordinate by the cellsize line creates rect object for the worm segment that will be passed to the pygame draw rect(function on line remember that each cell in the grid is cellsize in width and heightso that' what the size of the segment' rect object should be line draws dark green rectangle for the segment then on top of thisa smaller bright green rectangle is drawn this makes the worm look little nicer the inner bright green rectangle starts pixels to the right and pixels below the topleft corner of the cell the width and height of this rectangle are pixels less than the cell sizeso there will be pixel margin on the right and bottom sides as well def drawapple(coord) coord[' 'cellsize coord[' 'cellsize applerect pygame rect(xycellsizecellsize pygame draw rect(displaysurfredapplerectthe drawapple(function is very similar to drawworm()except since the red apple is just single rectangle that fills up the cellall the function needs to do is convert to pixel coordinates (which is what lines and do)create the rect object with the location and size of the apple (line )and then pass this rect object to the pygame draw rect(function def drawgrid() for in range( windowwidthcellsize)draw vertical lines |
10,674 | pygame draw line(displaysurfdarkgray( )(xwindowheight)for in range( windowheightcellsize)draw horizontal lines pygame draw line(displaysurfdarkgray( )(windowwidthy)just to make it easier to visualize the grid of cellswe call pygame draw line(to draw out each of the vertical and horizontal lines of the grid normallyto draw the vertical lines neededwe would need calls to pygame draw line(with the following coordinatespygame draw line(displaysurfdarkgray( )( windowheight)pygame draw line(displaysurfdarkgray( )( windowheight)pygame draw line(displaysurfdarkgray( )( windowheight)pygame draw line(displaysurfdarkgray( )( windowheight)skipped for brevity pygame draw line(displaysurfdarkgray( )( windowheight)pygame draw line(displaysurfdarkgray( )( windowheight)pygame draw line(displaysurfdarkgray( )( windowheight)pygame draw line(displaysurfdarkgray( )( windowheight)instead of typing out all these lines of codewe can just have one line of code inside for loop notice that the pattern for the vertical lines is that the coordinate of the start and end point starts at and goes up to increasing by each time the coordinate is always for the start point and windowheight for the end point parameter that means the for loop should iterate over range( this is why the for loop on line iterates over range( windowwidthcellsizefor the horizontal linesthe coordinates would have to bepygame draw line(displaysurfdarkgray( )(windowwidth )pygame draw line(displaysurfdarkgray( )(windowwidth )pygame draw line(displaysurfdarkgray( )(windowwidth )pygame draw line(displaysurfdarkgray( )(windowwidth )skipped for brevity pygame draw line(displaysurfdarkgray( )(windowwidth )pygame draw line(displaysurfdarkgray( )(windowwidth )pygame draw line(displaysurfdarkgray( )(windowwidth )pygame draw line(displaysurfdarkgray( )(windowwidth )the coordinate ranges from to increasing by each time the coordinate is always for the start point and windowwidth for the end point parameter we can also use for loop here so we don' have to type out all those pygame draw line(calls email questions to the authoral@inventwithpython com |
10,675 | noticing regular patterns needed by the calls and using loops is clever programmer trick to save us from lot of typing we could have typed out all pygame draw line(calls and the program would have worked the exact same but by being little bit cleverwe can save ourselves lot of work if __name__ ='__main__' main(after all the functions and constants and global variables have been defined and createdthe main(function is called to start the game don' reuse variable names take look at few lines of code from the drawworm(function again wormsegmentrect pygame rect(xycellsizecellsize pygame draw rect(displaysurfdarkgreenwormsegmentrect worminnersegmentrect pygame rect( cellsize cellsize pygame draw rect(displaysurfgreenworminnersegmentrectnotice that two different rect objects are created on lines and the rect object created on line is stored in the wormsegmentrect local variable and is passed to the pygame draw rect(function on line the rect object created on line is stored in the worminnersegmentrect local variable and is passed to the pygame draw rect(function on line every time you create variableit takes up small amount of the computer' memory you might think it would be clever to reuse the wormsegmentrect variable for both rect objectslike this wormsegmentrect pygame rect(xycellsizecellsizepygame draw rect(displaysurfdarkgreenwormsegmentrectwormsegmentrect pygame rect( cellsize cellsize pygame draw rect(displaysurfgreenworminnersegmentrectbecause the rect object returned by pygame rect(on line won' be needed after we can overwrite this value and reuse the variable to store the rect object returned by pygame rect(on line since we are now using fewer variables we are saving memoryright |
10,676 | while this is technically trueyou really are only saving few bytes modern computers have memory of several billion bytes so the savings aren' that great meanwhilereusing variables reduces the code readability if programmer was reading through this code after it was writtenthey would see that wormsegmentrect is passed to the pygame draw rect(calls on line and if they tried to find the first time the wormsegmentrect variable was assigned valuethey would see the pygame rect(call on line they might not realize that the rect object returned by line ' pygame rect(call isn' the same as the one that is passed to the pygame draw rect(call on line little things like this make it harder to understand how exactly your program works it won' just be other programmers looking at your code who will be confused when you look at your own code couple weeks after writing ityou may have hard time remembering how exactly it works code readability is much more important than saving few bytes of memory here and there for additional programming practiceyou can download buggy versions of wormy from email questions to the authoral@inventwithpython com |
10,677 | tetromino how to play tetromino tetromino is tetris clone differently shaped blocks (each made up of four boxesfall from the top of the screenand the player must guide them down to form complete rows that have no gaps in them when complete row is formedthe row disappears and each row above it moves down one row the player tries to keep forming complete lines until the screen fills up and new falling block cannot fit on the screen some tetromino nomenclature in this have come up with set of terms for the different things in the game program board the board is made up of spaces that the blocks fall and stack up in box box is single filled-in square space on the board piece the things that fall from the top of the board that the player can rotate and position each piece has shape and is made up of boxes shape the shapes are the different types of pieces in the game the names of the shapes are tszjliand |
10,678 | template list of shape data structures that represents all the possible rotations of shape these are store in variables with names like s_shape_template or j_shape_template landed when piece has either reached the bottom of the board or is touching box on the boardwe say that the piece has landed at that pointthe next piece should start falling source code to tetromino 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 the background music files in the same folder of as the tetromino py file you can download them from here tetromino ( tetris clone by al sweigart al@inventwithpython com creative commons by-nc-sa us import randomtimepygamesys from pygame locals import fps windowwidth windowheight boxsize boardwidth boardheight blank movesidewaysfreq movedownfreq xmargin int((windowwidth boardwidth boxsize topmargin windowheight (boardheight boxsize email questions to the authoral@inventwithpython com |
10,679 | white ( gray ( black red ( lightred ( green lightgreen blue lightblue yellow ( lightyellow ( bordercolor blue bgcolor black textcolor white textshadowcolor gray colors bluegreenredyellow lightcolors (lightbluelightgreenlightredlightyellow assert len(colors=len(lightcolorseach color must have light color templatewidth templateheight s_shape_template [[' ' oo ' oo ' '] [' ' oo ' ' '] z_shape_template [[' ' oo ' oo ' '] [' ' oo ' ' '] i_shape_template [[ ' |
10,680 | ' ' ' '] [' ' 'oooo ' ' '] o_shape_template [[' ' oo ' oo ' '] j_shape_template [[' ' ooo ' ' '] [' oo ' ' ' '] [' ' ooo ' ' '] [' ' ' oo ' '] l_shape_template [[' ' ooo ' ' '] [' ' ' oo 'email questions to the authoral@inventwithpython com |
10,681 | '] [' ' ooo ' ' '] [' oo ' ' ' '] t_shape_template [[' ' ooo ' ' '] [' ' oo ' ' '] [' ' ooo ' ' '] [' ' oo ' ' '] shapes {' 's_shape_template ' 'z_shape_template ' 'j_shape_template ' 'l_shape_template ' 'i_shape_template ' 'o_shape_template ' 't_shape_template def main() global fpsclockdisplaysurfbasicfontbigfont pygame init( fpsclock pygame time clock( |
10,682 | displaysurf pygame display set_mode((windowwidthwindowheight) basicfont pygame font font('freesansbold ttf' bigfont pygame font font('freesansbold ttf' pygame display set_caption('tetromino' showtextscreen('tetromino' while truegame loop if random randint( = pygame mixer music load('tetrisb mid' else pygame mixer music load('tetrisc mid' pygame mixer music play(- rungame( pygame mixer music stop( showtextscreen('game over' def rungame() setup variables for the start of the game board getblankboard( lastmovedowntime time time( lastmovesidewaystime time time( lastfalltime time time( movingdown false notethere is no movingup variable movingleft false movingright false score levelfallfreq calculatelevelandfallfreq(score fallingpiece getnewpiece( nextpiece getnewpiece( while truemain game loop if fallingpiece =none no falling piece in playso start new piece at the top fallingpiece nextpiece nextpiece getnewpiece( lastfalltime time time(reset lastfalltime if not isvalidposition(boardfallingpiece) return can' fit new piece on the boardso game over checkforquit( for event in pygame event get()event handling loop if event type =keyup if (event key =k_p)email questions to the authoral@inventwithpython com |
10,683 | pausing the game displaysurf fill(bgcolor pygame mixer music stop( showtextscreen('paused'pause until key press pygame mixer music play(- lastfalltime time time( lastmovedowntime time time( lastmovesidewaystime time time( elif (event key =k_left or event key =k_a) movingleft false elif (event key =k_right or event key =k_d) movingright false elif (event key =k_down or event key =k_s) movingdown false elif event type =keydown moving the block sideways if (event key =k_left or event key =k_aand isvalidposition(boardfallingpieceadjx=- ) fallingpiece[' '- movingleft true movingright false lastmovesidewaystime time time( elif (event key =k_right or event key =k_dand isvalidposition(boardfallingpieceadjx= ) fallingpiece[' '+ movingright true movingleft false lastmovesidewaystime time time( rotating the block (if there is room to rotate elif (event key =k_up or event key =k_w) fallingpiece['rotation'(fallingpiece['rotation' len(shapes[fallingpiece['shape']] if not isvalidposition(boardfallingpiece) fallingpiece['rotation'(fallingpiece['rotation' len(shapes[fallingpiece['shape']] 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']] making the block fall faster with the down key |
10,684 | elif (event key =k_down or event key =k_s) movingdown true if isvalidposition(boardfallingpieceadjy= ) fallingpiece[' '+ lastmovedowntime time time( move the current block all the way down elif event key =k_space movingdown false movingleft false movingright false for in range( boardheight) if not isvalidposition(boardfallingpieceadjy= ) break fallingpiece[' '+ 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( if movingdown and time time(lastmovedowntime movedownfreq and isvalidposition(boardfallingpieceadjy= ) fallingpiece[' '+ lastmovedowntime time time( let the piece fall if it is time to fall if time time(lastfalltime fallfreq see if the piece has landed if not isvalidposition(boardfallingpieceadjy= ) falling piece has landedset it on the board addtoboard(boardfallingpiece score +removecompletelines(board levelfallfreq calculatelevelandfallfreq(score fallingpiece none else piece did not landjust move the block down fallingpiece[' '+ lastfalltime time time(email questions to the authoral@inventwithpython com |
10,685 | drawing everything on the screen displaysurf fill(bgcolor drawboard(board drawstatus(scorelevel drawnextpiece(nextpiece if fallingpiece !none drawpiece(fallingpiece pygame display update( fpsclock tick(fps def maketextobjs(textfontcolor) surf font render(texttruecolor return surfsurf get_rect( def terminate() pygame quit( sys exit( 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 continue return event key return none 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 |
10,686 | 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(presskeysurfpresskeyrect while checkforkeypress(=none pygame display update( fpsclock tick( 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 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 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 def addtoboard(boardpiece) fill in the board based on piece' locationshapeand rotation for in range(templatewidth)email questions to the authoral@inventwithpython com |
10,687 | for in range(templateheight) if shapes[piece['shape']][piece['rotation']][ ][ !blank board[ piece[' ']][ piece[' ']piece['color' def getblankboard() create and return new blank board data structure board [ for in range(boardwidth) board append([blankboardheight return board def isonboard(xy) return > and boardwidth and boardheight 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 if not isonboard( piece[' 'adjxy piece[' 'adjy) return false if board[ piece[' 'adjx][ piece[' 'adjy!blank return false return true 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 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 |
10,688 | while > 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 else - move on to check next row up return numlinesremoved 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) 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 ) 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 email questions to the authoral@inventwithpython com |
10,689 | pygame draw rect(displaysurfbgcolor(xmargintopmarginboxsize boardwidthboxsize boardheight) draw the individual boxes on the board for in range(boardwidth) for in range(boardheight) drawbox(xyboard[ ][ ] 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(levelsurflevelrect 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) 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,690 | if __name__ ='__main__' main(the usual setup code tetromino ( tetris clone by al sweigart al@inventwithpython com creative commons by-nc-sa us import randomtimepygamesys from pygame locals import fps windowwidth windowheight boxsize boardwidth boardheight blank these are the constants used by our tetromino game each box is square that is pixels wide and high the board itself is boxes wide and boxes tall the blank constant will be used as value to represent blank spaces in the board' data structure setting up timing constants for holding down keys movesidewaysfreq movedownfreq every time the player pushes the left or right arrow key downthe falling piece should move one box over to the left or rightrespectively howeverthe player can also hold down the left or right arrow key to keep moving the falling piece the movesidewaysfreq constant will set it so that every seconds that passes with the left or right arrow key held downthe piece will move another space over the movedownfreq constant is the same thing except it tells how frequently the piece drops by one box while the player has the down arrow key held down more setup code xmargin int((windowwidth boardwidth boxsize email questions to the authoral@inventwithpython com |
10,691 | topmargin windowheight (boardheight boxsize the program needs to calculate how many pixels are to the left and right side of the board to use later in the program windowwidth is the total number of pixels wide the entire window is the board is boardwidth boxes wide and each box is boxsize pixels wide if we subtract boxsize pixels from this for each of the boxes wide in the board (which is boardwidth boxsize)we'll have the size of the margin to the left and right of the board if we divide this by then we will have the size of just one margin since the margins are the same sizewe can use xmargin for either the left-side or right-side margin we can calculate the size of the space between the top of the board and the top of the window in similar manner the board will be drawn pixels above the bottom of the windowso is subtracted from topmargin to account for this white ( gray ( black red ( lightred ( green lightgreen blue lightblue yellow ( lightyellow ( |
10,692 | bordercolor blue bgcolor black textcolor white textshadowcolor gray colors bluegreenredyellow lightcolors (lightbluelightgreenlightredlightyellow assert len(colors=len(lightcolorseach color must have light color the pieces will come in four colorsbluegreenredand yellow when we draw the boxes thoughthere will be thin highlight on the box in lighter color so this means we need to create light bluelight greenlight redand light yellow colors as well each of these four colors will be stored in tuples named colors (for the normal colorsand lightcolors (for the lighter colorssetting up the piece templates templatewidth templateheight s_shape_template [[' ' oo ' oo ' '] [' ' oo ' ' '] z_shape_template [[' ' oo ' oo ' '] [' ' oo ' ' '] i_shape_template [[ ' 'email questions to the authoral@inventwithpython com |
10,693 | ' ' '] [' ' 'oooo ' ' '] o_shape_template [[' ' oo ' oo ' '] j_shape_template [[' ' ooo ' ' '] [' oo ' ' ' '] [' ' ooo ' ' '] [' ' ' oo ' '] l_shape_template [[' ' ooo ' ' '] [' ' ' oo ' '] |
10,694 | [' ' ooo ' ' '] [' oo ' ' ' '] t_shape_template [[' ' ooo ' ' '] [' ' oo ' ' '] [' ' ooo ' ' '] [' ' oo ' ' ']our game program needs to know how each of the shapes are shapedincluding for all of their possible rotations in order to do thiswe will create lists of lists of strings the inner list of strings will represent single rotation of shapelike this[''oo 'oo ''we will write the rest of our code so that it interprets list of strings like the one above to represent shape where the periods are empty spaces and the ' are boxeslike thisemail questions to the authoral@inventwithpython com |
10,695 | splitting "line of codeacross multiple lines you can see that this list is spread across many lines in the file editor this is perfectly valid pythonbecause the python interpreter realizes that until it sees the closing square bracketthe list isn' finished the indentation doesn' matter because python knows you won' have different indentation for new block in the middle of list this code below works just finespam ['hello' 'world' 'fuzz'eggs ['hello' 'world 'fuzz'thoughof coursethe code for the eggs list would be much more readable if we lined up all the items in the list or put on single line like spam normallysplitting line of code across multiple lines in the file editor would require putting character at the end of the line the tells python--this code continues onto the next line |(this slash was first used in the sliding puzzle game in the isvalidmove(function we will make --template|data structures of the shapes by creating list of these list of stringsand store them in variables such as s_shape_template this waylen(s_shape_templatewill represent how many possible rotations there are for the shapeand s_shape_template[ will represent the shape' first possible rotation lines to will create --template|data structures for each of the shapes imagine that each possible piece in tiny board of empty spacewith some of the spaces on the board filled in with boxes the following expressions that use s_shape_template[ are trues_shape_template[ ][ ][ ='os_shape_template[ ][ ][ ='os_shape_template[ ][ ][ ='os_shape_template[ ][ ][ ='oif we represented this shape on paperit would look something like this |
10,696 | this is how we can represent things like tetromino pieces as python values such as strings and lists the templatewidth and templateheight constants simply set how large each row and column for each shape' rotation should be (the templates will always be shapes {' 's_shape_template ' 'z_shape_template ' 'j_shape_template ' 'l_shape_template ' 'i_shape_template ' 'o_shape_template ' 't_shape_templatethe shapes variable will be dictionary that stores all of the different templates because each template has all the possible rotations of single shapethis means that the shapes variable contains all possible rotations of every possible shape this will be the data structure that contains all of the shape data in our game the main(function def main() global fpsclockdisplaysurfbasicfontbigfont pygame init( fpsclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) basicfont pygame font font('freesansbold ttf' bigfont pygame font font('freesansbold ttf' pygame display set_caption('tetromino' showtextscreen('tetromino'email questions to the authoral@inventwithpython com |
10,697 | the main(function handles creating some more global constants and showing the start screen that appears when the program is run while truegame loop if random randint( = pygame mixer music load('tetrisb mid'elsepygame mixer music load('tetrisc mid'pygame mixer music play(- rungame(pygame mixer music stop(showtextscreen('game over'the code for the actual game is all in rungame(the main(function here simply randomly decides what background music to start playing (either the tetrisb mid or tetrisc mid midi music file)then calls rungame(to begin the game when the player losesrungame(will return to main()which then stops the background music and displays the game over screen when the player presses keythe showtextscreen(function that displays the game over screen will return the game loop will loop back to the beginning at line and start another game the start of new game def rungame() setup variables for the start of the game board getblankboard( lastmovedowntime time time( lastmovesidewaystime time time( lastfalltime time time( movingdown false notethere is no movingup variable movingleft false movingright false score levelfallfreq calculatelevelandfallfreq(score fallingpiece getnewpiece( nextpiece getnewpiece(before the game begins and pieces start fallingwe need to initialize some variables to their startof-game values on line the fallingpiece variable will be set to the currently falling piece that can be rotated by the player on line the nextpiece variable will be set to the piece that shows up in the --next|part of the screen so that player knows what piece is coming up after setting the falling piece |
10,698 | the game loop while truemain game loop if fallingpiece =noneno falling piece in playso start new piece at the top fallingpiece nextpiece nextpiece getnewpiece(lastfalltime time time(reset lastfalltime if not isvalidposition(boardfallingpiece)return can' fit new piece on the boardso game over checkforquit(the main game loop that starts on line handles all of the code for the main part of the game when pieces are falling to the bottom the fallingpiece variable is set to none after the falling piece has landed this means that the piece in nextpiece should be copied to the fallingpiece variableand random new piece should be put into the nextpiece variable new piece can be generated from the getnewpiece(function the lastfalltime variable is also reset to the current time so that the piece will fall in however many seconds is in fallfreq the pieces that getnewpiece(are positioned little bit above the boardusually with part of the piece already on the board but if this is an invalid position because the board is already filled up there (in which case the isvalidposition(call on line will return false)then we know that the board is full and the player should lose the game when this happensthe rungame(function returns the event handling loop for event in pygame event get()event handling loop if event type =keyupthe event handling loop takes care of when the player rotates the falling piecemoves the falling pieceor pauses the game pausing the game if (event key =k_p)pausing the game displaysurf fill(bgcolorpygame mixer music stop(showtextscreen('paused'pause until key press pygame mixer music play(- email questions to the authoral@inventwithpython com |
10,699 | lastfalltime time time(lastmovedowntime time time(lastmovesidewaystime time time(if the player has pressed the keythen the game should pause we need to hide the board from the player (otherwise the player could cheat by pausing the game and taking time to decide where to move the piecethe code blanks out the display surface with call to displaysurf fill(bgcolorand stops the music the showtextscreen(function is called to display the --paused|text and wait for the player to press key to continue once the player has pressed keyshowtextscreen(will return line will restart the background music alsosince large amount of time could have passed since the player paused the gamethe lastfalltimelastmovedowntimeand lastmovesidewaystime variables should all be reset to the current time (which is done on lines to using movement variables to handle user input elif (event key =k_left or event key =k_a)movingleft false elif (event key =k_right or event key =k_d)movingright false elif (event key =k_down or event key =k_s)movingdown false letting up on one of the arrow keys (or the wasd keyswill set the movingleftmovingrightor movingdown variables back to falseindicating that the player no longer wants to move the piece in those directions the code later will handle what to do based on the boolean values inside these --moving|variables note that the up arrow and keys are used for rotating the piecenot moving the piece up this is why there is no movingup variable checking if slide or rotation is valid elif event type =keydown moving the block sideways if (event key =k_left or event key =k_aand isvalidposition(boardfallingpieceadjx=- ) fallingpiece[' '- movingleft true movingright false lastmovesidewaystime time time( |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.