id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
10,700 | when the left arrow key is pressed down (and moving to the left is valid move for the falling pieceas determined by the call to isvalidposition())then we should change the position to one space to the left by subtracting the value of fallingpiece[' 'by the isvalidposition(function has optional parameters called adjx an... |
10,701 | fallingpiece['rotation'(fallingpiece['rotation' len(shapes[fallingpiece['shape']]the up arrow key (or keywill rotate the falling piece to its next rotation all the code has to do is increment the 'rotationkey' value in the fallingpiece dictionary by howeverif incrementing the 'rotationkey' value makes it larger than th... |
10,702 | elif (event key =k_q)rotate the other direction fallingpiece['rotation'(fallingpiece['rotation' len(shapes[fallingpiece['shape']] if not isvalidposition(boardfallingpiece) fallingpiece['rotation'(fallingpiece['rotation' len(shapes[fallingpiece['shape']]lines to do the same thing to except they handle the case where the... |
10,703 | done because this code will move the piece to the absolute bottom and begin falling the next pieceand we don' want to surprise the player by having those pieces immediately start moving just because they were holding down an arrow key when they hit the space key to find the farthest that the piece can fallwe should fir... |
10,704 | if the user held down on the key for longer than seconds (the value stored in movesidewaysfreq is the float then the expression time time(lastmovesidewaystime movesidewaysfreq would evaluate to true line ' condition is true if the user has both held down the arrow key and seconds has passedand in that case we should mo... |
10,705 | not yet not yet not yet not yet not yet not yet not yet not yet not yet passed wait time passed wait time passed wait time passed wait time passed wait timetraceback (most recent call last)file " :\timetest py"line in time sleep( keyboardinterrupt the first number on each line of output is the return value of time time... |
10,706 | lines to do almost the same thing as lines to do except for moving the falling piece down this has separate move variable (movingdownand --last time|variable (lastmovedowntimeas well as different --move frequency|variable (movedownfreqletting the piece "naturallyfall let the piece fall if it is time to fall if time tim... |
10,707 | drawstatus(scoreleveldrawnextpiece(nextpieceif fallingpiece !nonedrawpiece(fallingpiecepygame display update(fpsclock tick(fpsnow that the game loop has handled all events and updated the game statethe game loop just needs to draw the game state to the screen most of the drawing is handled by other functionsso the game... |
10,708 | continue return event key return none the checkforkeypress(function works almost the same as it did in the wormy game first it calls checkforquit(to handle any quit events (or keyup events specifically for the esc keyand terminates the program if there are any then it pulls out all the keyup and keydown events from the... |
10,709 | the showtextscreen(will be used for the start screenthe game over screenand also for pause screen (the pause screen is explained later in this while checkforkeypress(=nonepygame display update(fpsclock tick(we want the text to stay on the screen until the user presses key this small loop will constantly call pygame dis... |
10,710 | to calculate the levelwe use the int(function to round down the score divided by so if the score any number between and the int(call will round it down to the part of the code is there because we want the first level to be level not level when the score reaches then int( will evaluate to and the will make the level her... |
10,711 | fallfreq (level fall frequency (seconds - level you can see that at level the falling frequency will be less than this won' cause any bugs with our codebecause line just checks that the elapsed time since the falling piece last fell one space is greater than the calculated falling frequency so if the falling frequency ... |
10,712 | fallfreq (level fall frequency (seconds - level as you can seewith this new equationlevel would only be as hard as the original level you can change the game to be as difficult or easy as you like by changing the equations in calculatelevelandfallfreq(generating pieces with the getnewpiece(function def getnewpiece() re... |
10,713 | the value for the 'rotationkey is random integer between to one less than however many possible rotations there are for that shape the number of rotations for shape can be found from the expression len(shapes[shape]notice that we don' store the list of string values (like the ones store in the constants like s_shape_te... |
10,714 | return board the data structure used for the board is fairly simpleit' list of lists of values if the value is the same as the value in blankthen it is an empty space if the value is an integerthen it represents box that is the color that the integer indexes in the colors constant list that is is blue is green is redan... |
10,715 | the board with falling piece in valid position the board with the falling piece in an invalid position on the left boardthe falling piece' (that isthe top left corner of the falling piece'sxy coordinates are ( on the board but the boxes inside the falling piece' coordinate system have their own coordinates to find the ... |
10,716 | and now that we can figure out where the falling piece' boxes are as board coordinateswe can see if they overlap with the landed boxes that are already on the board the nested for loops on lines and go through each of the possible coordinates on the falling piece we want to check if box of the falling piece is either o... |
10,717 | the iscompleteline does simple check at the row specified by the parameter row on the board is considered to be --complete|when every space is filled by box the for loop on line goes through each space in the row if space is blank (which is caused by it having the same value as the blank constant)then the function retu... |
10,718 | range()so that the list it returns starts at yends at and after each iteration --increases|by let' look at the following example to save spaceonly the top five rows of the board are shown row is complete linewhich means that all the rows above it (row and must be --pulled down|firstrow is copied down to row the board o... |
10,719 | the line was being removed and the rows being pulled down that the variable changed at all so on the next iterationthe variable is pointing to the same row as before this is needed because if there were two complete linesthen the second complete line would have been pulled down and would also have to be removed the cod... |
10,720 | with the return values from converttopixelcoords(this call gets the pixel coordinates of the board coordinates specified by boxx and boxy the code won' fill the entire box' space with color to have black outline in between the boxes of piecethe left and top parameters in the pygame draw rect(call have added to them and... |
10,721 | the drawstatus(function is responsible for rendering the text for the --score:|and --level:|information that appears in the upper right of the corner of the screen drawing piece on the board or elsewhere on the screen def drawpiece(piecepixelx=nonepixely=none) shapetodraw shapes[piece['shape']][piece['rotation'] if pix... |
10,722 | if __name__ ='__main__' main(the drawnextpiece(draws the --next|piece in the upper right corner of the screen it does this by calling the drawpiece(function and passing in arguments for drawpiece()' pixelx and pixely parameters that' the last function line and are run after all the function definitions have been execut... |
10,723 | these variations can be downloaded from |
10,724 | squirrel eat squirrel how to play squirrel eat squirrel squirrel eat squirrel is loosely based on the game --katamari damacy|the player controls small squirrel that must hop around the screen eating smaller squirrels and avoiding larger squirrels each time the player' squirrel eats squirrel that is smaller than itit gr... |
10,725 | all the objects have the following keys in their dictionary value' '' 'and 'rectthe 'xand 'ykey' value give the coordinates of the top left of the object in game world coordinates these are different from pixel coordinates (which is what the 'rectkey' value tracksthe difference between game world and pixel coordinates ... |
10,726 | cameraslack how far from the center the squirrel moves before moving the camera moverate how fast the player moves bouncerate how fast the player bounces (large is slower bounceheight how high the player bounces startsize how big the player starts off winsize how big the player needs to be to win invulntime how long th... |
10,727 | 'surfacethe pygame surface object that stores the image of the squirrel which will be drawn to the screen 'movexhow many pixels per frame the squirrel moves horizontally negative integer is moving to the lefta positive to the right 'moveyhow many pixels per frame the squirrel moves vertically negative integer is moving... |
10,728 | winmode false if the player has won create the surfaces to hold game text gameoversurf basicfont render('game over'truewhite gameoverrect gameoversurf get_rect( gameoverrect center (half_winwidthhalf_winheight winsurf basicfont render('you have achieved omega squirrel!'truewhite winrect winsurf get_rect( winrect center... |
10,729 | if invulnerablemode and time time(invulnerablestarttime invulntime invulnerablemode false move all the squirrels for sobj in squirrelobjs move the squirreland adjust for their bounce sobj[' '+sobj['movex' sobj[' '+sobj['movey' sobj['bounce'+ if sobj['bounce'sobj['bouncerate'] sobj['bounce' reset bounce amount random ch... |
10,730 | if (cameray half_winheightplayercentery cameraslack cameray playercentery cameraslack half_winheight elif playercentery (cameray half_winheightcameraslack cameray playercentery cameraslack half_winheight draw the green background displaysurf fill(grasscolor draw all the grass objects on the screen for gobj in grassobjs... |
10,731 | if event key in (k_upk_w) movedown false moveup true elif event key in (k_downk_s) moveup false movedown true elif event key in (k_leftk_a) moveright false moveleft true if playerobj['facing'=rightchange player image playerobj['surface'pygame transform scale(l_squir_img(playerobj['size']playerobj['size']) playerobj['fa... |
10,732 | playerobj[' '+moverate if (moveleft or moveright or moveup or movedownor playerobj['bounce'! playerobj['bounce'+ if playerobj['bounce'bouncerate playerobj['bounce' reset bounce amount check if the player has collided with any squirrels for in range(len(squirrelobjs)- - - ) sqobj squirrelobjs[ if 'rectin sqobj and playe... |
10,733 | check if the player has won if winmode displaysurf blit(winsurfwinrect displaysurf blit(winsurf winrect pygame display update( fpsclock tick(fps def drawhealthmeter(currenthealth) for in range(currenthealth)draw red health bars pygame draw rect(displaysurfred( ( maxhealthi ) for in range(maxhealth)draw the white outlin... |
10,734 | random randint(camerax winwidthcamerax ( winwidth) random randint(cameray winheightcameray ( winheight) create rect object with the random coordinates and use colliderect( to make sure the right edge isn' in the camera view objrect pygame rect(xyobjwidthobjheight if not objrect colliderect(camerarect) return xy def mak... |
10,735 | half-window length beyond the edge of the window boundsleftedge camerax winwidth boundstopedge cameray winheight boundsrect pygame rect(boundsleftedgeboundstopedgewinwidth winheight objrect pygame rect(obj[' ']obj[' ']obj['width']obj['height'] return not boundsrect colliderect(objrect if __name__ ='__main__' main(the u... |
10,736 | bounceheight how high the player bounces startsize how big the player starts off winsize how big the player needs to be to win invulntime how long the player is invulnerable after being hit in seconds gameovertime how long the "game overtext stays on the screen in seconds maxhealth how much health the player starts wit... |
10,737 | 'surfacethe pygame surface object that stores the image of the squirrel which will be drawn to the screen 'movexhow many pixels per frame the squirrel moves horizontally negative integer is moving to the lefta positive to the right 'moveyhow many pixels per frame the squirrel moves vertically negative integer is moving... |
10,738 | the pygame transform flip(function load the image files l_squir_img pygame image load('squirrel png'r_squir_img pygame transform flip(l_squir_imgtruefalsegrassimages [for in range( )grassimages append(pygame image load('grass% pngi)the image for the player and enemy squirrels is loaded from squirrel png on line make su... |
10,739 | invulnerablemode false if the player is invulnerable invulnerablestarttime time the player became invulnerable gameovermode false if the player has lost gameoverstarttime time the player lost winmode false if the player has won the squirrel eat squirrel game has quite few variables that track the game state these varia... |
10,740 | as you can seethe game world xy coordinates keep getting bigger and smaller forever the game world origin is where the ( game world coordinates are you can see that the three squirrels are located (in game world coordinatesat (- - )( )and ( - but we can only display pixel area on the screen (though this can change if w... |
10,741 | the area that the camera can see (called the camera viewhas it' center (that isits originat the game world coordinates (- - since what the camera sees is displayed on the player' screenthe --camera|coordinates are the same as the --pixel|coordinates to find out the pixel coordinates of the squirrels (that iswhere on th... |
10,742 | calculating if something is in the active area or not is explained in the isoutsideactivearea(function' explanation later in this when we create new enemy squirrel or grass objectswe don' want them to be created inside the view of the camerasince it'll appear that they just pop out of nowhere but we also don' want to c... |
10,743 | starting off with some grass start off with some random grass images on the screen for in range( )grassobjs append(makenewgrass(cameraxcameray)grassobjs[ ][' 'random randint( winwidthgrassobjs[ ][' 'random randint( winheightthe active area should start off with few grass objects visible on the screen the makenewgrass(f... |
10,744 | move left or up the larger the valuethe farther they move on each iteration through the game loop (which means they move fasterthe for loop on line will apply this moving code to each of the enemy squirrel objects in the squirrelobjs list firstline and will adjust their 'xand 'ykeysvalues sobj['bounce'+ if sobj['bounce... |
10,745 | removing the far away grass and squirrel objects go through all the objects and see if any need to be deleted for in range(len(grassobjs - - )if isoutsideactivearea(cameraxcameraygrassobjs[ ])del grassobjs[ifor in range(len(squirrelobjs - - )if isoutsideactivearea(cameraxcameraysquirrelobjs[ ])del squirrelobjs[iduring ... |
10,746 | file ""line in indexerrorlist index out of range to see why this error happenslet' walk through the code firstthe animals list would be set to ['cat''mouse''dog''horse'and len(animalswould return this means that the call to range( would cause the for loop to iterate with the values and when the for loop iterates with s... |
10,747 | adding new grass and squirrel objects add more grass squirrels if we don' have enough while len(grassobjsnumgrassgrassobjs append(makenewgrass(cameraxcameray)while len(squirrelobjsnumsquirrelssquirrelobjs append(makenewsquirrel(cameraxcameray)remember that the numgrass constant was set to and the numsquirrels constant ... |
10,748 | camera than the camera slack should allow the camerax value needs to be updated so that the player squirrel is just at the edge of the camera slack this is why line sets camerax to playercenterx cameraslack half_winwidth note that the camerax variable is changednot the playerobj[' 'value we want to move the cameranot t... |
10,749 | displaysurf blit(sobj['surface']sobj['rect']the for loop that draws all the enemy squirrel game objects is similar to the previous for loopexcept that the rect object it creates is saved in the 'rectkey' value of the squirrel dictionary the reason the code does this is because we will use this rect object later to chec... |
10,750 | in facttime time(will keep returning values that will end up putting false into flashison until which is the next tenth second this is why the flashison variable will constantly have false for one tenth of secondand then true for the next one tenth of second (no matter how many iterations happen in that tenth of second... |
10,751 | moveup false movedown true if the up or down arrow keys have been pressed (or their wasd equivalents)then the move variable (moverightmovedownetc for that direction should be set to true and the move variable for the opposite direction should be set to false elif event key in (k_leftk_a) moveright false moveleft true i... |
10,752 | elif event key in (k_rightk_d)moveright false elif event key in (k_upk_w)moveup false elif event key in (k_downk_s)movedown false if the player lets up on any of the arrow or wasd keysthen the code should set the move variable for that direction to false this will stop the squirrel from moving in that direction any mor... |
10,753 | the value in playerobj['bounce'keeps track of at what point in bouncing the player is at this variable stores an integer value from to bouncerate just like the bounce value for the enemy squirrelsa playerobj['bounce'value of means the player squirrel is at the start of bounce and value of bouncerate means the player sq... |
10,754 | key in the player object (that isthe growthis calculated based on the enemy squirrel' size on line here' graph showing the growth from different sized squirrels notice that larger squirrels cause more growthint(sqobj['width'sqobj['height'])** growth size of eaten squirrel (width heightsoaccording to the charteating squ... |
10,755 | the way the player wins the game is by getting the squirrel to have size larger than the integer stored in the winsize constant variable if this is truethen the winmode variable is set to true code in the other parts of this function will handle displaying the congratulations text and checking for the player to press t... |
10,756 | this lets the enemy squirrels continue to be animated and moving around for few seconds after the player dies and before the next game starts the --game over screen|in squirrel eat squirrel does not wait until the player presses key before new game starts winning check if the player has won if winmodedisplaysurf blit(w... |
10,757 | the terminate(function works the same as in the previous game programs the mathematics of the sine function def getbounceamount(currentbouncebounceratebounceheight) returns the number of pixels to offset based on the bounce larger bouncerate means slower bounce larger bounceheight means higher bounce currentbounce will... |
10,758 | values returned by math sin( math sin(arg - - - arg you can kind of see wavy pattern in the values returned by math sin(if you figure out the sine values for more numbers besides integers (for example and and so onand then connect the dots with linesyou can see this wavy pattern more easilyvalues returned by math sin( ... |
10,759 | notice that math sin( returns then gradually increases until math sin( returns then it begins to decrease until math sin( returns the number is special number in mathematics called pi (pronounced the same as delicious --pie||this value is also stored in the constant variable pi in the math module (which is why line use... |
10,760 | as playerobj['bounce'gets its value incrementedthe getbounceamount(function will return values that have the same bounce shape that the sine wave has from to if you want to make the bounce higherthan increase the bounceheight constant if you want to make the bounce slowerthan increase the bouncerate constant the sine f... |
10,761 | not everyone will always be running the latest version of software and you want to ensure that the code you write works with as many computers as possible you can' always make your python code backwards compatible with python but if it' possible then you should do it otherwisewhen people with python try to run your gam... |
10,762 | represents the area of the camera (using cameraxcameraywinwidthand winheight constantsnextwe randomly generate numbers for the xy coordinates that would be within the active area the active area' left and top edge are winwidth and winheight pixels to the left and up of camerax and cameray so the active area' left and t... |
10,763 | squirrel aren' too different from each other otherwiseusing completely random numbers for width and height could give us very tall and skinny squirrels or very short and wide squirrels the width and height of the squirrel are this general size with random number from to added to it (for slight variation)and then multip... |
10,764 | the grass game objects are dictionaries with the usual ' '' ''width''height'and 'rectkeys but also 'grassimagekey which is number from to one less than the length of the grassimages list this number will determine what image the grass game object has for exampleif the value of the grass object' 'grassimagekey is then i... |
10,765 | since the player squirrelenemy squirrel and grass objects all have ' '' ''widthand 'heightkeysthe isoutsideactivearea(code can work with any type of those game objects if __name__ ='__main__' main(finallyafter all the functions have been definedthe program will run the main(function and start the game summary squirrel ... |
10,766 | star pusher how to play star pusher star pusher is sokoban or --box pusher|clone the player is in room with several stars there are star marks on the grounds of some of the tile sprites in the room the player must figure out how to push the stars on top of the tiles with star marks the player cannot push star if there ... |
10,767 | book the level file can be downloaded from downloaded from alsojust like the squirrelgrassand enemy --objects|in the squirrel eat squirrel gamewhen say --map objects||--game state objects||or --level objects|in this do not mean objects in the object-oriented programming sense these --objects|are really just dictionary ... |
10,768 | def main() global fpsclockdisplaysurfimagesdicttilemappingoutsidedecomappingbasicfontplayerimagescurrentimage pygame initialization and basic set up of the global variables pygame init( fpsclock pygame time clock( because the surface object stored in displaysurf was returned from the pygame display set_mode(functionthi... |
10,769 | outsidedecomapping {' 'imagesdict['rock'] ' 'imagesdict['short tree'] ' 'imagesdict['tall tree'] ' 'imagesdict['ugly tree'] playerimages is list of all possible characters the player can be currentimage is the index of the player' current player image currentimage playerimages [imagesdict['princess'] imagesdict['boy'] ... |
10,770 | mapobj decoratemap(levelobj['mapobj']levelobj['startstate']['player'] gamestateobj copy deepcopy(levelobj['startstate'] mapneedsredraw true set to true to call drawmap( levelsurf basicfont render('level % of % (levelobj['levelnum' totalnumoflevels) textcolor levelrect levelsurf get_rect( levelrect bottomleft ( winheigh... |
10,771 | set the camera move mode elif event key =k_acameraleft true elif event key =k_dcameraright true elif event key =k_wcameraup true elif event key =k_scameradown true elif event key =k_nreturn 'nextelif event key =k_breturn 'backelif event key =k_escapeterminate(esc key quits elif event key =k_backspacereturn 'resetreset ... |
10,772 | mapneedsredraw true if islevelfinished(levelobjgamestateobj) level is solvedwe should show the "solved!image leveliscomplete true keypressed false displaysurf fill(bgcolor if mapneedsredraw mapsurf drawmap(mapobjgamestateobjlevelobj['goals'] mapneedsredraw false if cameraup and cameraoffsety max_cam_x_pan cameraoffsety... |
10,773 | pygame display update(draw displaysurf to the screen fpsclock tick( def decoratemap(mapobjstartxy) """makes copy of the given map object and modifies it here is what is done to it walls that are corners are turned into corner pieces the outside/inside floor tile distinction is made tree/rock decorations are randomly ad... |
10,774 | mapobjcopy[ ][yrandom choice(list(outsidedecomapping keys()) return mapobjcopy def isblocked(mapobjgamestateobjxy) """returns true if the (xyposition on the map is blocked by wall or starotherwise return false "" if iswall(mapobjxy) return true elif len(mapobjor len(mapobj[ ]) return true and aren' actually on the map ... |
10,775 | xoffset yoffset elif playermoveto =left xoffset - yoffset see if the player can move in that direction if iswall(mapobjplayerx xoffsetplayery yoffset) return false else if (playerx xoffsetplayery yoffsetin stars there is star in the waysee if the player can push it if not isblocked(mapobjgamestateobjplayerx (xoffset* )... |
10,776 | displaysurf fill(bgcolor draw the title image to the window displaysurf blit(imagesdict['title']titlerect position and draw the text for in range(len(instructiontext)) instsurf basicfont render(instructiontext[ ] textcolor instrect instsurf get_rect( topcoord + pixels will go in between each line of text instrect top t... |
10,777 | ignore the linesthey're comments in the level file line line[:line find(';')if line !''this line is part of the map maptextlines append(lineelif line ='and len(maptextlines blank line indicates the end of level' map in the file convert the text in maptextlines into level object find the longest row in the map maxwidth ... |
10,778 | basic level design sanity checks assert startx !none and starty !none'level % (around line %sin % is missing "@or "+to mark the start point (levelnum+ linenumfilename assert len(goals 'level % (around line %sin % must have at least one goal (levelnum+ linenumfilename assert len(stars>len(goals)'level % (around line %si... |
10,779 | floodfill(mapobjx- yoldcharacternewcharactercall left if len(mapobj[ ] and mapobj[ ][ + =oldcharacter floodfill(mapobjxy+ oldcharacternewcharactercall down if and mapobj[ ][ - =oldcharacter floodfill(mapobjxy- oldcharacternewcharactercall up def drawmap(mapobjgamestateobjgoals) """draws the map to surface objectincludi... |
10,780 | last draw the player on the board if (xy=gamestateobj['player'] notethe value "currentimagerefers to key in "playerimageswhich has the specific player image we want to show mapsurf blit(playerimages[currentimage]spacerect return mapsurf def islevelfinished(levelobjgamestateobj) """returns true if all the goals have sta... |
10,781 | tileheight tilefloorheight cam_move_speed how many pixels per frame the camera moves the percentage of outdoor tiles that have additional decoration on themsuch as tree or rock outside_decoration_pct brightblue white ( bgcolor brightblue textcolor white up 'up down 'down left 'left right 'rightthese constants are used ... |
10,782 | from the pygame display set_mode(functionthis is the surface object that is drawn to the actual computer screen when pygame display update(is called displaysurf pygame display set_mode((winwidthwinheight)pygame display set_caption('star pusher'basicfont pygame font font('freesansbold ttf' this is the usual pygame setup... |
10,783 | the data structure for the map is just list of single character strings the tilemapping dictionary links the characters used in this map data structure to the images that they represent (this will become more clear in the drawmap(function' explanation outsidedecomapping {' 'imagesdict['rock']' 'imagesdict['short tree']... |
10,784 | result runlevel(levelscurrentlevelindexthe runlevel(function handles all the action for the game it is passed list of level objectsand the integer index of the level in that list to be played when the player has finished playing the levelrunlevel(will return one of the following strings'solved(because the player has fi... |
10,785 | def runlevel(levelslevelnum) global currentimage levelobj levels[levelnum mapobj decoratemap(levelobj['mapobj']levelobj['startstate']['player'] gamestateobj copy deepcopy(levelobj['startstate']the levels list contains all the level objects that were loaded from the level file the level object for the current level (whi... |
10,786 | cameraoffsety track if the keys to move the camera are being held downcameraup false cameradown false cameraleft false cameraright false more variables are set at the start of playing level the mapwidth and mapheight variables are the size of the maps in pixels the expression for calculating mapheight is bit complicate... |
10,787 | playermoveto up elif event key =k_downplayermoveto down set the camera move mode elif event key =k_acameraleft true elif event key =k_dcameraright true elif event key =k_wcameraup true elif event key =k_scameradown true elif event key =k_nreturn 'nextelif event key =k_breturn 'backelif event key =k_escapeterminate(esc ... |
10,788 | (if possibleand push any stars that are pushable moved makemove(mapobjgamestateobjplayermovetoif movedincrement the step counter gamestateobj['stepcounter'+ mapneedsredraw true if islevelfinished(levelobjgamestateobj)level is solvedwe should show the "solved!image leveliscomplete true keypressed false if the playermove... |
10,789 | cameraoffsety -cam_move_speed if cameraleft and cameraoffsetx max_cam_y_pancameraoffsetx +cam_move_speed elif cameraright and cameraoffsetx -max_cam_y_pancameraoffsetx -cam_move_speed if the camera movement variables are set to true and the camera has not gone past ( panned passedthe boundaries set by the max_cam_x_pan... |
10,790 | lines to position the camera and draw the map and other graphics to the display surface object in displaysurf if the level is solvedthen the victory graphic is also drawn on top of everything else the keypressed variable will be set to true if the user pressed key during this iterationat which point the runlevel(functi... |
10,791 | mapobjcopy[ ][ythe map object has characters that represent the position of the playergoalsand stars these are necessary for the map object (they're stored in other data structures after the map file is readso they are converted to blank spaces flood fill to determine inside/outside floor tiles floodfill(mapobjcopystar... |
10,792 | if iswall(mapobjxy)return true elif len(mapobjor len(mapobj[ ])return true and aren' actually on the map elif (xyin gamestateobj['stars']return true star is blocking return false there are three cases where space on the map would be blockedif there is stara wallor the coordinates of the space are past the edges of the ... |
10,793 | see if the player can move in that direction if iswall(mapobjplayerx xoffsetplayery yoffset) return false else if (playerx xoffsetplayery yoffsetin stars there is star in the waysee if the player can push it if not isblocked(mapobjgamestateobjplayerx (xoffset* )playery (yoffset* )) move the star ind stars index((player... |
10,794 | timeso we can' use strings with \ newline characters in them so we will use list with each line in it instructiontext ['push the stars over the marks ' 'arrow keys to movewasd for camera controlp to change character ' 'backspace to reset levelesc to quit ' ' for next levelb to go back level 'the startscreen(function ne... |
10,795 | if event type =quitterminate(elif event type =keydownif event key =k_escapeterminate(return user has pressed keyso return display the displaysurf contents to the actual screen pygame display update(fpsclock tick(there is game loop in startscreen(that begins on line and handles events that indicate if the program should... |
10,796 | '+ space with goal and the starting player' space '* space with goal and star at the start of the level grassy outdoor space 'oan inside floor space (this is lowercase letter onot zero ' rock on grass ' short tree on grass ' tall tree on grass ' an ugly tree on grass the "levelsdata structure the level object contains ... |
10,797 | only deal with text files writing to files to create filecall the open(function pass it two argumentsa string for the name of the fileand the string 'wto tell the open(function you want to open the file in --write|mode the open(function returns file objecttextfile open('hello txt'' 'if you run this code from the intera... |
10,798 | reading from files to read the content of filepass the string 'rinstead of 'wto the open(function then call the readlines(method on the file object to read in the contents of the file lastclose the file by calling the close(method textfile open('hello txt'' 'content textfile readlines(textfile close(the readlines(metho... |
10,799 | by al sweigart al@inventwithpython com everything after the is comment and will be ignored by the game that reads in this file the format is described atthe starting position of the player the starting position for pushable star goal where star needs to be pushed player goal star goal (spacean empty open space wall lev... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.