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 downloade... |
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((windowheigh... |
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 ... |
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 ri... |
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 ... |
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 isvali... |
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 (t... |
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(basesurfbgcolo... |
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 =rig... |
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 ... |
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 gen... |
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 compu... |
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( ... |
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... |
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 w... |
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 o... |
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 termin... |
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|bo... |
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[... |
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... |
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... |
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(tiles... |
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 re... |
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... |
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(boardme... |
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 =leftdr... |
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( tilesizeanim... |
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 la... |
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 lis... |
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 executio... |
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 sente... |
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 l... |
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 brightye... |
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 mix... |
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 f... |
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 ev... |
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 randin... |
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) r... |
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... |
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( ... |
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 currents... |
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 u... |
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... |
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 ... |
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 ... |
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 eval... |
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 flashbuttonanimat... |
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 eac... |
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... |
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((supplyin... |
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 dis... |
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 loo... |
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) r... |
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 ... |
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 ... |
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 r... |
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... |
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... |
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 ce... |
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 displays... |
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... |
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 t... |
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 cal... |
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 lin... |
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 w... |
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 direct... |
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 gridwormappl... |
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... |
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 (windowwid... |
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 t... |
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 num... |
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 q... |
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 dra... |
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 d... |
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 al... |
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 t... |
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 pla... |
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 ... |
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 t... |
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 pyga... |
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... |
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 ... |
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(board... |
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 qu... |
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 checkfork... |
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... |
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 s... |
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 scores... |
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 bo... |
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 box... |
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 hi... |
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... |
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' hav... |
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_templat... |
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(... |
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 ... |
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 su... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.